sqlite3.c 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706151707151708151709151710151711151712151713151714151715151716151717151718151719151720151721151722151723151724151725151726151727151728151729151730151731151732151733151734151735151736151737151738151739151740151741151742151743151744151745151746151747151748151749151750151751151752151753151754151755151756151757151758151759151760151761151762151763151764151765151766151767151768151769151770151771151772151773151774151775151776151777151778151779151780151781151782151783151784151785151786151787151788151789151790151791151792151793151794151795151796151797151798151799151800151801151802151803151804151805151806151807151808151809151810151811151812151813151814151815151816151817151818151819151820151821151822151823151824151825151826151827151828151829151830151831151832151833151834151835151836151837151838151839151840151841151842151843151844151845151846151847151848151849151850151851151852151853151854151855151856151857151858151859151860151861151862151863151864151865151866151867151868151869151870151871151872151873151874151875151876151877151878151879151880151881151882151883151884151885151886151887151888151889151890151891151892151893151894151895151896151897151898151899151900151901151902151903151904151905151906151907151908151909151910151911151912151913151914151915151916151917151918151919151920151921151922151923151924151925151926151927151928151929151930151931151932151933151934151935151936151937151938151939151940151941151942151943151944151945151946151947151948151949151950151951151952151953151954151955151956151957151958151959151960151961151962151963151964151965151966151967151968151969151970151971151972151973151974151975151976151977151978151979151980151981151982151983151984151985151986151987151988151989151990151991151992151993151994151995151996151997151998151999152000152001152002152003152004152005152006152007152008152009152010152011152012152013152014152015152016152017152018152019152020152021152022152023152024152025152026152027152028152029152030152031152032152033152034152035152036152037152038152039152040152041152042152043152044152045152046152047152048152049152050152051152052152053152054152055152056152057152058152059152060152061152062152063152064152065152066152067152068152069152070152071152072152073152074152075152076152077152078152079152080152081152082152083152084152085152086152087152088152089152090152091152092152093152094152095152096152097152098152099152100152101152102152103152104152105152106152107152108152109152110152111152112152113152114152115152116152117152118152119152120152121152122152123152124152125152126152127152128152129152130152131152132152133152134152135152136152137152138152139152140152141152142152143152144152145152146152147152148152149152150152151152152152153152154152155152156152157152158152159152160152161152162152163152164152165152166152167152168152169152170152171152172152173152174152175152176152177152178152179152180152181152182152183152184152185152186152187152188152189152190152191152192152193152194152195152196152197152198152199152200152201152202152203152204152205152206152207152208152209152210152211152212152213152214152215152216152217152218152219152220152221152222152223152224152225152226152227152228152229152230152231152232152233152234152235152236152237152238152239152240152241152242152243152244152245152246152247152248152249152250152251152252152253152254152255152256152257152258152259152260152261152262152263152264152265152266152267152268152269152270152271152272152273152274152275152276152277152278152279152280152281152282152283152284152285152286152287152288152289152290152291152292152293152294152295152296152297152298152299152300152301152302152303152304152305152306152307152308152309152310152311152312152313152314152315152316152317152318152319152320152321152322152323152324152325152326152327152328152329152330152331152332152333152334152335152336152337152338152339152340152341152342152343152344152345152346152347152348152349152350152351152352152353152354152355152356152357152358152359152360152361152362152363152364152365152366152367152368152369152370152371152372152373152374152375152376152377152378152379152380152381152382152383152384152385152386152387152388152389152390152391152392152393152394152395152396152397152398152399152400152401152402152403152404152405152406152407152408152409152410152411152412152413152414152415152416152417152418152419152420152421152422152423152424152425152426152427152428152429152430152431152432152433152434152435152436152437152438152439152440152441152442152443152444152445152446152447152448152449152450152451152452152453152454152455152456152457152458152459152460152461152462152463152464152465152466152467152468152469152470152471152472152473152474152475152476152477152478152479152480152481152482152483152484152485152486152487152488152489152490152491152492152493152494152495152496152497152498152499152500152501152502152503152504152505152506152507152508152509152510152511152512152513152514152515152516152517152518152519152520152521152522152523152524152525152526152527152528152529152530152531152532152533152534152535152536152537152538152539152540152541152542152543152544152545152546152547152548152549152550152551152552152553152554152555152556152557152558152559152560152561152562152563152564152565152566152567152568152569152570152571152572152573152574152575152576152577152578152579152580152581152582152583152584152585152586152587152588152589152590152591152592152593152594152595152596152597152598152599152600152601152602152603152604152605152606152607152608152609152610152611152612152613152614152615152616152617152618152619152620152621152622152623152624152625152626152627152628152629152630152631152632152633152634152635152636152637152638152639152640152641152642152643152644152645152646152647152648152649152650152651152652152653152654152655152656152657152658152659152660152661152662152663152664152665152666152667152668152669152670152671152672152673152674152675152676152677152678152679152680152681152682152683152684152685152686152687152688152689152690152691152692152693152694152695152696152697152698152699152700152701152702152703152704152705152706152707152708152709152710152711152712152713152714152715152716152717152718152719152720152721152722152723152724152725152726152727152728152729152730152731152732152733152734152735152736152737152738152739152740152741152742152743152744152745152746152747152748152749152750152751152752152753152754152755152756152757152758152759152760152761152762152763152764152765152766152767152768152769152770152771152772152773152774152775152776152777152778152779152780152781152782152783152784152785152786152787152788152789152790152791152792152793152794152795152796152797152798152799152800152801152802152803152804152805152806152807152808152809152810152811152812152813152814152815152816152817152818152819152820152821152822152823152824152825152826152827152828152829152830152831152832152833152834152835152836152837152838152839152840152841152842152843152844152845152846152847152848152849152850152851152852152853152854152855152856152857152858152859152860152861152862152863152864152865152866152867152868152869152870152871152872152873152874152875152876152877152878152879152880152881152882152883152884152885152886152887152888152889152890152891152892152893152894152895152896152897152898152899152900152901152902152903152904152905152906152907152908152909152910152911152912152913152914152915152916152917152918152919152920152921152922152923152924152925152926152927152928152929152930152931152932152933152934152935152936152937152938152939152940152941152942152943152944152945152946152947152948152949152950152951152952152953152954152955152956152957152958152959152960152961152962152963152964152965152966152967152968152969152970152971152972152973152974152975152976152977152978152979152980152981152982152983152984152985152986152987152988152989152990152991152992152993152994152995152996152997152998152999153000153001153002153003153004153005153006153007153008153009153010153011153012153013153014153015153016153017153018153019153020153021153022153023153024153025153026153027153028153029153030153031153032153033153034153035153036153037153038153039153040153041153042153043153044153045153046153047153048153049153050153051153052153053153054153055153056153057153058153059153060153061153062153063153064153065153066153067153068153069153070153071153072153073153074153075153076153077153078153079153080153081153082153083153084153085153086153087153088153089153090153091153092153093153094153095153096153097153098153099153100153101153102153103153104153105153106153107153108153109153110153111153112153113153114153115153116153117153118153119153120153121153122153123153124153125153126153127153128153129153130153131153132153133153134153135153136153137153138153139153140153141153142153143153144153145153146153147153148153149153150153151153152153153153154153155153156153157153158153159153160153161153162153163153164153165153166153167153168153169153170153171153172153173153174153175153176153177153178153179153180153181153182153183153184153185153186153187153188153189153190153191153192153193153194153195153196153197153198153199153200153201153202153203153204153205153206153207153208153209153210153211153212153213153214153215153216153217153218153219153220153221153222153223153224153225153226153227153228153229153230153231153232153233153234153235153236153237153238153239153240153241153242153243153244153245153246153247153248153249153250153251153252153253153254153255153256153257153258153259153260153261153262153263153264153265153266153267153268153269153270153271153272153273153274153275153276153277153278153279153280153281153282153283153284153285153286153287153288153289153290153291153292153293153294153295153296153297153298153299153300153301153302153303153304153305153306153307153308153309153310153311153312153313153314153315153316153317153318153319153320153321153322153323153324153325153326153327153328153329153330153331153332153333153334153335153336153337153338153339153340153341153342153343153344153345153346153347153348153349153350153351153352153353153354153355153356153357153358153359153360153361153362153363153364153365153366153367153368153369153370153371153372153373153374153375153376153377153378153379153380153381153382153383153384153385153386153387153388153389153390153391153392153393153394153395153396153397153398153399153400153401153402153403153404153405153406153407153408153409153410153411153412153413153414153415153416153417153418153419153420153421153422153423153424153425153426153427153428153429153430153431153432153433153434153435153436153437153438153439153440153441153442153443153444153445153446153447153448153449153450153451153452153453153454153455153456153457153458153459153460153461153462153463153464153465153466153467153468153469153470153471153472153473153474153475153476153477153478153479153480153481153482153483153484153485153486153487153488153489153490153491153492153493153494153495153496153497153498153499153500153501153502153503153504153505153506153507153508153509153510153511153512153513153514153515153516153517153518153519153520153521153522153523153524153525153526153527153528153529153530153531153532153533153534153535153536153537153538153539153540153541153542153543153544153545153546153547153548153549153550153551153552153553153554153555153556153557153558153559153560153561153562153563153564153565153566153567153568153569153570153571153572153573153574153575153576153577153578153579153580153581153582153583153584153585153586153587153588153589153590153591153592153593153594153595153596153597153598153599153600153601153602153603153604153605153606153607153608153609153610153611153612153613153614153615153616153617153618153619153620153621153622153623153624153625153626153627153628153629153630153631153632153633153634153635153636153637153638153639153640153641153642153643153644153645153646153647153648153649153650153651153652153653153654153655153656153657153658153659153660153661153662153663153664153665153666153667153668153669153670153671153672153673153674153675153676153677153678153679153680153681153682153683153684153685153686153687153688153689153690153691153692153693153694153695153696153697153698153699153700153701153702153703153704153705153706153707153708153709153710153711153712153713153714153715153716153717153718153719153720153721153722153723153724153725153726153727153728153729153730153731153732153733153734153735153736153737153738153739153740153741153742153743153744153745153746153747153748153749153750153751153752153753153754153755153756153757153758153759153760153761153762153763153764153765153766153767153768153769153770153771153772153773153774153775153776153777153778153779153780153781153782153783153784153785153786153787153788153789153790153791153792153793153794153795153796153797153798153799153800153801153802153803153804153805153806153807153808153809153810153811153812153813153814153815153816153817153818153819153820153821153822153823153824153825153826153827153828153829153830153831153832153833153834153835153836153837153838153839153840153841153842153843153844153845153846153847153848153849153850153851153852153853153854153855153856153857153858153859153860153861153862153863153864153865153866153867153868153869153870153871153872153873153874153875153876153877153878153879153880153881153882153883153884153885153886153887153888153889153890153891153892153893153894153895153896153897153898153899153900153901153902153903153904153905153906153907153908153909153910153911153912153913153914153915153916153917153918153919153920153921153922153923153924153925153926153927153928153929153930153931153932153933153934153935153936153937153938153939153940153941153942153943153944153945153946153947153948153949153950153951153952153953153954153955153956153957153958153959153960153961153962153963153964153965153966153967153968153969153970153971153972153973153974153975153976153977153978153979153980153981153982153983153984153985153986153987153988153989153990153991153992153993153994153995153996153997153998153999154000154001154002154003154004154005154006154007154008154009154010154011154012154013154014154015154016154017154018154019154020154021154022154023154024154025154026154027154028154029154030154031154032154033154034154035154036154037154038154039154040154041154042154043154044154045154046154047154048154049154050154051154052154053154054154055154056154057154058154059154060154061154062154063154064154065154066154067154068154069154070154071154072154073154074154075154076154077154078154079154080154081154082154083154084154085154086154087154088154089154090154091154092154093154094154095154096154097154098154099154100154101154102154103154104154105154106154107154108154109154110154111154112154113154114154115154116154117154118154119154120154121154122154123154124154125154126154127154128154129154130154131154132154133154134154135154136154137154138154139154140154141154142154143154144154145154146154147154148154149154150154151154152154153154154154155154156154157154158154159154160154161154162154163154164154165154166154167154168154169154170154171154172154173154174154175154176154177154178154179154180154181154182154183154184154185154186154187154188154189154190154191154192154193154194154195154196154197154198154199154200154201154202154203154204154205154206154207154208154209154210154211154212154213154214154215154216154217154218154219154220154221154222154223154224154225154226154227154228154229154230154231154232154233154234154235154236154237154238154239154240154241154242154243154244154245154246154247154248154249154250154251154252154253154254154255154256154257154258154259154260154261154262154263154264154265154266154267154268154269154270154271154272154273154274154275154276154277154278154279154280154281154282154283154284154285154286154287154288154289154290154291154292154293154294154295154296154297154298154299154300154301154302154303154304154305154306154307154308154309154310154311154312154313154314154315154316154317154318154319154320154321154322154323154324154325154326154327154328154329154330154331154332154333154334154335154336154337154338154339154340154341154342154343154344154345154346154347154348154349154350154351154352154353154354154355154356154357154358154359154360154361154362154363154364154365154366154367154368154369154370154371154372154373154374154375154376154377154378154379154380154381154382154383154384154385154386154387154388154389154390154391154392154393154394154395154396154397154398154399154400154401154402154403154404154405154406154407154408154409154410154411154412154413154414154415154416154417154418154419154420154421154422154423154424154425154426154427154428154429154430154431154432154433154434154435154436154437154438154439154440154441154442154443154444154445154446154447154448154449154450154451154452154453154454154455154456154457154458154459154460154461154462154463154464154465154466154467154468154469154470154471154472154473154474154475154476154477154478154479154480154481154482154483154484154485154486154487154488154489154490154491154492154493154494154495154496154497154498154499154500154501154502154503154504154505154506154507154508154509154510154511154512154513154514154515154516154517154518154519154520154521154522154523154524154525154526154527154528154529154530154531154532154533154534154535154536154537154538154539154540154541154542154543154544154545154546154547154548154549154550154551154552154553154554154555154556154557154558154559154560154561154562154563154564154565154566154567154568154569154570154571154572154573154574154575154576154577154578154579154580154581154582154583154584154585154586154587154588154589154590154591154592154593154594154595154596154597154598154599154600154601154602154603154604154605154606154607154608154609154610154611154612154613154614154615154616154617154618154619154620154621154622154623154624154625154626154627154628154629154630154631154632154633154634154635154636154637154638154639154640154641154642154643154644154645154646154647154648154649154650154651154652154653154654154655154656154657154658154659154660154661154662154663154664154665154666154667154668154669154670154671154672154673154674154675154676154677154678154679154680154681154682154683154684154685154686154687154688154689154690154691154692154693154694154695154696154697154698154699154700154701154702154703154704154705154706154707154708154709154710154711154712154713154714154715154716154717154718154719154720154721154722154723154724154725154726154727154728154729154730154731154732154733154734154735154736154737154738154739154740154741154742154743154744154745154746154747154748154749154750154751154752154753154754154755154756154757154758154759154760154761154762154763154764154765154766154767154768154769154770154771154772154773154774154775154776154777154778154779154780154781154782154783154784154785154786154787154788154789154790154791154792154793154794154795154796154797154798154799154800154801154802154803154804154805154806154807154808154809154810154811154812154813154814154815154816154817154818154819154820154821154822154823154824154825154826154827154828154829154830154831154832154833154834154835154836154837154838154839154840154841154842154843154844154845154846154847154848154849154850154851154852154853154854154855154856154857154858154859154860154861154862154863154864154865154866154867154868154869154870154871154872154873154874154875154876154877154878154879154880154881154882154883154884154885154886154887154888154889154890154891154892154893154894154895154896154897154898154899154900154901154902154903154904154905154906154907154908154909154910154911154912154913154914154915154916154917154918154919154920154921154922154923154924154925154926154927154928154929154930154931154932154933154934154935154936154937154938154939154940154941154942154943154944154945154946154947154948154949154950154951154952154953154954154955154956154957154958154959154960154961154962154963154964154965154966154967154968154969154970154971154972154973154974154975154976154977154978154979154980154981154982154983154984154985154986154987154988154989154990154991154992154993154994154995154996154997154998154999155000155001155002155003155004155005155006155007155008155009155010155011155012155013155014155015155016155017155018155019155020155021155022155023155024155025155026155027155028155029155030155031155032155033155034155035155036155037155038155039155040155041155042155043155044155045155046155047155048155049155050155051155052155053155054155055155056155057155058155059155060155061155062155063155064155065155066155067155068155069155070155071155072155073155074155075155076155077155078155079155080155081155082155083155084155085155086155087155088155089155090155091155092155093155094155095155096155097155098155099155100155101155102155103155104155105155106155107155108155109155110155111155112155113155114155115155116155117155118155119155120155121155122155123155124155125155126155127155128155129155130155131155132155133155134155135155136155137155138155139155140155141155142155143155144155145155146155147155148155149155150155151155152155153155154155155155156155157155158155159155160155161155162155163155164155165155166155167155168155169155170155171155172155173155174155175155176155177155178155179155180155181155182155183155184155185155186155187155188155189155190155191155192155193155194155195155196155197155198155199155200155201155202155203155204155205155206155207155208155209155210155211155212155213155214155215155216155217155218155219155220155221155222155223155224155225155226155227155228155229155230155231155232155233155234155235155236155237155238155239155240155241155242155243155244155245155246155247155248155249155250155251155252155253155254155255155256155257155258155259155260155261155262155263155264155265155266155267155268155269155270155271155272155273155274155275155276155277155278155279155280155281155282155283155284155285155286155287155288155289155290155291155292155293155294155295155296155297155298155299155300155301155302155303155304155305155306155307155308155309155310155311155312155313155314155315155316155317155318155319155320155321155322155323155324155325155326155327155328155329155330155331155332155333155334155335155336155337155338155339155340155341155342155343155344155345155346155347155348155349155350155351155352155353155354155355155356155357155358155359155360155361155362155363155364155365155366155367155368155369155370155371155372155373155374155375155376155377155378155379155380155381155382155383155384155385155386155387155388155389155390155391155392155393155394155395155396155397155398155399155400155401155402155403155404155405155406155407155408155409155410155411155412155413155414155415155416155417155418155419155420155421155422155423155424155425155426155427155428155429155430155431155432155433155434155435155436155437155438155439155440155441155442155443155444155445155446155447155448155449155450155451155452155453155454155455155456155457155458155459155460155461155462155463155464155465155466155467155468155469155470155471155472155473155474155475155476155477155478155479155480155481155482155483155484155485155486155487155488155489155490155491155492155493155494155495155496155497155498155499155500155501155502155503155504155505155506155507155508155509155510155511155512155513155514155515155516155517155518155519155520155521155522155523155524155525155526155527155528155529155530155531155532155533155534155535155536155537155538155539155540155541155542155543155544155545155546155547155548155549155550155551155552155553155554155555155556155557155558155559155560155561155562155563155564155565155566155567155568155569155570155571155572155573155574155575155576155577155578155579155580155581155582155583155584155585155586155587155588155589155590155591155592155593155594155595155596155597155598155599155600155601155602155603155604155605155606155607155608155609155610155611155612155613155614155615155616155617155618155619155620155621155622155623155624155625155626155627155628155629155630155631155632155633155634155635155636155637155638155639155640155641155642155643155644155645155646155647155648155649155650155651155652155653155654155655155656155657155658155659155660155661155662155663155664155665155666155667155668155669155670155671155672155673155674155675155676155677155678155679155680155681155682155683155684155685155686155687155688155689155690155691155692155693155694155695155696155697155698155699155700155701155702155703155704155705155706155707155708155709155710155711155712155713155714155715155716155717155718155719155720155721155722155723155724155725155726155727155728155729155730155731155732155733155734155735155736155737155738155739155740155741155742155743155744155745155746155747155748155749155750155751155752155753155754155755155756155757155758155759155760155761155762155763155764155765155766155767155768155769155770155771155772155773155774155775155776155777155778155779155780155781155782155783155784155785155786155787155788155789155790155791155792155793155794155795155796155797155798155799155800155801155802155803155804155805155806155807155808155809155810155811155812155813155814155815155816155817155818155819155820155821155822155823155824155825155826155827155828155829155830155831155832155833155834155835155836155837155838155839155840155841155842155843155844155845155846155847155848155849155850155851155852155853155854155855155856155857155858155859155860155861155862155863155864155865155866155867155868155869155870155871155872155873155874155875155876155877155878155879155880155881155882155883155884155885155886155887155888155889155890155891155892155893155894155895155896155897155898155899155900155901155902155903155904155905155906155907155908155909155910155911155912155913155914155915155916155917155918155919155920155921155922155923155924155925155926155927155928155929155930155931155932155933155934155935155936155937155938155939155940155941155942155943155944155945155946155947155948155949155950155951155952155953155954155955155956155957155958155959155960155961155962155963155964155965155966155967155968155969155970155971155972155973155974155975155976155977155978155979155980155981155982155983155984155985155986155987155988155989155990155991155992155993155994155995155996155997155998155999156000156001156002156003156004156005156006156007156008156009156010156011156012156013156014156015156016156017156018156019156020156021156022156023156024156025156026156027156028156029156030156031156032156033156034156035156036156037156038156039156040156041156042156043156044156045156046156047156048156049156050156051156052156053156054156055156056156057156058156059156060156061156062156063156064156065156066156067156068156069156070156071156072156073156074156075156076156077156078156079156080156081156082156083156084156085156086156087156088156089156090156091156092156093156094156095156096156097156098156099156100156101156102156103156104156105156106156107156108156109156110156111156112156113156114156115156116156117156118156119156120156121156122156123156124156125156126156127156128156129156130156131156132156133156134156135156136156137156138156139156140156141156142156143156144156145156146156147156148156149156150156151156152156153156154156155156156156157156158156159156160156161156162156163156164156165156166156167156168156169156170156171156172156173156174156175156176156177156178156179156180156181156182156183156184156185156186156187156188156189156190156191156192156193156194156195156196156197156198156199156200156201156202156203156204156205156206156207156208156209156210156211156212156213156214156215156216156217156218156219156220156221156222156223156224156225156226156227156228156229156230156231156232156233156234156235156236156237156238156239156240156241156242156243156244156245156246156247156248156249156250156251156252156253156254156255156256156257156258156259156260156261156262156263156264156265156266156267156268156269156270156271156272156273156274156275156276156277156278156279156280156281156282156283156284156285156286156287156288156289156290156291156292156293156294156295156296156297156298156299156300156301156302156303156304156305156306156307156308156309156310156311156312156313156314156315156316156317156318156319156320156321156322156323156324156325156326156327156328156329156330156331156332156333156334156335156336156337156338156339156340156341156342156343156344156345156346156347156348156349156350156351156352156353156354156355156356156357156358156359156360156361156362156363156364156365156366156367156368156369156370156371156372156373156374156375156376156377156378156379156380156381156382156383156384156385156386156387156388156389156390156391156392156393156394156395156396156397156398156399156400156401156402156403156404156405156406156407156408156409156410156411156412156413156414156415156416156417156418156419156420156421156422156423156424156425156426156427156428156429156430156431156432156433156434156435156436156437156438156439156440156441156442156443156444156445156446156447156448156449156450156451156452156453156454156455156456156457156458156459156460156461156462156463156464156465156466156467156468156469156470156471156472156473156474156475156476156477156478156479156480156481156482156483156484156485156486156487156488156489156490156491156492156493156494156495156496156497156498156499156500156501156502156503156504156505156506156507156508156509156510156511156512156513156514156515156516156517156518156519156520156521156522156523156524156525156526156527156528156529156530156531156532156533156534156535156536156537156538156539156540156541156542156543156544156545156546156547156548156549156550156551156552156553156554156555156556156557156558156559156560156561156562156563156564156565156566156567156568156569156570156571156572156573156574156575156576156577156578156579156580156581156582156583156584156585156586156587156588156589156590156591156592156593156594156595156596156597156598156599156600156601156602156603156604156605156606156607156608156609156610156611156612156613156614156615156616156617156618156619156620156621156622156623156624156625156626156627156628156629156630156631156632156633156634156635156636156637156638156639156640156641156642156643156644156645156646156647156648156649156650156651156652156653156654156655156656156657156658156659156660156661156662156663156664156665156666156667156668156669156670156671156672156673156674156675156676156677156678156679156680156681156682156683156684156685156686156687156688156689156690156691156692156693156694156695156696156697156698156699156700156701156702156703156704156705156706156707156708156709156710156711156712156713156714156715156716156717156718156719156720156721156722156723156724156725156726156727156728156729156730156731156732156733156734156735156736156737156738156739156740156741156742156743156744156745156746156747156748156749156750156751156752156753156754156755156756156757156758156759156760156761156762156763156764156765156766156767156768156769156770156771156772156773156774156775156776156777156778156779156780156781156782156783156784156785156786156787156788156789156790156791156792156793156794156795156796156797156798156799156800156801156802156803156804156805156806156807156808156809156810156811156812156813156814156815156816156817156818156819156820156821156822156823156824156825156826156827156828156829156830156831156832156833156834156835156836156837156838156839156840156841156842156843156844156845156846156847156848156849156850156851156852156853156854156855156856156857156858156859156860156861156862156863156864156865156866156867156868156869156870156871156872156873156874156875156876156877156878156879156880156881156882156883156884156885156886156887156888156889156890156891156892156893156894156895156896156897156898156899156900156901156902156903156904156905156906156907156908156909156910156911156912156913156914156915156916156917156918156919156920156921156922156923156924156925156926156927156928156929156930156931156932156933156934156935156936156937156938156939156940156941156942156943156944156945156946156947156948156949156950156951156952156953156954156955156956156957156958156959156960156961156962156963156964156965156966156967156968156969156970156971156972156973156974156975156976156977156978156979156980156981156982156983156984156985156986156987156988156989156990156991156992156993156994156995156996156997156998156999157000157001157002157003157004157005157006157007157008157009157010157011157012157013157014157015157016157017157018157019157020157021157022157023157024157025157026157027157028157029157030157031157032157033157034157035157036157037157038157039157040157041157042157043157044157045157046157047157048157049157050157051157052157053157054157055157056157057157058157059157060157061157062157063157064157065157066157067157068157069157070157071157072157073157074157075157076157077157078157079157080157081157082157083157084157085157086157087157088157089157090157091157092157093157094157095157096157097157098157099157100157101157102157103157104157105157106157107157108157109157110157111157112157113157114157115157116157117157118157119157120157121157122157123157124157125157126157127157128157129157130157131157132157133157134157135157136157137157138157139157140157141157142157143157144157145157146157147157148157149157150157151157152157153157154157155157156157157157158157159157160157161157162157163157164157165157166157167157168157169157170157171157172157173157174157175157176157177157178157179157180157181157182157183157184157185157186157187157188157189157190157191157192157193157194157195157196157197157198157199157200157201157202157203157204157205157206157207157208157209157210157211157212157213157214157215157216157217157218157219157220157221157222157223157224157225157226157227157228157229157230157231157232157233157234157235157236157237157238157239157240157241157242157243157244157245157246157247157248157249157250157251157252157253157254157255157256157257157258157259157260157261157262157263157264157265157266157267157268157269157270157271157272157273157274157275157276157277157278157279157280157281157282157283157284157285157286157287157288157289157290157291157292157293157294157295157296157297157298157299157300157301157302157303157304157305157306157307157308157309157310157311157312157313157314157315157316157317157318157319157320157321157322157323157324157325157326157327157328157329157330157331157332157333157334157335157336157337157338157339157340157341157342157343157344157345157346157347157348157349157350157351157352157353157354157355157356157357157358157359157360157361157362157363157364157365157366157367157368157369157370157371157372157373157374157375157376157377157378157379157380157381157382157383157384157385157386157387157388157389157390157391157392157393157394157395157396157397157398157399157400157401157402157403157404157405157406157407157408157409157410157411157412157413157414157415157416157417157418157419157420157421157422157423157424157425157426157427157428157429157430157431157432157433157434157435157436157437157438157439157440157441157442157443157444157445157446157447157448157449157450157451157452157453157454157455157456157457157458157459157460157461157462157463157464157465157466157467157468157469157470157471157472157473157474157475157476157477157478157479157480157481157482157483157484157485157486157487157488157489157490157491157492157493157494157495157496157497157498157499157500157501157502157503157504157505157506157507157508157509157510157511157512157513157514157515157516157517157518157519157520157521157522157523157524157525157526157527157528157529157530157531157532157533157534157535157536157537157538157539157540157541157542157543157544157545157546157547157548157549157550157551157552157553157554157555157556157557157558157559157560157561157562157563157564157565157566157567157568157569157570157571157572157573157574157575157576157577157578157579157580157581157582157583157584157585157586157587157588157589157590157591157592157593157594157595157596157597157598157599157600157601157602157603157604157605157606157607157608157609157610157611157612157613157614157615157616157617157618157619157620157621157622157623157624157625157626157627157628157629157630157631157632157633157634157635157636157637157638157639157640157641157642157643157644157645157646157647157648157649157650157651157652157653157654157655157656157657157658157659157660157661157662157663157664157665157666157667157668157669157670157671157672157673157674157675157676157677157678157679157680157681157682157683157684157685157686157687157688157689157690157691157692157693157694157695157696157697157698157699157700157701157702157703157704157705157706157707157708157709157710157711157712157713157714157715157716157717157718157719157720157721157722157723157724157725157726157727157728157729157730157731157732157733157734157735157736157737157738157739157740157741157742157743157744157745157746157747157748157749157750157751157752157753157754157755157756157757157758157759157760157761157762157763157764157765157766157767157768157769157770157771157772157773157774157775157776157777157778157779157780157781157782157783157784157785157786157787157788157789157790157791157792157793157794157795157796157797157798157799157800157801157802157803157804157805157806157807157808157809157810157811157812157813157814157815157816157817157818157819157820157821157822157823157824157825157826157827157828157829157830157831157832157833157834157835157836157837157838157839157840157841157842157843157844157845157846157847157848157849157850157851157852157853157854157855157856157857157858157859157860157861157862157863157864157865157866157867157868157869157870157871157872157873157874157875157876157877157878157879157880157881157882157883157884157885157886157887157888157889157890157891157892157893157894157895157896157897157898157899157900157901157902157903157904157905157906157907157908157909157910157911157912157913157914157915157916157917157918157919157920157921157922157923157924157925157926157927157928157929157930157931157932157933157934157935157936157937157938157939157940157941157942157943157944157945157946157947157948157949157950157951157952157953157954157955157956157957157958157959157960157961157962157963157964157965157966157967157968157969157970157971157972157973157974157975157976157977157978157979157980157981157982157983157984157985157986157987157988157989157990157991157992157993157994157995157996157997157998157999158000158001158002158003158004158005158006158007158008158009158010158011158012158013158014158015158016158017158018158019158020158021158022158023158024158025158026158027158028158029158030158031158032158033158034158035158036158037158038158039158040158041158042158043158044158045158046158047158048158049158050158051158052158053158054158055158056158057158058158059158060158061158062158063158064158065158066158067158068158069158070158071158072158073158074158075158076158077158078158079158080158081158082158083158084158085158086158087158088158089158090158091158092158093158094158095158096158097158098158099158100158101158102158103158104158105158106158107158108158109158110158111158112158113158114158115158116158117158118158119158120158121158122158123158124158125158126158127158128158129158130158131158132158133158134158135158136158137158138158139158140158141158142158143158144158145158146158147158148158149158150158151158152158153158154158155158156158157158158158159158160158161158162158163158164158165158166158167158168158169158170158171158172158173158174158175158176158177158178158179158180158181158182158183158184158185158186158187158188158189158190158191158192158193158194158195158196158197158198158199158200158201158202158203158204158205158206158207158208158209158210158211158212158213158214158215158216158217158218158219158220158221158222158223158224158225158226158227158228158229158230158231158232158233158234158235158236158237158238158239158240158241158242158243158244158245158246158247158248158249158250158251158252158253158254158255158256158257158258158259158260158261158262158263158264158265158266158267158268158269158270158271158272158273158274158275158276158277158278158279158280158281158282158283158284158285158286158287158288158289158290158291158292158293158294158295158296158297158298158299158300158301158302158303158304158305158306158307158308158309158310158311158312158313158314158315158316158317158318158319158320158321158322158323158324158325158326158327158328158329158330158331158332158333158334158335158336158337158338158339158340158341158342158343158344158345158346158347158348158349158350158351158352158353158354158355158356158357158358158359158360158361158362158363158364158365158366158367158368158369158370158371158372158373158374158375158376158377158378158379158380158381158382158383158384158385158386158387158388158389158390158391158392158393158394158395158396158397158398158399158400158401158402158403158404158405158406158407158408158409158410158411158412158413158414158415158416158417158418158419158420158421158422158423158424158425158426158427158428158429158430158431158432158433158434158435158436158437158438158439158440158441158442158443158444158445158446158447158448158449158450158451158452158453158454158455158456158457158458158459158460158461158462158463158464158465158466158467158468158469158470158471158472158473158474158475158476158477158478158479158480158481158482158483158484158485158486158487158488158489158490158491158492158493158494158495158496158497158498158499158500158501158502158503158504158505158506158507158508158509158510158511158512158513158514158515158516158517158518158519158520158521158522158523158524158525158526158527158528158529158530158531158532158533158534158535158536158537158538158539158540158541158542158543158544158545158546158547158548158549158550158551158552158553158554158555158556158557158558158559158560158561158562158563158564158565158566158567158568158569158570158571158572158573158574158575158576158577158578158579158580158581158582158583158584158585158586158587158588158589158590158591158592158593158594158595158596158597158598158599158600158601158602158603158604158605158606158607158608158609158610158611158612158613158614158615158616158617158618158619158620158621158622158623158624158625158626158627158628158629158630158631158632158633158634158635158636158637158638158639158640158641158642158643158644158645158646158647158648158649158650158651158652158653158654158655158656158657158658158659158660158661158662158663158664158665158666158667158668158669158670158671158672158673158674158675158676158677158678158679158680158681158682158683158684158685158686158687158688158689158690158691158692158693158694158695158696158697158698158699158700158701158702158703158704158705158706158707158708158709158710158711158712158713158714158715158716158717158718158719158720158721158722158723158724158725158726158727158728158729158730158731158732158733158734158735158736158737158738158739158740158741158742158743158744158745158746158747158748158749158750158751158752158753158754158755158756158757158758158759158760158761158762158763158764158765158766158767158768158769158770158771158772158773158774158775158776158777158778158779158780158781158782158783158784158785158786158787158788158789158790158791158792158793158794158795158796158797158798158799158800158801158802158803158804158805158806158807158808158809158810158811158812158813158814158815158816158817158818158819158820158821158822158823158824158825158826158827158828158829158830158831158832158833158834158835158836158837158838158839158840158841158842158843158844158845158846158847158848158849158850158851158852158853158854158855158856158857158858158859158860158861158862158863158864158865158866158867158868158869158870158871158872158873158874158875158876158877158878158879158880158881158882158883158884158885158886158887158888158889158890158891158892158893158894158895158896158897158898158899158900158901158902158903158904158905158906158907158908158909158910158911158912158913158914158915158916158917158918158919158920158921158922158923158924158925158926158927158928158929158930158931158932158933158934158935158936158937158938158939158940158941158942158943158944158945158946158947158948158949158950158951158952158953158954158955158956158957158958158959158960158961158962158963158964158965158966158967158968158969158970158971158972158973158974158975158976158977158978158979158980158981158982158983158984158985158986158987158988158989158990158991158992158993158994158995158996158997158998158999159000159001159002159003159004159005159006159007159008159009159010159011159012159013159014159015159016159017159018159019159020159021159022159023159024159025159026159027159028159029159030159031159032159033159034159035159036159037159038159039159040159041159042159043159044159045159046159047159048159049159050159051159052159053159054159055159056159057159058159059159060159061159062159063159064159065159066159067159068159069159070159071159072159073159074159075159076159077159078159079159080159081159082159083159084159085159086159087159088159089159090159091159092159093159094159095159096159097159098159099159100159101159102159103159104159105159106159107159108159109159110159111159112159113159114159115159116159117159118159119159120159121159122159123159124159125159126159127159128159129159130159131159132159133159134159135159136159137159138159139159140159141159142159143159144159145159146159147159148159149159150159151159152159153159154159155159156159157159158159159159160159161159162159163159164159165159166159167159168159169159170159171159172159173159174159175159176159177159178159179159180159181159182159183159184159185159186159187159188159189159190159191159192159193159194159195159196159197159198159199159200159201159202159203159204159205159206159207159208159209159210159211159212159213159214159215159216159217159218159219159220159221159222159223159224159225159226159227159228159229159230159231159232159233159234159235159236159237159238159239159240159241159242159243159244159245159246159247159248159249159250159251159252159253159254159255159256159257159258159259159260159261159262159263159264159265159266159267159268159269159270159271159272159273159274159275159276159277159278159279159280159281159282159283159284159285159286159287159288159289159290159291159292159293159294159295159296159297159298159299159300159301159302159303159304159305159306159307159308159309159310159311159312159313159314159315159316159317159318159319159320159321159322159323159324159325159326159327159328159329159330159331159332159333159334159335159336159337159338159339159340159341159342159343159344159345159346159347159348159349159350159351159352159353159354159355159356159357159358159359159360159361159362159363159364159365159366159367159368159369159370159371159372159373159374159375159376159377159378159379159380159381159382159383159384159385159386159387159388159389159390159391159392159393159394159395159396159397159398159399159400159401159402159403159404159405159406159407159408159409159410159411159412159413159414159415159416159417159418159419159420159421159422159423159424159425159426159427159428159429159430159431159432159433159434159435159436159437159438159439159440159441159442159443159444159445159446159447159448159449159450159451159452159453159454159455159456159457159458159459159460159461159462159463159464159465159466159467159468159469159470159471159472159473159474159475159476159477159478159479159480159481159482159483159484159485159486159487159488159489159490159491159492159493159494159495159496159497159498159499159500159501159502159503159504159505159506159507159508159509159510159511159512159513159514159515159516159517159518159519159520159521159522159523159524159525159526159527159528159529159530159531159532159533159534159535159536159537159538159539159540159541159542159543159544159545159546159547159548159549159550159551159552159553159554159555159556159557159558159559159560159561159562159563159564159565159566159567159568159569159570159571159572159573159574159575159576159577159578159579159580159581159582159583159584159585159586159587159588159589159590159591159592159593159594159595159596159597159598159599159600159601159602159603159604159605159606159607159608159609159610159611159612159613159614159615159616159617159618159619159620159621159622159623159624159625159626159627159628159629159630159631159632159633159634159635159636159637159638159639159640159641159642159643159644159645159646159647159648159649159650159651159652159653159654159655159656159657159658159659159660159661159662159663159664159665159666159667159668159669159670159671159672159673159674159675159676159677159678159679159680159681159682159683159684159685159686159687159688159689159690159691159692159693159694159695159696159697159698159699159700159701159702159703159704159705159706159707159708159709159710159711159712159713159714159715159716159717159718159719159720159721159722159723159724159725159726159727159728159729159730159731159732159733159734159735159736159737159738159739159740159741159742159743159744159745159746159747159748159749159750159751159752159753159754159755159756159757159758159759159760159761159762159763159764159765159766159767159768159769159770159771159772159773159774159775159776159777159778159779159780159781159782159783159784159785159786159787159788159789159790159791159792159793159794159795159796159797159798159799159800159801159802159803159804159805159806159807159808159809159810159811159812159813159814159815159816159817159818159819159820159821159822159823159824159825159826159827159828159829159830159831159832159833159834159835159836159837159838159839159840159841159842159843159844159845159846159847159848159849159850159851159852159853159854159855159856159857159858159859159860159861159862159863159864159865159866159867159868159869159870159871159872159873159874159875159876159877159878159879159880159881159882159883159884159885159886159887159888159889159890159891159892159893159894159895159896159897159898159899159900159901159902159903159904159905159906159907159908159909159910159911159912159913159914159915159916159917159918159919159920159921159922159923159924159925159926159927159928159929159930159931159932159933159934159935159936159937159938159939159940159941159942159943159944159945159946159947159948159949159950159951159952159953159954159955159956159957159958159959159960159961159962159963159964159965159966159967159968159969159970159971159972159973159974159975159976159977159978159979159980159981159982159983159984159985159986159987159988159989159990159991159992159993159994159995159996159997159998159999160000160001160002160003160004160005160006160007160008160009160010160011160012160013160014160015160016160017160018160019160020160021160022160023160024160025160026160027160028160029160030160031160032160033160034160035160036160037160038160039160040160041160042160043160044160045160046160047160048160049160050160051160052160053160054160055160056160057160058160059160060160061160062160063160064160065160066160067160068160069160070160071160072160073160074160075160076160077160078160079160080160081160082160083160084160085160086160087160088160089160090160091160092160093160094160095160096160097160098160099160100160101160102160103160104160105160106160107160108160109160110160111160112160113160114160115160116160117160118160119160120160121160122160123160124160125160126160127160128160129160130160131160132160133160134160135160136160137160138160139160140160141160142160143160144160145160146160147160148160149160150160151160152160153160154160155160156160157160158160159160160160161160162160163160164160165160166160167160168160169160170160171160172160173160174160175160176160177160178160179160180160181160182160183160184160185160186160187160188160189160190160191160192160193160194160195160196160197160198160199160200160201160202160203160204160205160206160207160208160209160210160211160212160213160214160215160216160217160218160219160220160221160222160223160224160225160226160227160228160229160230160231160232160233160234160235160236160237160238160239160240160241160242160243160244160245160246160247160248160249160250160251160252160253160254160255160256160257160258160259160260160261160262160263160264160265160266160267160268160269160270160271160272160273160274160275160276160277160278160279160280160281160282160283160284160285160286160287160288160289160290160291160292160293160294160295160296160297160298160299160300160301160302160303160304160305160306160307160308160309160310160311160312160313160314160315160316160317160318160319160320160321160322160323160324160325160326160327160328160329160330160331160332160333160334160335160336160337160338160339160340160341160342160343160344160345160346160347160348160349160350160351160352160353160354160355160356160357160358160359160360160361160362160363160364160365160366160367160368160369160370160371160372160373160374160375160376160377160378160379160380160381160382160383160384160385160386160387160388160389160390160391160392160393160394160395160396160397160398160399160400160401160402160403160404160405160406160407160408160409160410160411160412160413160414160415160416160417160418160419160420160421160422160423160424160425160426160427160428160429160430160431160432160433160434160435160436160437160438160439160440160441160442160443160444160445160446160447160448160449160450160451160452160453160454160455160456160457160458160459160460160461160462160463160464160465160466160467160468160469160470160471160472160473160474160475160476160477160478160479160480160481160482160483160484160485160486160487160488160489160490160491160492160493160494160495160496160497160498160499160500160501160502160503160504160505160506160507160508160509160510160511160512160513160514160515160516160517160518160519160520160521160522160523160524160525160526160527160528160529160530160531160532160533160534160535160536160537160538160539160540160541160542160543160544160545160546160547160548160549160550160551160552160553160554160555160556160557160558160559160560160561160562160563160564160565160566160567160568160569160570160571160572160573160574160575160576160577160578160579160580160581160582160583160584160585160586160587160588160589160590160591160592160593160594160595160596160597160598160599160600160601160602160603160604160605160606160607160608160609160610160611160612160613160614160615160616160617160618160619160620160621160622160623160624160625160626160627160628160629160630160631160632160633160634160635160636160637160638160639160640160641160642160643160644160645160646160647160648160649160650160651160652160653160654160655160656160657160658160659160660160661160662160663160664160665160666160667160668160669160670160671160672160673160674160675160676160677160678160679160680160681160682160683160684160685160686160687160688160689160690160691160692160693160694160695160696160697160698160699160700160701160702160703160704160705160706160707160708160709160710160711160712160713160714160715160716160717160718160719160720160721160722160723160724160725160726160727160728160729160730160731160732160733160734160735160736160737160738160739160740160741160742160743160744160745160746160747160748160749160750160751160752160753160754160755160756160757160758160759160760160761160762160763160764160765160766160767160768160769160770160771160772160773160774160775160776160777160778160779160780160781160782160783160784160785160786160787160788160789160790160791160792160793160794160795160796160797160798160799160800160801160802160803160804160805160806160807160808160809160810160811160812160813160814160815160816160817160818160819160820160821160822160823160824160825160826160827160828160829160830160831160832160833160834160835160836160837160838160839160840160841160842160843160844160845160846160847160848160849160850160851160852160853160854160855160856160857160858160859160860160861160862160863160864160865160866160867160868160869160870160871160872160873160874160875160876160877160878160879160880160881160882160883160884160885160886160887160888160889160890160891160892160893160894160895160896160897160898160899160900160901160902160903160904160905160906160907160908160909160910160911160912160913160914160915160916160917160918160919160920160921160922160923160924160925160926160927160928160929160930160931160932160933160934160935160936160937160938160939160940160941160942160943160944160945160946160947160948160949160950160951160952160953160954160955160956160957160958160959160960160961160962160963160964160965160966160967160968160969160970160971160972160973160974160975160976160977160978160979160980160981160982160983160984160985160986160987160988160989160990160991160992160993160994160995160996160997160998160999161000161001161002161003161004161005161006161007161008161009161010161011161012161013161014161015161016161017161018161019161020161021161022161023161024161025161026161027161028161029161030161031161032161033161034161035161036161037161038161039161040161041161042161043161044161045161046161047161048161049161050161051161052161053161054161055161056161057161058161059161060161061161062161063161064161065161066161067161068161069161070161071161072161073161074161075161076161077161078161079161080161081161082161083161084161085161086161087161088161089161090161091161092161093161094161095161096161097161098161099161100161101161102161103161104161105161106161107161108161109161110161111161112161113161114161115161116161117161118161119161120161121161122161123161124161125161126161127161128161129161130161131161132161133161134161135161136161137161138161139161140161141161142161143161144161145161146161147161148161149161150161151161152161153161154161155161156161157161158161159161160161161161162161163161164161165161166161167161168161169161170161171161172161173161174161175161176161177161178161179161180161181161182161183161184161185161186161187161188161189161190161191161192161193161194161195161196161197161198161199161200161201161202161203161204161205161206161207161208161209161210161211161212161213161214161215161216161217161218161219161220161221161222161223161224161225161226161227161228161229161230161231161232161233161234161235161236161237161238161239161240161241161242161243161244161245161246161247161248161249161250161251161252161253161254161255161256161257161258161259161260161261161262161263161264161265161266161267161268161269161270161271161272161273161274161275161276161277161278161279161280161281161282161283161284161285161286161287161288161289161290161291161292161293161294161295161296161297161298161299161300161301161302161303161304161305161306161307161308161309161310161311161312161313161314161315161316161317161318161319161320161321161322161323161324161325161326161327161328161329161330161331161332161333161334161335161336161337161338161339161340161341161342161343161344161345161346161347161348161349161350161351161352161353161354161355161356161357161358161359161360161361161362161363161364161365161366161367161368161369161370161371161372161373161374161375161376161377161378161379161380161381161382161383161384161385161386161387161388161389161390161391161392161393161394161395161396161397161398161399161400161401161402161403161404161405161406161407161408161409161410161411161412161413161414161415161416161417161418161419161420161421161422161423161424161425161426161427161428161429161430161431161432161433161434161435161436161437161438161439161440161441161442161443161444161445161446161447161448161449161450161451161452161453161454161455161456161457161458161459161460161461161462161463161464161465161466161467161468161469161470161471161472161473161474161475161476161477161478161479161480161481161482161483161484161485161486161487161488161489161490161491161492161493161494161495161496161497161498161499161500161501161502161503161504161505161506161507161508161509161510161511161512161513161514161515161516161517161518161519161520161521161522161523161524161525161526161527161528161529161530161531161532161533161534161535161536161537161538161539161540161541161542161543161544161545161546161547161548161549161550161551161552161553161554161555161556161557161558161559161560161561161562161563161564161565161566161567161568161569161570161571161572161573161574161575161576161577161578161579161580161581161582161583161584161585161586161587161588161589161590161591161592161593161594161595161596161597161598161599161600161601161602161603161604161605161606161607161608161609161610161611161612161613161614161615161616161617161618161619161620161621161622161623161624
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.11.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.8.11.1"
  310. #define SQLITE_VERSION_NUMBER 3008011
  311. #define SQLITE_SOURCE_ID "2015-07-29 20:00:57 cf538e2783e468bbc25e7cb2a9ee64d3e0e80b2f"
  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 insure 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 insure 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_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  665. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  666. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  667. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  668. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  669. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  670. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  671. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  672. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  673. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  674. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  675. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  676. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  677. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  678. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  679. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  680. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  681. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  682. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  683. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  684. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  685. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  686. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  687. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  688. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  689. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  690. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  691. /*
  692. ** CAPI3REF: Flags For File Open Operations
  693. **
  694. ** These bit values are intended for use in the
  695. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  696. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  697. */
  698. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  699. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  700. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  701. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  702. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  703. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  704. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  705. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  706. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  707. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  708. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  709. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  710. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  711. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  712. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  713. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  714. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  715. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  716. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  717. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  718. /* Reserved: 0x00F00000 */
  719. /*
  720. ** CAPI3REF: Device Characteristics
  721. **
  722. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  723. ** object returns an integer which is a vector of these
  724. ** bit values expressing I/O characteristics of the mass storage
  725. ** device that holds the file that the [sqlite3_io_methods]
  726. ** refers to.
  727. **
  728. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  729. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  730. ** mean that writes of blocks that are nnn bytes in size and
  731. ** are aligned to an address which is an integer multiple of
  732. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  733. ** that when data is appended to a file, the data is appended
  734. ** first then the size of the file is extended, never the other
  735. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  736. ** information is written to disk in the same order as calls
  737. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  738. ** after reboot following a crash or power loss, the only bytes in a
  739. ** file that were written at the application level might have changed
  740. ** and that adjacent bytes, even bytes within the same sector are
  741. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  742. ** flag indicate that a file cannot be deleted when open. The
  743. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  744. ** read-only media and cannot be changed even by processes with
  745. ** elevated privileges.
  746. */
  747. #define SQLITE_IOCAP_ATOMIC 0x00000001
  748. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  749. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  750. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  751. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  752. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  753. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  754. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  755. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  756. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  757. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  758. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  759. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  760. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  761. /*
  762. ** CAPI3REF: File Locking Levels
  763. **
  764. ** SQLite uses one of these integer values as the second
  765. ** argument to calls it makes to the xLock() and xUnlock() methods
  766. ** of an [sqlite3_io_methods] object.
  767. */
  768. #define SQLITE_LOCK_NONE 0
  769. #define SQLITE_LOCK_SHARED 1
  770. #define SQLITE_LOCK_RESERVED 2
  771. #define SQLITE_LOCK_PENDING 3
  772. #define SQLITE_LOCK_EXCLUSIVE 4
  773. /*
  774. ** CAPI3REF: Synchronization Type Flags
  775. **
  776. ** When SQLite invokes the xSync() method of an
  777. ** [sqlite3_io_methods] object it uses a combination of
  778. ** these integer values as the second argument.
  779. **
  780. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  781. ** sync operation only needs to flush data to mass storage. Inode
  782. ** information need not be flushed. If the lower four bits of the flag
  783. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  784. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  785. ** to use Mac OS X style fullsync instead of fsync().
  786. **
  787. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  788. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  789. ** settings. The [synchronous pragma] determines when calls to the
  790. ** xSync VFS method occur and applies uniformly across all platforms.
  791. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  792. ** energetic or rigorous or forceful the sync operations are and
  793. ** only make a difference on Mac OSX for the default SQLite code.
  794. ** (Third-party VFS implementations might also make the distinction
  795. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  796. ** operating systems natively supported by SQLite, only Mac OSX
  797. ** cares about the difference.)
  798. */
  799. #define SQLITE_SYNC_NORMAL 0x00002
  800. #define SQLITE_SYNC_FULL 0x00003
  801. #define SQLITE_SYNC_DATAONLY 0x00010
  802. /*
  803. ** CAPI3REF: OS Interface Open File Handle
  804. **
  805. ** An [sqlite3_file] object represents an open file in the
  806. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  807. ** implementations will
  808. ** want to subclass this object by appending additional fields
  809. ** for their own use. The pMethods entry is a pointer to an
  810. ** [sqlite3_io_methods] object that defines methods for performing
  811. ** I/O operations on the open file.
  812. */
  813. typedef struct sqlite3_file sqlite3_file;
  814. struct sqlite3_file {
  815. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  816. };
  817. /*
  818. ** CAPI3REF: OS Interface File Virtual Methods Object
  819. **
  820. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  821. ** [sqlite3_file] object (or, more commonly, a subclass of the
  822. ** [sqlite3_file] object) with a pointer to an instance of this object.
  823. ** This object defines the methods used to perform various operations
  824. ** against the open file represented by the [sqlite3_file] object.
  825. **
  826. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  827. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  828. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  829. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  830. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  831. ** to NULL.
  832. **
  833. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  834. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  835. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  836. ** flag may be ORed in to indicate that only the data of the file
  837. ** and not its inode needs to be synced.
  838. **
  839. ** The integer values to xLock() and xUnlock() are one of
  840. ** <ul>
  841. ** <li> [SQLITE_LOCK_NONE],
  842. ** <li> [SQLITE_LOCK_SHARED],
  843. ** <li> [SQLITE_LOCK_RESERVED],
  844. ** <li> [SQLITE_LOCK_PENDING], or
  845. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  846. ** </ul>
  847. ** xLock() increases the lock. xUnlock() decreases the lock.
  848. ** The xCheckReservedLock() method checks whether any database connection,
  849. ** either in this process or in some other process, is holding a RESERVED,
  850. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  851. ** if such a lock exists and false otherwise.
  852. **
  853. ** The xFileControl() method is a generic interface that allows custom
  854. ** VFS implementations to directly control an open file using the
  855. ** [sqlite3_file_control()] interface. The second "op" argument is an
  856. ** integer opcode. The third argument is a generic pointer intended to
  857. ** point to a structure that may contain arguments or space in which to
  858. ** write return values. Potential uses for xFileControl() might be
  859. ** functions to enable blocking locks with timeouts, to change the
  860. ** locking strategy (for example to use dot-file locks), to inquire
  861. ** about the status of a lock, or to break stale locks. The SQLite
  862. ** core reserves all opcodes less than 100 for its own use.
  863. ** A [file control opcodes | list of opcodes] less than 100 is available.
  864. ** Applications that define a custom xFileControl method should use opcodes
  865. ** greater than 100 to avoid conflicts. VFS implementations should
  866. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  867. ** recognize.
  868. **
  869. ** The xSectorSize() method returns the sector size of the
  870. ** device that underlies the file. The sector size is the
  871. ** minimum write that can be performed without disturbing
  872. ** other bytes in the file. The xDeviceCharacteristics()
  873. ** method returns a bit vector describing behaviors of the
  874. ** underlying device:
  875. **
  876. ** <ul>
  877. ** <li> [SQLITE_IOCAP_ATOMIC]
  878. ** <li> [SQLITE_IOCAP_ATOMIC512]
  879. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  880. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  881. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  882. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  883. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  884. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  885. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  886. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  887. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  888. ** </ul>
  889. **
  890. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  891. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  892. ** mean that writes of blocks that are nnn bytes in size and
  893. ** are aligned to an address which is an integer multiple of
  894. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  895. ** that when data is appended to a file, the data is appended
  896. ** first then the size of the file is extended, never the other
  897. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  898. ** information is written to disk in the same order as calls
  899. ** to xWrite().
  900. **
  901. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  902. ** in the unread portions of the buffer with zeros. A VFS that
  903. ** fails to zero-fill short reads might seem to work. However,
  904. ** failure to zero-fill short reads will eventually lead to
  905. ** database corruption.
  906. */
  907. typedef struct sqlite3_io_methods sqlite3_io_methods;
  908. struct sqlite3_io_methods {
  909. int iVersion;
  910. int (*xClose)(sqlite3_file*);
  911. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  912. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  913. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  914. int (*xSync)(sqlite3_file*, int flags);
  915. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  916. int (*xLock)(sqlite3_file*, int);
  917. int (*xUnlock)(sqlite3_file*, int);
  918. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  919. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  920. int (*xSectorSize)(sqlite3_file*);
  921. int (*xDeviceCharacteristics)(sqlite3_file*);
  922. /* Methods above are valid for version 1 */
  923. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  924. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  925. void (*xShmBarrier)(sqlite3_file*);
  926. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  927. /* Methods above are valid for version 2 */
  928. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  929. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  930. /* Methods above are valid for version 3 */
  931. /* Additional methods may be added in future releases */
  932. };
  933. /*
  934. ** CAPI3REF: Standard File Control Opcodes
  935. ** KEYWORDS: {file control opcodes} {file control opcode}
  936. **
  937. ** These integer constants are opcodes for the xFileControl method
  938. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  939. ** interface.
  940. **
  941. ** <ul>
  942. ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
  943. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  944. ** opcode causes the xFileControl method to write the current state of
  945. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  946. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  947. ** into an integer that the pArg argument points to. This capability
  948. ** is used during testing and is only available when the SQLITE_TEST
  949. ** compile-time option is used.
  950. **
  951. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  952. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  953. ** layer a hint of how large the database file will grow to be during the
  954. ** current transaction. This hint is not guaranteed to be accurate but it
  955. ** is often close. The underlying VFS might choose to preallocate database
  956. ** file space based on this hint in order to help writes to the database
  957. ** file run faster.
  958. **
  959. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  960. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  961. ** extends and truncates the database file in chunks of a size specified
  962. ** by the user. The fourth argument to [sqlite3_file_control()] should
  963. ** point to an integer (type int) containing the new chunk-size to use
  964. ** for the nominated database. Allocating database file space in large
  965. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  966. ** improve performance on some systems.
  967. **
  968. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  969. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  970. ** to the [sqlite3_file] object associated with a particular database
  971. ** connection. See the [sqlite3_file_control()] documentation for
  972. ** additional information.
  973. **
  974. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  975. ** No longer in use.
  976. **
  977. ** <li>[[SQLITE_FCNTL_SYNC]]
  978. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  979. ** sent to the VFS immediately before the xSync method is invoked on a
  980. ** database file descriptor. Or, if the xSync method is not invoked
  981. ** because the user has configured SQLite with
  982. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  983. ** of the xSync method. In most cases, the pointer argument passed with
  984. ** this file-control is NULL. However, if the database file is being synced
  985. ** as part of a multi-database commit, the argument points to a nul-terminated
  986. ** string containing the transactions master-journal file name. VFSes that
  987. ** do not need this signal should silently ignore this opcode. Applications
  988. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  989. ** disrupt the operation of the specialized VFSes that do require it.
  990. **
  991. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  992. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  993. ** and sent to the VFS after a transaction has been committed immediately
  994. ** but before the database is unlocked. VFSes that do not need this signal
  995. ** should silently ignore this opcode. Applications should not call
  996. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  997. ** operation of the specialized VFSes that do require it.
  998. **
  999. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  1000. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  1001. ** retry counts and intervals for certain disk I/O operations for the
  1002. ** windows [VFS] in order to provide robustness in the presence of
  1003. ** anti-virus programs. By default, the windows VFS will retry file read,
  1004. ** file write, and file delete operations up to 10 times, with a delay
  1005. ** of 25 milliseconds before the first retry and with the delay increasing
  1006. ** by an additional 25 milliseconds with each subsequent retry. This
  1007. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  1008. ** to be adjusted. The values are changed for all database connections
  1009. ** within the same process. The argument is a pointer to an array of two
  1010. ** integers where the first integer i the new retry count and the second
  1011. ** integer is the delay. If either integer is negative, then the setting
  1012. ** is not changed but instead the prior value of that setting is written
  1013. ** into the array entry, allowing the current retry settings to be
  1014. ** interrogated. The zDbName parameter is ignored.
  1015. **
  1016. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  1017. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  1018. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  1019. ** write ahead log and shared memory files used for transaction control
  1020. ** are automatically deleted when the latest connection to the database
  1021. ** closes. Setting persistent WAL mode causes those files to persist after
  1022. ** close. Persisting the files is useful when other processes that do not
  1023. ** have write permission on the directory containing the database file want
  1024. ** to read the database file, as the WAL and shared memory files must exist
  1025. ** in order for the database to be readable. The fourth parameter to
  1026. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1027. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  1028. ** WAL mode. If the integer is -1, then it is overwritten with the current
  1029. ** WAL persistence setting.
  1030. **
  1031. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  1032. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  1033. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  1034. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  1035. ** xDeviceCharacteristics methods. The fourth parameter to
  1036. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  1037. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  1038. ** mode. If the integer is -1, then it is overwritten with the current
  1039. ** zero-damage mode setting.
  1040. **
  1041. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  1042. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  1043. ** a write transaction to indicate that, unless it is rolled back for some
  1044. ** reason, the entire database file will be overwritten by the current
  1045. ** transaction. This is used by VACUUM operations.
  1046. **
  1047. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  1048. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  1049. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  1050. ** final bottom-level VFS are written into memory obtained from
  1051. ** [sqlite3_malloc()] and the result is stored in the char* variable
  1052. ** that the fourth parameter of [sqlite3_file_control()] points to.
  1053. ** The caller is responsible for freeing the memory when done. As with
  1054. ** all file-control actions, there is no guarantee that this will actually
  1055. ** do anything. Callers should initialize the char* variable to a NULL
  1056. ** pointer in case this file-control is not implemented. This file-control
  1057. ** is intended for diagnostic use only.
  1058. **
  1059. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  1060. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  1061. ** file control is sent to the open [sqlite3_file] object corresponding
  1062. ** to the database file to which the pragma statement refers. ^The argument
  1063. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  1064. ** pointers to strings (char**) in which the second element of the array
  1065. ** is the name of the pragma and the third element is the argument to the
  1066. ** pragma or NULL if the pragma has no argument. ^The handler for an
  1067. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  1068. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  1069. ** or the equivalent and that string will become the result of the pragma or
  1070. ** the error message if the pragma fails. ^If the
  1071. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  1072. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  1073. ** file control returns [SQLITE_OK], then the parser assumes that the
  1074. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  1075. ** prepared statement if result string is NULL, or that returns a copy
  1076. ** of the result string if the string is non-NULL.
  1077. ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  1078. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  1079. ** that the VFS encountered an error while handling the [PRAGMA] and the
  1080. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  1081. ** file control occurs at the beginning of pragma statement analysis and so
  1082. ** it is able to override built-in [PRAGMA] statements.
  1083. **
  1084. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  1085. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  1086. ** file-control may be invoked by SQLite on the database file handle
  1087. ** shortly after it is opened in order to provide a custom VFS with access
  1088. ** to the connections busy-handler callback. The argument is of type (void **)
  1089. ** - an array of two (void *) values. The first (void *) actually points
  1090. ** to a function of type (int (*)(void *)). In order to invoke the connections
  1091. ** busy-handler, this function should be invoked with the second (void *) in
  1092. ** the array as the only argument. If it returns non-zero, then the operation
  1093. ** should be retried. If it returns zero, the custom VFS should abandon the
  1094. ** current operation.
  1095. **
  1096. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1097. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1098. ** to have SQLite generate a
  1099. ** temporary filename using the same algorithm that is followed to generate
  1100. ** temporary filenames for TEMP tables and other internal uses. The
  1101. ** argument should be a char** which will be filled with the filename
  1102. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1103. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1104. **
  1105. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1106. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1107. ** maximum number of bytes that will be used for memory-mapped I/O.
  1108. ** The argument is a pointer to a value of type sqlite3_int64 that
  1109. ** is an advisory maximum number of bytes in the file to memory map. The
  1110. ** pointer is overwritten with the old value. The limit is not changed if
  1111. ** the value originally pointed to is negative, and so the current limit
  1112. ** can be queried by passing in a pointer to a negative number. This
  1113. ** file-control is used internally to implement [PRAGMA mmap_size].
  1114. **
  1115. ** <li>[[SQLITE_FCNTL_TRACE]]
  1116. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1117. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1118. ** This file control is used by some VFS activity tracing [shims].
  1119. ** The argument is a zero-terminated string. Higher layers in the
  1120. ** SQLite stack may generate instances of this file control if
  1121. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1122. **
  1123. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1124. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1125. ** pointer to an integer and it writes a boolean into that integer depending
  1126. ** on whether or not the file has been renamed, moved, or deleted since it
  1127. ** was first opened.
  1128. **
  1129. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1130. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1131. ** opcode causes the xFileControl method to swap the file handle with the one
  1132. ** pointed to by the pArg argument. This capability is used during testing
  1133. ** and only needs to be supported when SQLITE_TEST is defined.
  1134. **
  1135. ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
  1136. ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
  1137. ** be advantageous to block on the next WAL lock if the lock is not immediately
  1138. ** available. The WAL subsystem issues this signal during rare
  1139. ** circumstances in order to fix a problem with priority inversion.
  1140. ** Applications should <em>not</em> use this file-control.
  1141. **
  1142. ** <li>[[SQLITE_FCNTL_ZIPVFS]]
  1143. ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
  1144. ** VFS should return SQLITE_NOTFOUND for this opcode.
  1145. **
  1146. ** <li>[[SQLITE_FCNTL_RBU]]
  1147. ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
  1148. ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
  1149. ** this opcode.
  1150. ** </ul>
  1151. */
  1152. #define SQLITE_FCNTL_LOCKSTATE 1
  1153. #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
  1154. #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
  1155. #define SQLITE_FCNTL_LAST_ERRNO 4
  1156. #define SQLITE_FCNTL_SIZE_HINT 5
  1157. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1158. #define SQLITE_FCNTL_FILE_POINTER 7
  1159. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1160. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1161. #define SQLITE_FCNTL_PERSIST_WAL 10
  1162. #define SQLITE_FCNTL_OVERWRITE 11
  1163. #define SQLITE_FCNTL_VFSNAME 12
  1164. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1165. #define SQLITE_FCNTL_PRAGMA 14
  1166. #define SQLITE_FCNTL_BUSYHANDLER 15
  1167. #define SQLITE_FCNTL_TEMPFILENAME 16
  1168. #define SQLITE_FCNTL_MMAP_SIZE 18
  1169. #define SQLITE_FCNTL_TRACE 19
  1170. #define SQLITE_FCNTL_HAS_MOVED 20
  1171. #define SQLITE_FCNTL_SYNC 21
  1172. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1173. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1174. #define SQLITE_FCNTL_WAL_BLOCK 24
  1175. #define SQLITE_FCNTL_ZIPVFS 25
  1176. #define SQLITE_FCNTL_RBU 26
  1177. /* deprecated names */
  1178. #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
  1179. #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
  1180. #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
  1181. /*
  1182. ** CAPI3REF: Mutex Handle
  1183. **
  1184. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1185. ** abstract type for a mutex object. The SQLite core never looks
  1186. ** at the internal representation of an [sqlite3_mutex]. It only
  1187. ** deals with pointers to the [sqlite3_mutex] object.
  1188. **
  1189. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1190. */
  1191. typedef struct sqlite3_mutex sqlite3_mutex;
  1192. /*
  1193. ** CAPI3REF: OS Interface Object
  1194. **
  1195. ** An instance of the sqlite3_vfs object defines the interface between
  1196. ** the SQLite core and the underlying operating system. The "vfs"
  1197. ** in the name of the object stands for "virtual file system". See
  1198. ** the [VFS | VFS documentation] for further information.
  1199. **
  1200. ** The value of the iVersion field is initially 1 but may be larger in
  1201. ** future versions of SQLite. Additional fields may be appended to this
  1202. ** object when the iVersion value is increased. Note that the structure
  1203. ** of the sqlite3_vfs object changes in the transaction between
  1204. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1205. ** modified.
  1206. **
  1207. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1208. ** structure used by this VFS. mxPathname is the maximum length of
  1209. ** a pathname in this VFS.
  1210. **
  1211. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1212. ** the pNext pointer. The [sqlite3_vfs_register()]
  1213. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1214. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1215. ** searches the list. Neither the application code nor the VFS
  1216. ** implementation should use the pNext pointer.
  1217. **
  1218. ** The pNext field is the only field in the sqlite3_vfs
  1219. ** structure that SQLite will ever modify. SQLite will only access
  1220. ** or modify this field while holding a particular static mutex.
  1221. ** The application should never modify anything within the sqlite3_vfs
  1222. ** object once the object has been registered.
  1223. **
  1224. ** The zName field holds the name of the VFS module. The name must
  1225. ** be unique across all VFS modules.
  1226. **
  1227. ** [[sqlite3_vfs.xOpen]]
  1228. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1229. ** is either a NULL pointer or string obtained
  1230. ** from xFullPathname() with an optional suffix added.
  1231. ** ^If a suffix is added to the zFilename parameter, it will
  1232. ** consist of a single "-" character followed by no more than
  1233. ** 11 alphanumeric and/or "-" characters.
  1234. ** ^SQLite further guarantees that
  1235. ** the string will be valid and unchanged until xClose() is
  1236. ** called. Because of the previous sentence,
  1237. ** the [sqlite3_file] can safely store a pointer to the
  1238. ** filename if it needs to remember the filename for some reason.
  1239. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1240. ** must invent its own temporary name for the file. ^Whenever the
  1241. ** xFilename parameter is NULL it will also be the case that the
  1242. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1243. **
  1244. ** The flags argument to xOpen() includes all bits set in
  1245. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1246. ** or [sqlite3_open16()] is used, then flags includes at least
  1247. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1248. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1249. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1250. **
  1251. ** ^(SQLite will also add one of the following flags to the xOpen()
  1252. ** call, depending on the object being opened:
  1253. **
  1254. ** <ul>
  1255. ** <li> [SQLITE_OPEN_MAIN_DB]
  1256. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1257. ** <li> [SQLITE_OPEN_TEMP_DB]
  1258. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1259. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1260. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1261. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1262. ** <li> [SQLITE_OPEN_WAL]
  1263. ** </ul>)^
  1264. **
  1265. ** The file I/O implementation can use the object type flags to
  1266. ** change the way it deals with files. For example, an application
  1267. ** that does not care about crash recovery or rollback might make
  1268. ** the open of a journal file a no-op. Writes to this journal would
  1269. ** also be no-ops, and any attempt to read the journal would return
  1270. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1271. ** file will be doing page-aligned sector reads and writes in a random
  1272. ** order and set up its I/O subsystem accordingly.
  1273. **
  1274. ** SQLite might also add one of the following flags to the xOpen method:
  1275. **
  1276. ** <ul>
  1277. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1278. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1279. ** </ul>
  1280. **
  1281. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1282. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1283. ** will be set for TEMP databases and their journals, transient
  1284. ** databases, and subjournals.
  1285. **
  1286. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1287. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1288. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1289. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1290. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1291. ** be created, and that it is an error if it already exists.
  1292. ** It is <i>not</i> used to indicate the file should be opened
  1293. ** for exclusive access.
  1294. **
  1295. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1296. ** to hold the [sqlite3_file] structure passed as the third
  1297. ** argument to xOpen. The xOpen method does not have to
  1298. ** allocate the structure; it should just fill it in. Note that
  1299. ** the xOpen method must set the sqlite3_file.pMethods to either
  1300. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1301. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1302. ** element will be valid after xOpen returns regardless of the success
  1303. ** or failure of the xOpen call.
  1304. **
  1305. ** [[sqlite3_vfs.xAccess]]
  1306. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1307. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1308. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1309. ** to test whether a file is at least readable. The file can be a
  1310. ** directory.
  1311. **
  1312. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1313. ** output buffer xFullPathname. The exact size of the output buffer
  1314. ** is also passed as a parameter to both methods. If the output buffer
  1315. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1316. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1317. ** to prevent this by setting mxPathname to a sufficiently large value.
  1318. **
  1319. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1320. ** interfaces are not strictly a part of the filesystem, but they are
  1321. ** included in the VFS structure for completeness.
  1322. ** The xRandomness() function attempts to return nBytes bytes
  1323. ** of good-quality randomness into zOut. The return value is
  1324. ** the actual number of bytes of randomness obtained.
  1325. ** The xSleep() method causes the calling thread to sleep for at
  1326. ** least the number of microseconds given. ^The xCurrentTime()
  1327. ** method returns a Julian Day Number for the current date and time as
  1328. ** a floating point value.
  1329. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1330. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1331. ** a 24-hour day).
  1332. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1333. ** date and time if that method is available (if iVersion is 2 or
  1334. ** greater and the function pointer is not NULL) and will fall back
  1335. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1336. **
  1337. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1338. ** are not used by the SQLite core. These optional interfaces are provided
  1339. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1340. ** system calls with functions under its control, a test program can
  1341. ** simulate faults and error conditions that would otherwise be difficult
  1342. ** or impossible to induce. The set of system calls that can be overridden
  1343. ** varies from one VFS to another, and from one version of the same VFS to the
  1344. ** next. Applications that use these interfaces must be prepared for any
  1345. ** or all of these interfaces to be NULL or for their behavior to change
  1346. ** from one release to the next. Applications must not attempt to access
  1347. ** any of these methods if the iVersion of the VFS is less than 3.
  1348. */
  1349. typedef struct sqlite3_vfs sqlite3_vfs;
  1350. typedef void (*sqlite3_syscall_ptr)(void);
  1351. struct sqlite3_vfs {
  1352. int iVersion; /* Structure version number (currently 3) */
  1353. int szOsFile; /* Size of subclassed sqlite3_file */
  1354. int mxPathname; /* Maximum file pathname length */
  1355. sqlite3_vfs *pNext; /* Next registered VFS */
  1356. const char *zName; /* Name of this virtual file system */
  1357. void *pAppData; /* Pointer to application-specific data */
  1358. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1359. int flags, int *pOutFlags);
  1360. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1361. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1362. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1363. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1364. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1365. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1366. void (*xDlClose)(sqlite3_vfs*, void*);
  1367. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1368. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1369. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1370. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1371. /*
  1372. ** The methods above are in version 1 of the sqlite_vfs object
  1373. ** definition. Those that follow are added in version 2 or later
  1374. */
  1375. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1376. /*
  1377. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1378. ** Those below are for version 3 and greater.
  1379. */
  1380. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1381. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1382. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1383. /*
  1384. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1385. ** New fields may be appended in figure versions. The iVersion
  1386. ** value will increment whenever this happens.
  1387. */
  1388. };
  1389. /*
  1390. ** CAPI3REF: Flags for the xAccess VFS method
  1391. **
  1392. ** These integer constants can be used as the third parameter to
  1393. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1394. ** what kind of permissions the xAccess method is looking for.
  1395. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1396. ** simply checks whether the file exists.
  1397. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1398. ** checks whether the named directory is both readable and writable
  1399. ** (in other words, if files can be added, removed, and renamed within
  1400. ** the directory).
  1401. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1402. ** [temp_store_directory pragma], though this could change in a future
  1403. ** release of SQLite.
  1404. ** With SQLITE_ACCESS_READ, the xAccess method
  1405. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1406. ** currently unused, though it might be used in a future release of
  1407. ** SQLite.
  1408. */
  1409. #define SQLITE_ACCESS_EXISTS 0
  1410. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1411. #define SQLITE_ACCESS_READ 2 /* Unused */
  1412. /*
  1413. ** CAPI3REF: Flags for the xShmLock VFS method
  1414. **
  1415. ** These integer constants define the various locking operations
  1416. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1417. ** following are the only legal combinations of flags to the
  1418. ** xShmLock method:
  1419. **
  1420. ** <ul>
  1421. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1422. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1423. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1424. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1425. ** </ul>
  1426. **
  1427. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1428. ** was given on the corresponding lock.
  1429. **
  1430. ** The xShmLock method can transition between unlocked and SHARED or
  1431. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1432. ** and EXCLUSIVE.
  1433. */
  1434. #define SQLITE_SHM_UNLOCK 1
  1435. #define SQLITE_SHM_LOCK 2
  1436. #define SQLITE_SHM_SHARED 4
  1437. #define SQLITE_SHM_EXCLUSIVE 8
  1438. /*
  1439. ** CAPI3REF: Maximum xShmLock index
  1440. **
  1441. ** The xShmLock method on [sqlite3_io_methods] may use values
  1442. ** between 0 and this upper bound as its "offset" argument.
  1443. ** The SQLite core will never attempt to acquire or release a
  1444. ** lock outside of this range
  1445. */
  1446. #define SQLITE_SHM_NLOCK 8
  1447. /*
  1448. ** CAPI3REF: Initialize The SQLite Library
  1449. **
  1450. ** ^The sqlite3_initialize() routine initializes the
  1451. ** SQLite library. ^The sqlite3_shutdown() routine
  1452. ** deallocates any resources that were allocated by sqlite3_initialize().
  1453. ** These routines are designed to aid in process initialization and
  1454. ** shutdown on embedded systems. Workstation applications using
  1455. ** SQLite normally do not need to invoke either of these routines.
  1456. **
  1457. ** A call to sqlite3_initialize() is an "effective" call if it is
  1458. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1459. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1460. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1461. ** of sqlite3_initialize() does any initialization. All other calls
  1462. ** are harmless no-ops.)^
  1463. **
  1464. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1465. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1466. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1467. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1468. **
  1469. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1470. ** is not. The sqlite3_shutdown() interface must only be called from a
  1471. ** single thread. All open [database connections] must be closed and all
  1472. ** other SQLite resources must be deallocated prior to invoking
  1473. ** sqlite3_shutdown().
  1474. **
  1475. ** Among other things, ^sqlite3_initialize() will invoke
  1476. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1477. ** will invoke sqlite3_os_end().
  1478. **
  1479. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1480. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1481. ** the library (perhaps it is unable to allocate a needed resource such
  1482. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1483. **
  1484. ** ^The sqlite3_initialize() routine is called internally by many other
  1485. ** SQLite interfaces so that an application usually does not need to
  1486. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1487. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1488. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1489. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1490. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1491. ** are omitted and the application must call sqlite3_initialize() directly
  1492. ** prior to using any other SQLite interface. For maximum portability,
  1493. ** it is recommended that applications always invoke sqlite3_initialize()
  1494. ** directly prior to using any other SQLite interface. Future releases
  1495. ** of SQLite may require this. In other words, the behavior exhibited
  1496. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1497. ** default behavior in some future release of SQLite.
  1498. **
  1499. ** The sqlite3_os_init() routine does operating-system specific
  1500. ** initialization of the SQLite library. The sqlite3_os_end()
  1501. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1502. ** performed by these routines include allocation or deallocation
  1503. ** of static resources, initialization of global variables,
  1504. ** setting up a default [sqlite3_vfs] module, or setting up
  1505. ** a default configuration using [sqlite3_config()].
  1506. **
  1507. ** The application should never invoke either sqlite3_os_init()
  1508. ** or sqlite3_os_end() directly. The application should only invoke
  1509. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1510. ** interface is called automatically by sqlite3_initialize() and
  1511. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1512. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1513. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1514. ** When [custom builds | built for other platforms]
  1515. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1516. ** option) the application must supply a suitable implementation for
  1517. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1518. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1519. ** must return [SQLITE_OK] on success and some other [error code] upon
  1520. ** failure.
  1521. */
  1522. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
  1523. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
  1524. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
  1525. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
  1526. /*
  1527. ** CAPI3REF: Configuring The SQLite Library
  1528. **
  1529. ** The sqlite3_config() interface is used to make global configuration
  1530. ** changes to SQLite in order to tune SQLite to the specific needs of
  1531. ** the application. The default configuration is recommended for most
  1532. ** applications and so this routine is usually not necessary. It is
  1533. ** provided to support rare applications with unusual needs.
  1534. **
  1535. ** The sqlite3_config() interface is not threadsafe. The application
  1536. ** must insure that no other SQLite interfaces are invoked by other
  1537. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1538. ** may only be invoked prior to library initialization using
  1539. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1540. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1541. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1542. ** Note, however, that ^sqlite3_config() can be called as part of the
  1543. ** implementation of an application-defined [sqlite3_os_init()].
  1544. **
  1545. ** The first argument to sqlite3_config() is an integer
  1546. ** [configuration option] that determines
  1547. ** what property of SQLite is to be configured. Subsequent arguments
  1548. ** vary depending on the [configuration option]
  1549. ** in the first argument.
  1550. **
  1551. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1552. ** ^If the option is unknown or SQLite is unable to set the option
  1553. ** then this routine returns a non-zero [error code].
  1554. */
  1555. SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
  1556. /*
  1557. ** CAPI3REF: Configure database connections
  1558. ** METHOD: sqlite3
  1559. **
  1560. ** The sqlite3_db_config() interface is used to make configuration
  1561. ** changes to a [database connection]. The interface is similar to
  1562. ** [sqlite3_config()] except that the changes apply to a single
  1563. ** [database connection] (specified in the first argument).
  1564. **
  1565. ** The second argument to sqlite3_db_config(D,V,...) is the
  1566. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1567. ** that indicates what aspect of the [database connection] is being configured.
  1568. ** Subsequent arguments vary depending on the configuration verb.
  1569. **
  1570. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1571. ** the call is considered successful.
  1572. */
  1573. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
  1574. /*
  1575. ** CAPI3REF: Memory Allocation Routines
  1576. **
  1577. ** An instance of this object defines the interface between SQLite
  1578. ** and low-level memory allocation routines.
  1579. **
  1580. ** This object is used in only one place in the SQLite interface.
  1581. ** A pointer to an instance of this object is the argument to
  1582. ** [sqlite3_config()] when the configuration option is
  1583. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1584. ** By creating an instance of this object
  1585. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1586. ** during configuration, an application can specify an alternative
  1587. ** memory allocation subsystem for SQLite to use for all of its
  1588. ** dynamic memory needs.
  1589. **
  1590. ** Note that SQLite comes with several [built-in memory allocators]
  1591. ** that are perfectly adequate for the overwhelming majority of applications
  1592. ** and that this object is only useful to a tiny minority of applications
  1593. ** with specialized memory allocation requirements. This object is
  1594. ** also used during testing of SQLite in order to specify an alternative
  1595. ** memory allocator that simulates memory out-of-memory conditions in
  1596. ** order to verify that SQLite recovers gracefully from such
  1597. ** conditions.
  1598. **
  1599. ** The xMalloc, xRealloc, and xFree methods must work like the
  1600. ** malloc(), realloc() and free() functions from the standard C library.
  1601. ** ^SQLite guarantees that the second argument to
  1602. ** xRealloc is always a value returned by a prior call to xRoundup.
  1603. **
  1604. ** xSize should return the allocated size of a memory allocation
  1605. ** previously obtained from xMalloc or xRealloc. The allocated size
  1606. ** is always at least as big as the requested size but may be larger.
  1607. **
  1608. ** The xRoundup method returns what would be the allocated size of
  1609. ** a memory allocation given a particular requested size. Most memory
  1610. ** allocators round up memory allocations at least to the next multiple
  1611. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1612. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1613. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1614. ** that causes the corresponding memory allocation to fail.
  1615. **
  1616. ** The xInit method initializes the memory allocator. For example,
  1617. ** it might allocate any require mutexes or initialize internal data
  1618. ** structures. The xShutdown method is invoked (indirectly) by
  1619. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1620. ** by xInit. The pAppData pointer is used as the only parameter to
  1621. ** xInit and xShutdown.
  1622. **
  1623. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1624. ** the xInit method, so the xInit method need not be threadsafe. The
  1625. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1626. ** not need to be threadsafe either. For all other methods, SQLite
  1627. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1628. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1629. ** it is by default) and so the methods are automatically serialized.
  1630. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1631. ** methods must be threadsafe or else make their own arrangements for
  1632. ** serialization.
  1633. **
  1634. ** SQLite will never invoke xInit() more than once without an intervening
  1635. ** call to xShutdown().
  1636. */
  1637. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1638. struct sqlite3_mem_methods {
  1639. void *(*xMalloc)(int); /* Memory allocation function */
  1640. void (*xFree)(void*); /* Free a prior allocation */
  1641. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1642. int (*xSize)(void*); /* Return the size of an allocation */
  1643. int (*xRoundup)(int); /* Round up request size to allocation size */
  1644. int (*xInit)(void*); /* Initialize the memory allocator */
  1645. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1646. void *pAppData; /* Argument to xInit() and xShutdown() */
  1647. };
  1648. /*
  1649. ** CAPI3REF: Configuration Options
  1650. ** KEYWORDS: {configuration option}
  1651. **
  1652. ** These constants are the available integer configuration options that
  1653. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1654. **
  1655. ** New configuration options may be added in future releases of SQLite.
  1656. ** Existing configuration options might be discontinued. Applications
  1657. ** should check the return code from [sqlite3_config()] to make sure that
  1658. ** the call worked. The [sqlite3_config()] interface will return a
  1659. ** non-zero [error code] if a discontinued or unsupported configuration option
  1660. ** is invoked.
  1661. **
  1662. ** <dl>
  1663. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1664. ** <dd>There are no arguments to this option. ^This option sets the
  1665. ** [threading mode] to Single-thread. In other words, it disables
  1666. ** all mutexing and puts SQLite into a mode where it can only be used
  1667. ** by a single thread. ^If SQLite is compiled with
  1668. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1669. ** it is not possible to change the [threading mode] from its default
  1670. ** value of Single-thread and so [sqlite3_config()] will return
  1671. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1672. ** configuration option.</dd>
  1673. **
  1674. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1675. ** <dd>There are no arguments to this option. ^This option sets the
  1676. ** [threading mode] to Multi-thread. In other words, it disables
  1677. ** mutexing on [database connection] and [prepared statement] objects.
  1678. ** The application is responsible for serializing access to
  1679. ** [database connections] and [prepared statements]. But other mutexes
  1680. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1681. ** environment as long as no two threads attempt to use the same
  1682. ** [database connection] at the same time. ^If SQLite is compiled with
  1683. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1684. ** it is not possible to set the Multi-thread [threading mode] and
  1685. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1686. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1687. **
  1688. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1689. ** <dd>There are no arguments to this option. ^This option sets the
  1690. ** [threading mode] to Serialized. In other words, this option enables
  1691. ** all mutexes including the recursive
  1692. ** mutexes on [database connection] and [prepared statement] objects.
  1693. ** In this mode (which is the default when SQLite is compiled with
  1694. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1695. ** to [database connections] and [prepared statements] so that the
  1696. ** application is free to use the same [database connection] or the
  1697. ** same [prepared statement] in different threads at the same time.
  1698. ** ^If SQLite is compiled with
  1699. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1700. ** it is not possible to set the Serialized [threading mode] and
  1701. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1702. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1703. **
  1704. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1705. ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
  1706. ** a pointer to an instance of the [sqlite3_mem_methods] structure.
  1707. ** The argument specifies
  1708. ** alternative low-level memory allocation routines to be used in place of
  1709. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1710. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1711. ** before the [sqlite3_config()] call returns.</dd>
  1712. **
  1713. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1714. ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
  1715. ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
  1716. ** The [sqlite3_mem_methods]
  1717. ** structure is filled with the currently defined memory allocation routines.)^
  1718. ** This option can be used to overload the default memory allocation
  1719. ** routines with a wrapper that simulations memory allocation failure or
  1720. ** tracks memory usage, for example. </dd>
  1721. **
  1722. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1723. ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
  1724. ** interpreted as a boolean, which enables or disables the collection of
  1725. ** memory allocation statistics. ^(When memory allocation statistics are
  1726. ** disabled, the following SQLite interfaces become non-operational:
  1727. ** <ul>
  1728. ** <li> [sqlite3_memory_used()]
  1729. ** <li> [sqlite3_memory_highwater()]
  1730. ** <li> [sqlite3_soft_heap_limit64()]
  1731. ** <li> [sqlite3_status64()]
  1732. ** </ul>)^
  1733. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1734. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1735. ** allocation statistics are disabled by default.
  1736. ** </dd>
  1737. **
  1738. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1739. ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
  1740. ** that SQLite can use for scratch memory. ^(There are three arguments
  1741. ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
  1742. ** aligned memory buffer from which the scratch allocations will be
  1743. ** drawn, the size of each scratch allocation (sz),
  1744. ** and the maximum number of scratch allocations (N).)^
  1745. ** The first argument must be a pointer to an 8-byte aligned buffer
  1746. ** of at least sz*N bytes of memory.
  1747. ** ^SQLite will not use more than one scratch buffers per thread.
  1748. ** ^SQLite will never request a scratch buffer that is more than 6
  1749. ** times the database page size.
  1750. ** ^If SQLite needs needs additional
  1751. ** scratch memory beyond what is provided by this configuration option, then
  1752. ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
  1753. ** ^When the application provides any amount of scratch memory using
  1754. ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
  1755. ** [sqlite3_malloc|heap allocations].
  1756. ** This can help [Robson proof|prevent memory allocation failures] due to heap
  1757. ** fragmentation in low-memory embedded systems.
  1758. ** </dd>
  1759. **
  1760. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1761. ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a static memory buffer
  1762. ** that SQLite can use for the database page cache with the default page
  1763. ** cache implementation.
  1764. ** This configuration should not be used if an application-define page
  1765. ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]
  1766. ** configuration option.
  1767. ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
  1768. ** 8-byte aligned
  1769. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1770. ** The sz argument should be the size of the largest database page
  1771. ** (a power of two between 512 and 65536) plus some extra bytes for each
  1772. ** page header. ^The number of extra bytes needed by the page header
  1773. ** can be determined using the [SQLITE_CONFIG_PCACHE_HDRSZ] option
  1774. ** to [sqlite3_config()].
  1775. ** ^It is harmless, apart from the wasted memory,
  1776. ** for the sz parameter to be larger than necessary. The first
  1777. ** argument should pointer to an 8-byte aligned block of memory that
  1778. ** is at least sz*N bytes of memory, otherwise subsequent behavior is
  1779. ** undefined.
  1780. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1781. ** memory needs for the first N pages that it adds to cache. ^If additional
  1782. ** page cache memory is needed beyond what is provided by this option, then
  1783. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.</dd>
  1784. **
  1785. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1786. ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
  1787. ** that SQLite will use for all of its dynamic memory allocation needs
  1788. ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
  1789. ** [SQLITE_CONFIG_PAGECACHE].
  1790. ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
  1791. ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
  1792. ** [SQLITE_ERROR] if invoked otherwise.
  1793. ** ^There are three arguments to SQLITE_CONFIG_HEAP:
  1794. ** An 8-byte aligned pointer to the memory,
  1795. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1796. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1797. ** to using its default memory allocator (the system malloc() implementation),
  1798. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1799. ** memory pointer is not NULL then the alternative memory
  1800. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1801. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1802. ** boundary or subsequent behavior of SQLite will be undefined.
  1803. ** The minimum allocation size is capped at 2**12. Reasonable values
  1804. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1805. **
  1806. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1807. ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
  1808. ** pointer to an instance of the [sqlite3_mutex_methods] structure.
  1809. ** The argument specifies alternative low-level mutex routines to be used
  1810. ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
  1811. ** the content of the [sqlite3_mutex_methods] structure before the call to
  1812. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1813. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1814. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1815. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1816. ** return [SQLITE_ERROR].</dd>
  1817. **
  1818. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1819. ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
  1820. ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
  1821. ** [sqlite3_mutex_methods]
  1822. ** structure is filled with the currently defined mutex routines.)^
  1823. ** This option can be used to overload the default mutex allocation
  1824. ** routines with a wrapper used to track mutex usage for performance
  1825. ** profiling or testing, for example. ^If SQLite is compiled with
  1826. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1827. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1828. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1829. ** return [SQLITE_ERROR].</dd>
  1830. **
  1831. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1832. ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
  1833. ** the default size of lookaside memory on each [database connection].
  1834. ** The first argument is the
  1835. ** size of each lookaside buffer slot and the second is the number of
  1836. ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
  1837. ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1838. ** option to [sqlite3_db_config()] can be used to change the lookaside
  1839. ** configuration on individual connections.)^ </dd>
  1840. **
  1841. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1842. ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
  1843. ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
  1844. ** the interface to a custom page cache implementation.)^
  1845. ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
  1846. **
  1847. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1848. ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
  1849. ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
  1850. ** the current page cache implementation into that object.)^ </dd>
  1851. **
  1852. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1853. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1854. ** global [error log].
  1855. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1856. ** function with a call signature of void(*)(void*,int,const char*),
  1857. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1858. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1859. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1860. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1861. ** passed through as the first parameter to the application-defined logger
  1862. ** function whenever that function is invoked. ^The second parameter to
  1863. ** the logger function is a copy of the first parameter to the corresponding
  1864. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1865. ** [extended result code]. ^The third parameter passed to the logger is
  1866. ** log message after formatting via [sqlite3_snprintf()].
  1867. ** The SQLite logging interface is not reentrant; the logger function
  1868. ** supplied by the application must not invoke any SQLite interface.
  1869. ** In a multi-threaded application, the application-defined logger
  1870. ** function must be threadsafe. </dd>
  1871. **
  1872. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1873. ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
  1874. ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
  1875. ** then URI handling is globally disabled.)^ ^If URI handling is globally
  1876. ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
  1877. ** [sqlite3_open16()] or
  1878. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1879. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1880. ** connection is opened. ^If it is globally disabled, filenames are
  1881. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1882. ** database connection is opened. ^(By default, URI handling is globally
  1883. ** disabled. The default value may be changed by compiling with the
  1884. ** [SQLITE_USE_URI] symbol defined.)^
  1885. **
  1886. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1887. ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
  1888. ** argument which is interpreted as a boolean in order to enable or disable
  1889. ** the use of covering indices for full table scans in the query optimizer.
  1890. ** ^The default setting is determined
  1891. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1892. ** if that compile-time option is omitted.
  1893. ** The ability to disable the use of covering indices for full table scans
  1894. ** is because some incorrectly coded legacy applications might malfunction
  1895. ** when the optimization is enabled. Providing the ability to
  1896. ** disable the optimization allows the older, buggy application code to work
  1897. ** without change even with newer versions of SQLite.
  1898. **
  1899. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1900. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1901. ** <dd> These options are obsolete and should not be used by new code.
  1902. ** They are retained for backwards compatibility but are now no-ops.
  1903. ** </dd>
  1904. **
  1905. ** [[SQLITE_CONFIG_SQLLOG]]
  1906. ** <dt>SQLITE_CONFIG_SQLLOG
  1907. ** <dd>This option is only available if sqlite is compiled with the
  1908. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1909. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1910. ** The second should be of type (void*). The callback is invoked by the library
  1911. ** in three separate circumstances, identified by the value passed as the
  1912. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1913. ** passed as the second argument has just been opened. The third argument
  1914. ** points to a buffer containing the name of the main database file. If the
  1915. ** fourth parameter is 1, then the SQL statement that the third parameter
  1916. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1917. ** the connection being passed as the second parameter is being closed. The
  1918. ** third parameter is passed NULL In this case. An example of using this
  1919. ** configuration option can be seen in the "test_sqllog.c" source file in
  1920. ** the canonical SQLite source tree.</dd>
  1921. **
  1922. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1923. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1924. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1925. ** that are the default mmap size limit (the default setting for
  1926. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1927. ** ^The default setting can be overridden by each database connection using
  1928. ** either the [PRAGMA mmap_size] command, or by using the
  1929. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1930. ** will be silently truncated if necessary so that it does not exceed the
  1931. ** compile-time maximum mmap size set by the
  1932. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1933. ** ^If either argument to this option is negative, then that argument is
  1934. ** changed to its compile-time default.
  1935. **
  1936. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1937. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1938. ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
  1939. ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
  1940. ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1941. ** that specifies the maximum size of the created heap.
  1942. **
  1943. ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
  1944. ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
  1945. ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
  1946. ** is a pointer to an integer and writes into that integer the number of extra
  1947. ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
  1948. ** The amount of extra space required can change depending on the compiler,
  1949. ** target platform, and SQLite version.
  1950. **
  1951. ** [[SQLITE_CONFIG_PMASZ]]
  1952. ** <dt>SQLITE_CONFIG_PMASZ
  1953. ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
  1954. ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
  1955. ** sorter to that integer. The default minimum PMA Size is set by the
  1956. ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
  1957. ** to help with sort operations when multithreaded sorting
  1958. ** is enabled (using the [PRAGMA threads] command) and the amount of content
  1959. ** to be sorted exceeds the page size times the minimum of the
  1960. ** [PRAGMA cache_size] setting and this value.
  1961. ** </dl>
  1962. */
  1963. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1964. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1965. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1966. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1967. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1968. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1969. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1970. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1971. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1972. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1973. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1974. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1975. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1976. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1977. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1978. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1979. #define SQLITE_CONFIG_URI 17 /* int */
  1980. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1981. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1982. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1983. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1984. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1985. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  1986. #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
  1987. #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
  1988. /*
  1989. ** CAPI3REF: Database Connection Configuration Options
  1990. **
  1991. ** These constants are the available integer configuration options that
  1992. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1993. **
  1994. ** New configuration options may be added in future releases of SQLite.
  1995. ** Existing configuration options might be discontinued. Applications
  1996. ** should check the return code from [sqlite3_db_config()] to make sure that
  1997. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1998. ** non-zero [error code] if a discontinued or unsupported configuration option
  1999. ** is invoked.
  2000. **
  2001. ** <dl>
  2002. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  2003. ** <dd> ^This option takes three additional arguments that determine the
  2004. ** [lookaside memory allocator] configuration for the [database connection].
  2005. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  2006. ** pointer to a memory buffer to use for lookaside memory.
  2007. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  2008. ** may be NULL in which case SQLite will allocate the
  2009. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  2010. ** size of each lookaside buffer slot. ^The third argument is the number of
  2011. ** slots. The size of the buffer in the first argument must be greater than
  2012. ** or equal to the product of the second and third arguments. The buffer
  2013. ** must be aligned to an 8-byte boundary. ^If the second argument to
  2014. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  2015. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  2016. ** configuration for a database connection can only be changed when that
  2017. ** connection is not currently using lookaside memory, or in other words
  2018. ** when the "current value" returned by
  2019. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  2020. ** Any attempt to change the lookaside memory configuration when lookaside
  2021. ** memory is in use leaves the configuration unchanged and returns
  2022. ** [SQLITE_BUSY].)^</dd>
  2023. **
  2024. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  2025. ** <dd> ^This option is used to enable or disable the enforcement of
  2026. ** [foreign key constraints]. There should be two additional arguments.
  2027. ** The first argument is an integer which is 0 to disable FK enforcement,
  2028. ** positive to enable FK enforcement or negative to leave FK enforcement
  2029. ** unchanged. The second parameter is a pointer to an integer into which
  2030. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  2031. ** following this call. The second parameter may be a NULL pointer, in
  2032. ** which case the FK enforcement setting is not reported back. </dd>
  2033. **
  2034. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  2035. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  2036. ** There should be two additional arguments.
  2037. ** The first argument is an integer which is 0 to disable triggers,
  2038. ** positive to enable triggers or negative to leave the setting unchanged.
  2039. ** The second parameter is a pointer to an integer into which
  2040. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  2041. ** following this call. The second parameter may be a NULL pointer, in
  2042. ** which case the trigger setting is not reported back. </dd>
  2043. **
  2044. ** </dl>
  2045. */
  2046. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  2047. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  2048. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  2049. /*
  2050. ** CAPI3REF: Enable Or Disable Extended Result Codes
  2051. ** METHOD: sqlite3
  2052. **
  2053. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  2054. ** [extended result codes] feature of SQLite. ^The extended result
  2055. ** codes are disabled by default for historical compatibility.
  2056. */
  2057. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
  2058. /*
  2059. ** CAPI3REF: Last Insert Rowid
  2060. ** METHOD: sqlite3
  2061. **
  2062. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  2063. ** has a unique 64-bit signed
  2064. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  2065. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  2066. ** names are not also used by explicitly declared columns. ^If
  2067. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  2068. ** is another alias for the rowid.
  2069. **
  2070. ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
  2071. ** most recent successful [INSERT] into a rowid table or [virtual table]
  2072. ** on database connection D.
  2073. ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  2074. ** ^If no successful [INSERT]s into rowid tables
  2075. ** have ever occurred on the database connection D,
  2076. ** then sqlite3_last_insert_rowid(D) returns zero.
  2077. **
  2078. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  2079. ** method, then this routine will return the [rowid] of the inserted
  2080. ** row as long as the trigger or virtual table method is running.
  2081. ** But once the trigger or virtual table method ends, the value returned
  2082. ** by this routine reverts to what it was before the trigger or virtual
  2083. ** table method began.)^
  2084. **
  2085. ** ^An [INSERT] that fails due to a constraint violation is not a
  2086. ** successful [INSERT] and does not change the value returned by this
  2087. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  2088. ** and INSERT OR ABORT make no changes to the return value of this
  2089. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  2090. ** encounters a constraint violation, it does not fail. The
  2091. ** INSERT continues to completion after deleting rows that caused
  2092. ** the constraint problem so INSERT OR REPLACE will always change
  2093. ** the return value of this interface.)^
  2094. **
  2095. ** ^For the purposes of this routine, an [INSERT] is considered to
  2096. ** be successful even if it is subsequently rolled back.
  2097. **
  2098. ** This function is accessible to SQL statements via the
  2099. ** [last_insert_rowid() SQL function].
  2100. **
  2101. ** If a separate thread performs a new [INSERT] on the same
  2102. ** database connection while the [sqlite3_last_insert_rowid()]
  2103. ** function is running and thus changes the last insert [rowid],
  2104. ** then the value returned by [sqlite3_last_insert_rowid()] is
  2105. ** unpredictable and might not equal either the old or the new
  2106. ** last insert [rowid].
  2107. */
  2108. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
  2109. /*
  2110. ** CAPI3REF: Count The Number Of Rows Modified
  2111. ** METHOD: sqlite3
  2112. **
  2113. ** ^This function returns the number of rows modified, inserted or
  2114. ** deleted by the most recently completed INSERT, UPDATE or DELETE
  2115. ** statement on the database connection specified by the only parameter.
  2116. ** ^Executing any other type of SQL statement does not modify the value
  2117. ** returned by this function.
  2118. **
  2119. ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
  2120. ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
  2121. ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
  2122. **
  2123. ** Changes to a view that are intercepted by
  2124. ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
  2125. ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
  2126. ** DELETE statement run on a view is always zero. Only changes made to real
  2127. ** tables are counted.
  2128. **
  2129. ** Things are more complicated if the sqlite3_changes() function is
  2130. ** executed while a trigger program is running. This may happen if the
  2131. ** program uses the [changes() SQL function], or if some other callback
  2132. ** function invokes sqlite3_changes() directly. Essentially:
  2133. **
  2134. ** <ul>
  2135. ** <li> ^(Before entering a trigger program the value returned by
  2136. ** sqlite3_changes() function is saved. After the trigger program
  2137. ** has finished, the original value is restored.)^
  2138. **
  2139. ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
  2140. ** statement sets the value returned by sqlite3_changes()
  2141. ** upon completion as normal. Of course, this value will not include
  2142. ** any changes performed by sub-triggers, as the sqlite3_changes()
  2143. ** value will be saved and restored after each sub-trigger has run.)^
  2144. ** </ul>
  2145. **
  2146. ** ^This means that if the changes() SQL function (or similar) is used
  2147. ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
  2148. ** returns the value as set when the calling statement began executing.
  2149. ** ^If it is used by the second or subsequent such statement within a trigger
  2150. ** program, the value returned reflects the number of rows modified by the
  2151. ** previous INSERT, UPDATE or DELETE statement within the same trigger.
  2152. **
  2153. ** See also the [sqlite3_total_changes()] interface, the
  2154. ** [count_changes pragma], and the [changes() SQL function].
  2155. **
  2156. ** If a separate thread makes changes on the same database connection
  2157. ** while [sqlite3_changes()] is running then the value returned
  2158. ** is unpredictable and not meaningful.
  2159. */
  2160. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
  2161. /*
  2162. ** CAPI3REF: Total Number Of Rows Modified
  2163. ** METHOD: sqlite3
  2164. **
  2165. ** ^This function returns the total number of rows inserted, modified or
  2166. ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
  2167. ** since the database connection was opened, including those executed as
  2168. ** part of trigger programs. ^Executing any other type of SQL statement
  2169. ** does not affect the value returned by sqlite3_total_changes().
  2170. **
  2171. ** ^Changes made as part of [foreign key actions] are included in the
  2172. ** count, but those made as part of REPLACE constraint resolution are
  2173. ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
  2174. ** are not counted.
  2175. **
  2176. ** See also the [sqlite3_changes()] interface, the
  2177. ** [count_changes pragma], and the [total_changes() SQL function].
  2178. **
  2179. ** If a separate thread makes changes on the same database connection
  2180. ** while [sqlite3_total_changes()] is running then the value
  2181. ** returned is unpredictable and not meaningful.
  2182. */
  2183. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
  2184. /*
  2185. ** CAPI3REF: Interrupt A Long-Running Query
  2186. ** METHOD: sqlite3
  2187. **
  2188. ** ^This function causes any pending database operation to abort and
  2189. ** return at its earliest opportunity. This routine is typically
  2190. ** called in response to a user action such as pressing "Cancel"
  2191. ** or Ctrl-C where the user wants a long query operation to halt
  2192. ** immediately.
  2193. **
  2194. ** ^It is safe to call this routine from a thread different from the
  2195. ** thread that is currently running the database operation. But it
  2196. ** is not safe to call this routine with a [database connection] that
  2197. ** is closed or might close before sqlite3_interrupt() returns.
  2198. **
  2199. ** ^If an SQL operation is very nearly finished at the time when
  2200. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2201. ** to be interrupted and might continue to completion.
  2202. **
  2203. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2204. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2205. ** that is inside an explicit transaction, then the entire transaction
  2206. ** will be rolled back automatically.
  2207. **
  2208. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2209. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2210. ** that are started after the sqlite3_interrupt() call and before the
  2211. ** running statements reaches zero are interrupted as if they had been
  2212. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2213. ** that are started after the running statement count reaches zero are
  2214. ** not effected by the sqlite3_interrupt().
  2215. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2216. ** SQL statements is a no-op and has no effect on SQL statements
  2217. ** that are started after the sqlite3_interrupt() call returns.
  2218. **
  2219. ** If the database connection closes while [sqlite3_interrupt()]
  2220. ** is running then bad things will likely happen.
  2221. */
  2222. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
  2223. /*
  2224. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2225. **
  2226. ** These routines are useful during command-line input to determine if the
  2227. ** currently entered text seems to form a complete SQL statement or
  2228. ** if additional input is needed before sending the text into
  2229. ** SQLite for parsing. ^These routines return 1 if the input string
  2230. ** appears to be a complete SQL statement. ^A statement is judged to be
  2231. ** complete if it ends with a semicolon token and is not a prefix of a
  2232. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2233. ** string literals or quoted identifier names or comments are not
  2234. ** independent tokens (they are part of the token in which they are
  2235. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2236. ** and comments that follow the final semicolon are ignored.
  2237. **
  2238. ** ^These routines return 0 if the statement is incomplete. ^If a
  2239. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2240. **
  2241. ** ^These routines do not parse the SQL statements thus
  2242. ** will not detect syntactically incorrect SQL.
  2243. **
  2244. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2245. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2246. ** automatically by sqlite3_complete16(). If that initialization fails,
  2247. ** then the return value from sqlite3_complete16() will be non-zero
  2248. ** regardless of whether or not the input SQL is complete.)^
  2249. **
  2250. ** The input to [sqlite3_complete()] must be a zero-terminated
  2251. ** UTF-8 string.
  2252. **
  2253. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2254. ** UTF-16 string in native byte order.
  2255. */
  2256. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
  2257. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
  2258. /*
  2259. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2260. ** KEYWORDS: {busy-handler callback} {busy handler}
  2261. ** METHOD: sqlite3
  2262. **
  2263. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2264. ** that might be invoked with argument P whenever
  2265. ** an attempt is made to access a database table associated with
  2266. ** [database connection] D when another thread
  2267. ** or process has the table locked.
  2268. ** The sqlite3_busy_handler() interface is used to implement
  2269. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2270. **
  2271. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2272. ** is returned immediately upon encountering the lock. ^If the busy callback
  2273. ** is not NULL, then the callback might be invoked with two arguments.
  2274. **
  2275. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2276. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2277. ** the busy handler callback is the number of times that the busy handler has
  2278. ** been invoked previously for the same locking event. ^If the
  2279. ** busy callback returns 0, then no additional attempts are made to
  2280. ** access the database and [SQLITE_BUSY] is returned
  2281. ** to the application.
  2282. ** ^If the callback returns non-zero, then another attempt
  2283. ** is made to access the database and the cycle repeats.
  2284. **
  2285. ** The presence of a busy handler does not guarantee that it will be invoked
  2286. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2287. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2288. ** to the application instead of invoking the
  2289. ** busy handler.
  2290. ** Consider a scenario where one process is holding a read lock that
  2291. ** it is trying to promote to a reserved lock and
  2292. ** a second process is holding a reserved lock that it is trying
  2293. ** to promote to an exclusive lock. The first process cannot proceed
  2294. ** because it is blocked by the second and the second process cannot
  2295. ** proceed because it is blocked by the first. If both processes
  2296. ** invoke the busy handlers, neither will make any progress. Therefore,
  2297. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2298. ** will induce the first process to release its read lock and allow
  2299. ** the second process to proceed.
  2300. **
  2301. ** ^The default busy callback is NULL.
  2302. **
  2303. ** ^(There can only be a single busy handler defined for each
  2304. ** [database connection]. Setting a new busy handler clears any
  2305. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2306. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2307. ** busy handler and thus clear any previously set busy handler.
  2308. **
  2309. ** The busy callback should not take any actions which modify the
  2310. ** database connection that invoked the busy handler. In other words,
  2311. ** the busy handler is not reentrant. Any such actions
  2312. ** result in undefined behavior.
  2313. **
  2314. ** A busy handler must not close the database connection
  2315. ** or [prepared statement] that invoked the busy handler.
  2316. */
  2317. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2318. /*
  2319. ** CAPI3REF: Set A Busy Timeout
  2320. ** METHOD: sqlite3
  2321. **
  2322. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2323. ** for a specified amount of time when a table is locked. ^The handler
  2324. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2325. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2326. ** the handler returns 0 which causes [sqlite3_step()] to return
  2327. ** [SQLITE_BUSY].
  2328. **
  2329. ** ^Calling this routine with an argument less than or equal to zero
  2330. ** turns off all busy handlers.
  2331. **
  2332. ** ^(There can only be a single busy handler for a particular
  2333. ** [database connection] at any given moment. If another busy handler
  2334. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2335. ** this routine, that other busy handler is cleared.)^
  2336. **
  2337. ** See also: [PRAGMA busy_timeout]
  2338. */
  2339. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
  2340. /*
  2341. ** CAPI3REF: Convenience Routines For Running Queries
  2342. ** METHOD: sqlite3
  2343. **
  2344. ** This is a legacy interface that is preserved for backwards compatibility.
  2345. ** Use of this interface is not recommended.
  2346. **
  2347. ** Definition: A <b>result table</b> is memory data structure created by the
  2348. ** [sqlite3_get_table()] interface. A result table records the
  2349. ** complete query results from one or more queries.
  2350. **
  2351. ** The table conceptually has a number of rows and columns. But
  2352. ** these numbers are not part of the result table itself. These
  2353. ** numbers are obtained separately. Let N be the number of rows
  2354. ** and M be the number of columns.
  2355. **
  2356. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2357. ** There are (N+1)*M elements in the array. The first M pointers point
  2358. ** to zero-terminated strings that contain the names of the columns.
  2359. ** The remaining entries all point to query results. NULL values result
  2360. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2361. ** string representation as returned by [sqlite3_column_text()].
  2362. **
  2363. ** A result table might consist of one or more memory allocations.
  2364. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2365. ** A result table should be deallocated using [sqlite3_free_table()].
  2366. **
  2367. ** ^(As an example of the result table format, suppose a query result
  2368. ** is as follows:
  2369. **
  2370. ** <blockquote><pre>
  2371. ** Name | Age
  2372. ** -----------------------
  2373. ** Alice | 43
  2374. ** Bob | 28
  2375. ** Cindy | 21
  2376. ** </pre></blockquote>
  2377. **
  2378. ** There are two column (M==2) and three rows (N==3). Thus the
  2379. ** result table has 8 entries. Suppose the result table is stored
  2380. ** in an array names azResult. Then azResult holds this content:
  2381. **
  2382. ** <blockquote><pre>
  2383. ** azResult&#91;0] = "Name";
  2384. ** azResult&#91;1] = "Age";
  2385. ** azResult&#91;2] = "Alice";
  2386. ** azResult&#91;3] = "43";
  2387. ** azResult&#91;4] = "Bob";
  2388. ** azResult&#91;5] = "28";
  2389. ** azResult&#91;6] = "Cindy";
  2390. ** azResult&#91;7] = "21";
  2391. ** </pre></blockquote>)^
  2392. **
  2393. ** ^The sqlite3_get_table() function evaluates one or more
  2394. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2395. ** string of its 2nd parameter and returns a result table to the
  2396. ** pointer given in its 3rd parameter.
  2397. **
  2398. ** After the application has finished with the result from sqlite3_get_table(),
  2399. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2400. ** release the memory that was malloced. Because of the way the
  2401. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2402. ** function must not try to call [sqlite3_free()] directly. Only
  2403. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2404. **
  2405. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2406. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2407. ** to any internal data structures of SQLite. It uses only the public
  2408. ** interface defined here. As a consequence, errors that occur in the
  2409. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2410. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2411. ** [sqlite3_errmsg()].
  2412. */
  2413. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  2414. sqlite3 *db, /* An open database */
  2415. const char *zSql, /* SQL to be evaluated */
  2416. char ***pazResult, /* Results of the query */
  2417. int *pnRow, /* Number of result rows written here */
  2418. int *pnColumn, /* Number of result columns written here */
  2419. char **pzErrmsg /* Error msg written here */
  2420. );
  2421. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
  2422. /*
  2423. ** CAPI3REF: Formatted String Printing Functions
  2424. **
  2425. ** These routines are work-alikes of the "printf()" family of functions
  2426. ** from the standard C library.
  2427. ** These routines understand most of the common K&R formatting options,
  2428. ** plus some additional non-standard formats, detailed below.
  2429. ** Note that some of the more obscure formatting options from recent
  2430. ** C-library standards are omitted from this implementation.
  2431. **
  2432. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2433. ** results into memory obtained from [sqlite3_malloc()].
  2434. ** The strings returned by these two routines should be
  2435. ** released by [sqlite3_free()]. ^Both routines return a
  2436. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2437. ** memory to hold the resulting string.
  2438. **
  2439. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2440. ** the standard C library. The result is written into the
  2441. ** buffer supplied as the second parameter whose size is given by
  2442. ** the first parameter. Note that the order of the
  2443. ** first two parameters is reversed from snprintf().)^ This is an
  2444. ** historical accident that cannot be fixed without breaking
  2445. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2446. ** returns a pointer to its buffer instead of the number of
  2447. ** characters actually written into the buffer.)^ We admit that
  2448. ** the number of characters written would be a more useful return
  2449. ** value but we cannot change the implementation of sqlite3_snprintf()
  2450. ** now without breaking compatibility.
  2451. **
  2452. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2453. ** guarantees that the buffer is always zero-terminated. ^The first
  2454. ** parameter "n" is the total size of the buffer, including space for
  2455. ** the zero terminator. So the longest string that can be completely
  2456. ** written will be n-1 characters.
  2457. **
  2458. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2459. **
  2460. ** These routines all implement some additional formatting
  2461. ** options that are useful for constructing SQL statements.
  2462. ** All of the usual printf() formatting options apply. In addition, there
  2463. ** is are "%q", "%Q", "%w" and "%z" options.
  2464. **
  2465. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2466. ** string from the argument list. But %q also doubles every '\'' character.
  2467. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2468. ** character it escapes that character and allows it to be inserted into
  2469. ** the string.
  2470. **
  2471. ** For example, assume the string variable zText contains text as follows:
  2472. **
  2473. ** <blockquote><pre>
  2474. ** char *zText = "It's a happy day!";
  2475. ** </pre></blockquote>
  2476. **
  2477. ** One can use this text in an SQL statement as follows:
  2478. **
  2479. ** <blockquote><pre>
  2480. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2481. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2482. ** sqlite3_free(zSQL);
  2483. ** </pre></blockquote>
  2484. **
  2485. ** Because the %q format string is used, the '\'' character in zText
  2486. ** is escaped and the SQL generated is as follows:
  2487. **
  2488. ** <blockquote><pre>
  2489. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2490. ** </pre></blockquote>
  2491. **
  2492. ** This is correct. Had we used %s instead of %q, the generated SQL
  2493. ** would have looked like this:
  2494. **
  2495. ** <blockquote><pre>
  2496. ** INSERT INTO table1 VALUES('It's a happy day!');
  2497. ** </pre></blockquote>
  2498. **
  2499. ** This second example is an SQL syntax error. As a general rule you should
  2500. ** always use %q instead of %s when inserting text into a string literal.
  2501. **
  2502. ** ^(The %Q option works like %q except it also adds single quotes around
  2503. ** the outside of the total string. Additionally, if the parameter in the
  2504. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2505. ** single quotes).)^ So, for example, one could say:
  2506. **
  2507. ** <blockquote><pre>
  2508. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2509. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2510. ** sqlite3_free(zSQL);
  2511. ** </pre></blockquote>
  2512. **
  2513. ** The code above will render a correct SQL statement in the zSQL
  2514. ** variable even if the zText variable is a NULL pointer.
  2515. **
  2516. ** ^(The "%w" formatting option is like "%q" except that it expects to
  2517. ** be contained within double-quotes instead of single quotes, and it
  2518. ** escapes the double-quote character instead of the single-quote
  2519. ** character.)^ The "%w" formatting option is intended for safely inserting
  2520. ** table and column names into a constructed SQL statement.
  2521. **
  2522. ** ^(The "%z" formatting option works like "%s" but with the
  2523. ** addition that after the string has been read and copied into
  2524. ** the result, [sqlite3_free()] is called on the input string.)^
  2525. */
  2526. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
  2527. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
  2528. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
  2529. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
  2530. /*
  2531. ** CAPI3REF: Memory Allocation Subsystem
  2532. **
  2533. ** The SQLite core uses these three routines for all of its own
  2534. ** internal memory allocation needs. "Core" in the previous sentence
  2535. ** does not include operating-system specific VFS implementation. The
  2536. ** Windows VFS uses native malloc() and free() for some operations.
  2537. **
  2538. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2539. ** of memory at least N bytes in length, where N is the parameter.
  2540. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2541. ** memory, it returns a NULL pointer. ^If the parameter N to
  2542. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2543. ** a NULL pointer.
  2544. **
  2545. ** ^The sqlite3_malloc64(N) routine works just like
  2546. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2547. ** of a signed 32-bit integer.
  2548. **
  2549. ** ^Calling sqlite3_free() with a pointer previously returned
  2550. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2551. ** that it might be reused. ^The sqlite3_free() routine is
  2552. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2553. ** to sqlite3_free() is harmless. After being freed, memory
  2554. ** should neither be read nor written. Even reading previously freed
  2555. ** memory might result in a segmentation fault or other severe error.
  2556. ** Memory corruption, a segmentation fault, or other severe error
  2557. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2558. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2559. **
  2560. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2561. ** prior memory allocation X to be at least N bytes.
  2562. ** ^If the X parameter to sqlite3_realloc(X,N)
  2563. ** is a NULL pointer then its behavior is identical to calling
  2564. ** sqlite3_malloc(N).
  2565. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2566. ** negative then the behavior is exactly the same as calling
  2567. ** sqlite3_free(X).
  2568. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2569. ** of at least N bytes in size or NULL if insufficient memory is available.
  2570. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2571. ** of the prior allocation are copied into the beginning of buffer returned
  2572. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2573. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2574. ** prior allocation is not freed.
  2575. **
  2576. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2577. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2578. ** of a 32-bit signed integer.
  2579. **
  2580. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2581. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2582. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2583. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2584. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2585. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2586. ** the beginning of memory allocation, or if it points to a formerly
  2587. ** valid memory allocation that has now been freed, then the behavior
  2588. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2589. **
  2590. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2591. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2592. ** is always aligned to at least an 8 byte boundary, or to a
  2593. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2594. ** option is used.
  2595. **
  2596. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2597. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2598. ** implementation of these routines to be omitted. That capability
  2599. ** is no longer provided. Only built-in memory allocators can be used.
  2600. **
  2601. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2602. ** the system malloc() and free() directly when converting
  2603. ** filenames between the UTF-8 encoding used by SQLite
  2604. ** and whatever filename encoding is used by the particular Windows
  2605. ** installation. Memory allocation errors were detected, but
  2606. ** they were reported back as [SQLITE_CANTOPEN] or
  2607. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2608. **
  2609. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2610. ** must be either NULL or else pointers obtained from a prior
  2611. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2612. ** not yet been released.
  2613. **
  2614. ** The application must not read or write any part of
  2615. ** a block of memory after it has been released using
  2616. ** [sqlite3_free()] or [sqlite3_realloc()].
  2617. */
  2618. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
  2619. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
  2620. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
  2621. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
  2622. SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
  2623. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
  2624. /*
  2625. ** CAPI3REF: Memory Allocator Statistics
  2626. **
  2627. ** SQLite provides these two interfaces for reporting on the status
  2628. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2629. ** routines, which form the built-in memory allocation subsystem.
  2630. **
  2631. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2632. ** of memory currently outstanding (malloced but not freed).
  2633. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2634. ** value of [sqlite3_memory_used()] since the high-water mark
  2635. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2636. ** [sqlite3_memory_highwater()] include any overhead
  2637. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2638. ** but not overhead added by the any underlying system library
  2639. ** routines that [sqlite3_malloc()] may call.
  2640. **
  2641. ** ^The memory high-water mark is reset to the current value of
  2642. ** [sqlite3_memory_used()] if and only if the parameter to
  2643. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2644. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2645. ** prior to the reset.
  2646. */
  2647. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
  2648. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
  2649. /*
  2650. ** CAPI3REF: Pseudo-Random Number Generator
  2651. **
  2652. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2653. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2654. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2655. ** the build-in random() and randomblob() SQL functions. This interface allows
  2656. ** applications to access the same PRNG for other purposes.
  2657. **
  2658. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2659. ** ^The P parameter can be a NULL pointer.
  2660. **
  2661. ** ^If this routine has not been previously called or if the previous
  2662. ** call had N less than one or a NULL pointer for P, then the PRNG is
  2663. ** seeded using randomness obtained from the xRandomness method of
  2664. ** the default [sqlite3_vfs] object.
  2665. ** ^If the previous call to this routine had an N of 1 or more and a
  2666. ** non-NULL P then the pseudo-randomness is generated
  2667. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2668. ** method.
  2669. */
  2670. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
  2671. /*
  2672. ** CAPI3REF: Compile-Time Authorization Callbacks
  2673. ** METHOD: sqlite3
  2674. **
  2675. ** ^This routine registers an authorizer callback with a particular
  2676. ** [database connection], supplied in the first argument.
  2677. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2678. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2679. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2680. ** points during the compilation process, as logic is being created
  2681. ** to perform various actions, the authorizer callback is invoked to
  2682. ** see if those actions are allowed. ^The authorizer callback should
  2683. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2684. ** specific action but allow the SQL statement to continue to be
  2685. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2686. ** rejected with an error. ^If the authorizer callback returns
  2687. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2688. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2689. ** the authorizer will fail with an error message.
  2690. **
  2691. ** When the callback returns [SQLITE_OK], that means the operation
  2692. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2693. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2694. ** authorizer will fail with an error message explaining that
  2695. ** access is denied.
  2696. **
  2697. ** ^The first parameter to the authorizer callback is a copy of the third
  2698. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2699. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2700. ** the particular action to be authorized. ^The third through sixth parameters
  2701. ** to the callback are zero-terminated strings that contain additional
  2702. ** details about the action to be authorized.
  2703. **
  2704. ** ^If the action code is [SQLITE_READ]
  2705. ** and the callback returns [SQLITE_IGNORE] then the
  2706. ** [prepared statement] statement is constructed to substitute
  2707. ** a NULL value in place of the table column that would have
  2708. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2709. ** return can be used to deny an untrusted user access to individual
  2710. ** columns of a table.
  2711. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2712. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2713. ** [truncate optimization] is disabled and all rows are deleted individually.
  2714. **
  2715. ** An authorizer is used when [sqlite3_prepare | preparing]
  2716. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2717. ** do not try to access data they are not allowed to see, or that they do not
  2718. ** try to execute malicious statements that damage the database. For
  2719. ** example, an application may allow a user to enter arbitrary
  2720. ** SQL queries for evaluation by a database. But the application does
  2721. ** not want the user to be able to make arbitrary changes to the
  2722. ** database. An authorizer could then be put in place while the
  2723. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2724. ** disallows everything except [SELECT] statements.
  2725. **
  2726. ** Applications that need to process SQL from untrusted sources
  2727. ** might also consider lowering resource limits using [sqlite3_limit()]
  2728. ** and limiting database size using the [max_page_count] [PRAGMA]
  2729. ** in addition to using an authorizer.
  2730. **
  2731. ** ^(Only a single authorizer can be in place on a database connection
  2732. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2733. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2734. ** The authorizer is disabled by default.
  2735. **
  2736. ** The authorizer callback must not do anything that will modify
  2737. ** the database connection that invoked the authorizer callback.
  2738. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2739. ** database connections for the meaning of "modify" in this paragraph.
  2740. **
  2741. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2742. ** statement might be re-prepared during [sqlite3_step()] due to a
  2743. ** schema change. Hence, the application should ensure that the
  2744. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2745. **
  2746. ** ^Note that the authorizer callback is invoked only during
  2747. ** [sqlite3_prepare()] or its variants. Authorization is not
  2748. ** performed during statement evaluation in [sqlite3_step()], unless
  2749. ** as stated in the previous paragraph, sqlite3_step() invokes
  2750. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2751. */
  2752. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  2753. sqlite3*,
  2754. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2755. void *pUserData
  2756. );
  2757. /*
  2758. ** CAPI3REF: Authorizer Return Codes
  2759. **
  2760. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2761. ** return either [SQLITE_OK] or one of these two constants in order
  2762. ** to signal SQLite whether or not the action is permitted. See the
  2763. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2764. ** information.
  2765. **
  2766. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2767. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2768. */
  2769. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2770. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2771. /*
  2772. ** CAPI3REF: Authorizer Action Codes
  2773. **
  2774. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2775. ** that is invoked to authorize certain SQL statement actions. The
  2776. ** second parameter to the callback is an integer code that specifies
  2777. ** what action is being authorized. These are the integer action codes that
  2778. ** the authorizer callback may be passed.
  2779. **
  2780. ** These action code values signify what kind of operation is to be
  2781. ** authorized. The 3rd and 4th parameters to the authorization
  2782. ** callback function will be parameters or NULL depending on which of these
  2783. ** codes is used as the second parameter. ^(The 5th parameter to the
  2784. ** authorizer callback is the name of the database ("main", "temp",
  2785. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2786. ** is the name of the inner-most trigger or view that is responsible for
  2787. ** the access attempt or NULL if this access attempt is directly from
  2788. ** top-level SQL code.
  2789. */
  2790. /******************************************* 3rd ************ 4th ***********/
  2791. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2792. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2793. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2794. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2795. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2796. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2797. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2798. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2799. #define SQLITE_DELETE 9 /* Table Name NULL */
  2800. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2801. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2802. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2803. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2804. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2805. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2806. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2807. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2808. #define SQLITE_INSERT 18 /* Table Name NULL */
  2809. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2810. #define SQLITE_READ 20 /* Table Name Column Name */
  2811. #define SQLITE_SELECT 21 /* NULL NULL */
  2812. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2813. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2814. #define SQLITE_ATTACH 24 /* Filename NULL */
  2815. #define SQLITE_DETACH 25 /* Database Name NULL */
  2816. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2817. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2818. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2819. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2820. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2821. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2822. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2823. #define SQLITE_COPY 0 /* No longer used */
  2824. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2825. /*
  2826. ** CAPI3REF: Tracing And Profiling Functions
  2827. ** METHOD: sqlite3
  2828. **
  2829. ** These routines register callback functions that can be used for
  2830. ** tracing and profiling the execution of SQL statements.
  2831. **
  2832. ** ^The callback function registered by sqlite3_trace() is invoked at
  2833. ** various times when an SQL statement is being run by [sqlite3_step()].
  2834. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2835. ** SQL statement text as the statement first begins executing.
  2836. ** ^(Additional sqlite3_trace() callbacks might occur
  2837. ** as each triggered subprogram is entered. The callbacks for triggers
  2838. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2839. **
  2840. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2841. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2842. **
  2843. ** ^The callback function registered by sqlite3_profile() is invoked
  2844. ** as each SQL statement finishes. ^The profile callback contains
  2845. ** the original statement text and an estimate of wall-clock time
  2846. ** of how long that statement took to run. ^The profile callback
  2847. ** time is in units of nanoseconds, however the current implementation
  2848. ** is only capable of millisecond resolution so the six least significant
  2849. ** digits in the time are meaningless. Future versions of SQLite
  2850. ** might provide greater resolution on the profiler callback. The
  2851. ** sqlite3_profile() function is considered experimental and is
  2852. ** subject to change in future versions of SQLite.
  2853. */
  2854. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2855. SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
  2856. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2857. /*
  2858. ** CAPI3REF: Query Progress Callbacks
  2859. ** METHOD: sqlite3
  2860. **
  2861. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2862. ** function X to be invoked periodically during long running calls to
  2863. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2864. ** database connection D. An example use for this
  2865. ** interface is to keep a GUI updated during a large query.
  2866. **
  2867. ** ^The parameter P is passed through as the only parameter to the
  2868. ** callback function X. ^The parameter N is the approximate number of
  2869. ** [virtual machine instructions] that are evaluated between successive
  2870. ** invocations of the callback X. ^If N is less than one then the progress
  2871. ** handler is disabled.
  2872. **
  2873. ** ^Only a single progress handler may be defined at one time per
  2874. ** [database connection]; setting a new progress handler cancels the
  2875. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2876. ** ^The progress handler is also disabled by setting N to a value less
  2877. ** than 1.
  2878. **
  2879. ** ^If the progress callback returns non-zero, the operation is
  2880. ** interrupted. This feature can be used to implement a
  2881. ** "Cancel" button on a GUI progress dialog box.
  2882. **
  2883. ** The progress handler callback must not do anything that will modify
  2884. ** the database connection that invoked the progress handler.
  2885. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2886. ** database connections for the meaning of "modify" in this paragraph.
  2887. **
  2888. */
  2889. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2890. /*
  2891. ** CAPI3REF: Opening A New Database Connection
  2892. ** CONSTRUCTOR: sqlite3
  2893. **
  2894. ** ^These routines open an SQLite database file as specified by the
  2895. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2896. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2897. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2898. ** returned in *ppDb, even if an error occurs. The only exception is that
  2899. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2900. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2901. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2902. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2903. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2904. ** an English language description of the error following a failure of any
  2905. ** of the sqlite3_open() routines.
  2906. **
  2907. ** ^The default encoding will be UTF-8 for databases created using
  2908. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  2909. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  2910. **
  2911. ** Whether or not an error occurs when it is opened, resources
  2912. ** associated with the [database connection] handle should be released by
  2913. ** passing it to [sqlite3_close()] when it is no longer required.
  2914. **
  2915. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2916. ** except that it accepts two additional parameters for additional control
  2917. ** over the new database connection. ^(The flags parameter to
  2918. ** sqlite3_open_v2() can take one of
  2919. ** the following three values, optionally combined with the
  2920. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2921. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2922. **
  2923. ** <dl>
  2924. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2925. ** <dd>The database is opened in read-only mode. If the database does not
  2926. ** already exist, an error is returned.</dd>)^
  2927. **
  2928. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2929. ** <dd>The database is opened for reading and writing if possible, or reading
  2930. ** only if the file is write protected by the operating system. In either
  2931. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2932. **
  2933. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2934. ** <dd>The database is opened for reading and writing, and is created if
  2935. ** it does not already exist. This is the behavior that is always used for
  2936. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2937. ** </dl>
  2938. **
  2939. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2940. ** combinations shown above optionally combined with other
  2941. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2942. ** then the behavior is undefined.
  2943. **
  2944. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2945. ** opens in the multi-thread [threading mode] as long as the single-thread
  2946. ** mode has not been set at compile-time or start-time. ^If the
  2947. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2948. ** in the serialized [threading mode] unless single-thread was
  2949. ** previously selected at compile-time or start-time.
  2950. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2951. ** eligible to use [shared cache mode], regardless of whether or not shared
  2952. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2953. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2954. ** participate in [shared cache mode] even if it is enabled.
  2955. **
  2956. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2957. ** [sqlite3_vfs] object that defines the operating system interface that
  2958. ** the new database connection should use. ^If the fourth parameter is
  2959. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2960. **
  2961. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2962. ** is created for the connection. ^This in-memory database will vanish when
  2963. ** the database connection is closed. Future versions of SQLite might
  2964. ** make use of additional special filenames that begin with the ":" character.
  2965. ** It is recommended that when a database filename actually does begin with
  2966. ** a ":" character you should prefix the filename with a pathname such as
  2967. ** "./" to avoid ambiguity.
  2968. **
  2969. ** ^If the filename is an empty string, then a private, temporary
  2970. ** on-disk database will be created. ^This private database will be
  2971. ** automatically deleted as soon as the database connection is closed.
  2972. **
  2973. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2974. **
  2975. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2976. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2977. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2978. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2979. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2980. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2981. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2982. ** by default, but future releases of SQLite might enable URI filename
  2983. ** interpretation by default. See "[URI filenames]" for additional
  2984. ** information.
  2985. **
  2986. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2987. ** authority, then it must be either an empty string or the string
  2988. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2989. ** error is returned to the caller. ^The fragment component of a URI, if
  2990. ** present, is ignored.
  2991. **
  2992. ** ^SQLite uses the path component of the URI as the name of the disk file
  2993. ** which contains the database. ^If the path begins with a '/' character,
  2994. ** then it is interpreted as an absolute path. ^If the path does not begin
  2995. ** with a '/' (meaning that the authority section is omitted from the URI)
  2996. ** then the path is interpreted as a relative path.
  2997. ** ^(On windows, the first component of an absolute path
  2998. ** is a drive specification (e.g. "C:").)^
  2999. **
  3000. ** [[core URI query parameters]]
  3001. ** The query component of a URI may contain parameters that are interpreted
  3002. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  3003. ** SQLite and its built-in [VFSes] interpret the
  3004. ** following query parameters:
  3005. **
  3006. ** <ul>
  3007. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  3008. ** a VFS object that provides the operating system interface that should
  3009. ** be used to access the database file on disk. ^If this option is set to
  3010. ** an empty string the default VFS object is used. ^Specifying an unknown
  3011. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  3012. ** present, then the VFS specified by the option takes precedence over
  3013. ** the value passed as the fourth parameter to sqlite3_open_v2().
  3014. **
  3015. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  3016. ** "rwc", or "memory". Attempting to set it to any other value is
  3017. ** an error)^.
  3018. ** ^If "ro" is specified, then the database is opened for read-only
  3019. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  3020. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  3021. ** "rw", then the database is opened for read-write (but not create)
  3022. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  3023. ** been set. ^Value "rwc" is equivalent to setting both
  3024. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  3025. ** set to "memory" then a pure [in-memory database] that never reads
  3026. ** or writes from disk is used. ^It is an error to specify a value for
  3027. ** the mode parameter that is less restrictive than that specified by
  3028. ** the flags passed in the third parameter to sqlite3_open_v2().
  3029. **
  3030. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  3031. ** "private". ^Setting it to "shared" is equivalent to setting the
  3032. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  3033. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  3034. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  3035. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  3036. ** a URI filename, its value overrides any behavior requested by setting
  3037. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  3038. **
  3039. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  3040. ** [powersafe overwrite] property does or does not apply to the
  3041. ** storage media on which the database file resides.
  3042. **
  3043. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  3044. ** which if set disables file locking in rollback journal modes. This
  3045. ** is useful for accessing a database on a filesystem that does not
  3046. ** support locking. Caution: Database corruption might result if two
  3047. ** or more processes write to the same database and any one of those
  3048. ** processes uses nolock=1.
  3049. **
  3050. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  3051. ** parameter that indicates that the database file is stored on
  3052. ** read-only media. ^When immutable is set, SQLite assumes that the
  3053. ** database file cannot be changed, even by a process with higher
  3054. ** privilege, and so the database is opened read-only and all locking
  3055. ** and change detection is disabled. Caution: Setting the immutable
  3056. ** property on a database file that does in fact change can result
  3057. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  3058. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  3059. **
  3060. ** </ul>
  3061. **
  3062. ** ^Specifying an unknown parameter in the query component of a URI is not an
  3063. ** error. Future versions of SQLite might understand additional query
  3064. ** parameters. See "[query parameters with special meaning to SQLite]" for
  3065. ** additional information.
  3066. **
  3067. ** [[URI filename examples]] <h3>URI filename examples</h3>
  3068. **
  3069. ** <table border="1" align=center cellpadding=5>
  3070. ** <tr><th> URI filenames <th> Results
  3071. ** <tr><td> file:data.db <td>
  3072. ** Open the file "data.db" in the current directory.
  3073. ** <tr><td> file:/home/fred/data.db<br>
  3074. ** file:///home/fred/data.db <br>
  3075. ** file://localhost/home/fred/data.db <br> <td>
  3076. ** Open the database file "/home/fred/data.db".
  3077. ** <tr><td> file://darkstar/home/fred/data.db <td>
  3078. ** An error. "darkstar" is not a recognized authority.
  3079. ** <tr><td style="white-space:nowrap">
  3080. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  3081. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  3082. ** C:. Note that the %20 escaping in this example is not strictly
  3083. ** necessary - space characters can be used literally
  3084. ** in URI filenames.
  3085. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  3086. ** Open file "data.db" in the current directory for read-only access.
  3087. ** Regardless of whether or not shared-cache mode is enabled by
  3088. ** default, use a private cache.
  3089. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  3090. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  3091. ** that uses dot-files in place of posix advisory locking.
  3092. ** <tr><td> file:data.db?mode=readonly <td>
  3093. ** An error. "readonly" is not a valid option for the "mode" parameter.
  3094. ** </table>
  3095. **
  3096. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  3097. ** query components of a URI. A hexadecimal escape sequence consists of a
  3098. ** percent sign - "%" - followed by exactly two hexadecimal digits
  3099. ** specifying an octet value. ^Before the path or query components of a
  3100. ** URI filename are interpreted, they are encoded using UTF-8 and all
  3101. ** hexadecimal escape sequences replaced by a single byte containing the
  3102. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  3103. ** the results are undefined.
  3104. **
  3105. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  3106. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  3107. ** codepage is currently defined. Filenames containing international
  3108. ** characters must be converted to UTF-8 prior to passing them into
  3109. ** sqlite3_open() or sqlite3_open_v2().
  3110. **
  3111. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  3112. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  3113. ** features that require the use of temporary files may fail.
  3114. **
  3115. ** See also: [sqlite3_temp_directory]
  3116. */
  3117. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  3118. const char *filename, /* Database filename (UTF-8) */
  3119. sqlite3 **ppDb /* OUT: SQLite db handle */
  3120. );
  3121. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  3122. const void *filename, /* Database filename (UTF-16) */
  3123. sqlite3 **ppDb /* OUT: SQLite db handle */
  3124. );
  3125. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  3126. const char *filename, /* Database filename (UTF-8) */
  3127. sqlite3 **ppDb, /* OUT: SQLite db handle */
  3128. int flags, /* Flags */
  3129. const char *zVfs /* Name of VFS module to use */
  3130. );
  3131. /*
  3132. ** CAPI3REF: Obtain Values For URI Parameters
  3133. **
  3134. ** These are utility routines, useful to VFS implementations, that check
  3135. ** to see if a database file was a URI that contained a specific query
  3136. ** parameter, and if so obtains the value of that query parameter.
  3137. **
  3138. ** If F is the database filename pointer passed into the xOpen() method of
  3139. ** a VFS implementation when the flags parameter to xOpen() has one or
  3140. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  3141. ** P is the name of the query parameter, then
  3142. ** sqlite3_uri_parameter(F,P) returns the value of the P
  3143. ** parameter if it exists or a NULL pointer if P does not appear as a
  3144. ** query parameter on F. If P is a query parameter of F
  3145. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  3146. ** a pointer to an empty string.
  3147. **
  3148. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  3149. ** parameter and returns true (1) or false (0) according to the value
  3150. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  3151. ** value of query parameter P is one of "yes", "true", or "on" in any
  3152. ** case or if the value begins with a non-zero number. The
  3153. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  3154. ** query parameter P is one of "no", "false", or "off" in any case or
  3155. ** if the value begins with a numeric zero. If P is not a query
  3156. ** parameter on F or if the value of P is does not match any of the
  3157. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  3158. **
  3159. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  3160. ** 64-bit signed integer and returns that integer, or D if P does not
  3161. ** exist. If the value of P is something other than an integer, then
  3162. ** zero is returned.
  3163. **
  3164. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  3165. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  3166. ** is not a database file pathname pointer that SQLite passed into the xOpen
  3167. ** VFS method, then the behavior of this routine is undefined and probably
  3168. ** undesirable.
  3169. */
  3170. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  3171. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  3172. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  3173. /*
  3174. ** CAPI3REF: Error Codes And Messages
  3175. ** METHOD: sqlite3
  3176. **
  3177. ** ^If the most recent sqlite3_* API call associated with
  3178. ** [database connection] D failed, then the sqlite3_errcode(D) interface
  3179. ** returns the numeric [result code] or [extended result code] for that
  3180. ** API call.
  3181. ** If the most recent API call was successful,
  3182. ** then the return value from sqlite3_errcode() is undefined.
  3183. ** ^The sqlite3_extended_errcode()
  3184. ** interface is the same except that it always returns the
  3185. ** [extended result code] even when extended result codes are
  3186. ** disabled.
  3187. **
  3188. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3189. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3190. ** ^(Memory to hold the error message string is managed internally.
  3191. ** The application does not need to worry about freeing the result.
  3192. ** However, the error string might be overwritten or deallocated by
  3193. ** subsequent calls to other SQLite interface functions.)^
  3194. **
  3195. ** ^The sqlite3_errstr() interface returns the English-language text
  3196. ** that describes the [result code], as UTF-8.
  3197. ** ^(Memory to hold the error message string is managed internally
  3198. ** and must not be freed by the application)^.
  3199. **
  3200. ** When the serialized [threading mode] is in use, it might be the
  3201. ** case that a second error occurs on a separate thread in between
  3202. ** the time of the first error and the call to these interfaces.
  3203. ** When that happens, the second error will be reported since these
  3204. ** interfaces always report the most recent result. To avoid
  3205. ** this, each thread can obtain exclusive use of the [database connection] D
  3206. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3207. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3208. ** all calls to the interfaces listed here are completed.
  3209. **
  3210. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3211. ** was invoked incorrectly by the application. In that case, the
  3212. ** error code and message may or may not be set.
  3213. */
  3214. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
  3215. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
  3216. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
  3217. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
  3218. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
  3219. /*
  3220. ** CAPI3REF: Prepared Statement Object
  3221. ** KEYWORDS: {prepared statement} {prepared statements}
  3222. **
  3223. ** An instance of this object represents a single SQL statement that
  3224. ** has been compiled into binary form and is ready to be evaluated.
  3225. **
  3226. ** Think of each SQL statement as a separate computer program. The
  3227. ** original SQL text is source code. A prepared statement object
  3228. ** is the compiled object code. All SQL must be converted into a
  3229. ** prepared statement before it can be run.
  3230. **
  3231. ** The life-cycle of a prepared statement object usually goes like this:
  3232. **
  3233. ** <ol>
  3234. ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
  3235. ** <li> Bind values to [parameters] using the sqlite3_bind_*()
  3236. ** interfaces.
  3237. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3238. ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
  3239. ** to step 2. Do this zero or more times.
  3240. ** <li> Destroy the object using [sqlite3_finalize()].
  3241. ** </ol>
  3242. */
  3243. typedef struct sqlite3_stmt sqlite3_stmt;
  3244. /*
  3245. ** CAPI3REF: Run-time Limits
  3246. ** METHOD: sqlite3
  3247. **
  3248. ** ^(This interface allows the size of various constructs to be limited
  3249. ** on a connection by connection basis. The first parameter is the
  3250. ** [database connection] whose limit is to be set or queried. The
  3251. ** second parameter is one of the [limit categories] that define a
  3252. ** class of constructs to be size limited. The third parameter is the
  3253. ** new limit for that construct.)^
  3254. **
  3255. ** ^If the new limit is a negative number, the limit is unchanged.
  3256. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3257. ** [limits | hard upper bound]
  3258. ** set at compile-time by a C preprocessor macro called
  3259. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3260. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3261. ** ^Attempts to increase a limit above its hard upper bound are
  3262. ** silently truncated to the hard upper bound.
  3263. **
  3264. ** ^Regardless of whether or not the limit was changed, the
  3265. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3266. ** ^Hence, to find the current value of a limit without changing it,
  3267. ** simply invoke this interface with the third parameter set to -1.
  3268. **
  3269. ** Run-time limits are intended for use in applications that manage
  3270. ** both their own internal database and also databases that are controlled
  3271. ** by untrusted external sources. An example application might be a
  3272. ** web browser that has its own databases for storing history and
  3273. ** separate databases controlled by JavaScript applications downloaded
  3274. ** off the Internet. The internal databases can be given the
  3275. ** large, default limits. Databases managed by external sources can
  3276. ** be given much smaller limits designed to prevent a denial of service
  3277. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3278. ** interface to further control untrusted SQL. The size of the database
  3279. ** created by an untrusted script can be contained using the
  3280. ** [max_page_count] [PRAGMA].
  3281. **
  3282. ** New run-time limit categories may be added in future releases.
  3283. */
  3284. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
  3285. /*
  3286. ** CAPI3REF: Run-Time Limit Categories
  3287. ** KEYWORDS: {limit category} {*limit categories}
  3288. **
  3289. ** These constants define various performance limits
  3290. ** that can be lowered at run-time using [sqlite3_limit()].
  3291. ** The synopsis of the meanings of the various limits is shown below.
  3292. ** Additional information is available at [limits | Limits in SQLite].
  3293. **
  3294. ** <dl>
  3295. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3296. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3297. **
  3298. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3299. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3300. **
  3301. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3302. ** <dd>The maximum number of columns in a table definition or in the
  3303. ** result set of a [SELECT] or the maximum number of columns in an index
  3304. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3305. **
  3306. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3307. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3308. **
  3309. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3310. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3311. **
  3312. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3313. ** <dd>The maximum number of instructions in a virtual machine program
  3314. ** used to implement an SQL statement. This limit is not currently
  3315. ** enforced, though that might be added in some future release of
  3316. ** SQLite.</dd>)^
  3317. **
  3318. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3319. ** <dd>The maximum number of arguments on a function.</dd>)^
  3320. **
  3321. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3322. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3323. **
  3324. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3325. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3326. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3327. ** [GLOB] operators.</dd>)^
  3328. **
  3329. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3330. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3331. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3332. **
  3333. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3334. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3335. **
  3336. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3337. ** <dd>The maximum number of auxiliary worker threads that a single
  3338. ** [prepared statement] may start.</dd>)^
  3339. ** </dl>
  3340. */
  3341. #define SQLITE_LIMIT_LENGTH 0
  3342. #define SQLITE_LIMIT_SQL_LENGTH 1
  3343. #define SQLITE_LIMIT_COLUMN 2
  3344. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3345. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3346. #define SQLITE_LIMIT_VDBE_OP 5
  3347. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3348. #define SQLITE_LIMIT_ATTACHED 7
  3349. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3350. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3351. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3352. #define SQLITE_LIMIT_WORKER_THREADS 11
  3353. /*
  3354. ** CAPI3REF: Compiling An SQL Statement
  3355. ** KEYWORDS: {SQL statement compiler}
  3356. ** METHOD: sqlite3
  3357. ** CONSTRUCTOR: sqlite3_stmt
  3358. **
  3359. ** To execute an SQL query, it must first be compiled into a byte-code
  3360. ** program using one of these routines.
  3361. **
  3362. ** The first argument, "db", is a [database connection] obtained from a
  3363. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3364. ** [sqlite3_open16()]. The database connection must not have been closed.
  3365. **
  3366. ** The second argument, "zSql", is the statement to be compiled, encoded
  3367. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3368. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3369. ** use UTF-16.
  3370. **
  3371. ** ^If the nByte argument is negative, then zSql is read up to the
  3372. ** first zero terminator. ^If nByte is positive, then it is the
  3373. ** number of bytes read from zSql. ^If nByte is zero, then no prepared
  3374. ** statement is generated.
  3375. ** If the caller knows that the supplied string is nul-terminated, then
  3376. ** there is a small performance advantage to passing an nByte parameter that
  3377. ** is the number of bytes in the input string <i>including</i>
  3378. ** the nul-terminator.
  3379. **
  3380. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3381. ** past the end of the first SQL statement in zSql. These routines only
  3382. ** compile the first statement in zSql, so *pzTail is left pointing to
  3383. ** what remains uncompiled.
  3384. **
  3385. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3386. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3387. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3388. ** string or a comment) then *ppStmt is set to NULL.
  3389. ** The calling procedure is responsible for deleting the compiled
  3390. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3391. ** ppStmt may not be NULL.
  3392. **
  3393. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3394. ** otherwise an [error code] is returned.
  3395. **
  3396. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3397. ** recommended for all new programs. The two older interfaces are retained
  3398. ** for backwards compatibility, but their use is discouraged.
  3399. ** ^In the "v2" interfaces, the prepared statement
  3400. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3401. ** original SQL text. This causes the [sqlite3_step()] interface to
  3402. ** behave differently in three ways:
  3403. **
  3404. ** <ol>
  3405. ** <li>
  3406. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3407. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3408. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3409. ** retries will occur before sqlite3_step() gives up and returns an error.
  3410. ** </li>
  3411. **
  3412. ** <li>
  3413. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3414. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3415. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3416. ** and the application would have to make a second call to [sqlite3_reset()]
  3417. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3418. ** interfaces, the underlying reason for the error is returned immediately.
  3419. ** </li>
  3420. **
  3421. ** <li>
  3422. ** ^If the specific value bound to [parameter | host parameter] in the
  3423. ** WHERE clause might influence the choice of query plan for a statement,
  3424. ** then the statement will be automatically recompiled, as if there had been
  3425. ** a schema change, on the first [sqlite3_step()] call following any change
  3426. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3427. ** ^The specific value of WHERE-clause [parameter] might influence the
  3428. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3429. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3430. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3431. ** </li>
  3432. ** </ol>
  3433. */
  3434. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  3435. sqlite3 *db, /* Database handle */
  3436. const char *zSql, /* SQL statement, UTF-8 encoded */
  3437. int nByte, /* Maximum length of zSql in bytes. */
  3438. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3439. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3440. );
  3441. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  3442. sqlite3 *db, /* Database handle */
  3443. const char *zSql, /* SQL statement, UTF-8 encoded */
  3444. int nByte, /* Maximum length of zSql in bytes. */
  3445. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3446. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3447. );
  3448. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  3449. sqlite3 *db, /* Database handle */
  3450. const void *zSql, /* SQL statement, UTF-16 encoded */
  3451. int nByte, /* Maximum length of zSql in bytes. */
  3452. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3453. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3454. );
  3455. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  3456. sqlite3 *db, /* Database handle */
  3457. const void *zSql, /* SQL statement, UTF-16 encoded */
  3458. int nByte, /* Maximum length of zSql in bytes. */
  3459. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3460. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3461. );
  3462. /*
  3463. ** CAPI3REF: Retrieving Statement SQL
  3464. ** METHOD: sqlite3_stmt
  3465. **
  3466. ** ^This interface can be used to retrieve a saved copy of the original
  3467. ** SQL text used to create a [prepared statement] if that statement was
  3468. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3469. */
  3470. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
  3471. /*
  3472. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3473. ** METHOD: sqlite3_stmt
  3474. **
  3475. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3476. ** and only if the [prepared statement] X makes no direct changes to
  3477. ** the content of the database file.
  3478. **
  3479. ** Note that [application-defined SQL functions] or
  3480. ** [virtual tables] might change the database indirectly as a side effect.
  3481. ** ^(For example, if an application defines a function "eval()" that
  3482. ** calls [sqlite3_exec()], then the following SQL statement would
  3483. ** change the database file through side-effects:
  3484. **
  3485. ** <blockquote><pre>
  3486. ** SELECT eval('DELETE FROM t1') FROM t2;
  3487. ** </pre></blockquote>
  3488. **
  3489. ** But because the [SELECT] statement does not change the database file
  3490. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3491. **
  3492. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3493. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3494. ** since the statements themselves do not actually modify the database but
  3495. ** rather they control the timing of when other statements modify the
  3496. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3497. ** sqlite3_stmt_readonly() to return true since, while those statements
  3498. ** change the configuration of a database connection, they do not make
  3499. ** changes to the content of the database files on disk.
  3500. */
  3501. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3502. /*
  3503. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3504. ** METHOD: sqlite3_stmt
  3505. **
  3506. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3507. ** [prepared statement] S has been stepped at least once using
  3508. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3509. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3510. ** interface returns false if S is a NULL pointer. If S is not a
  3511. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3512. ** object, then the behavior is undefined and probably undesirable.
  3513. **
  3514. ** This interface can be used in combination [sqlite3_next_stmt()]
  3515. ** to locate all prepared statements associated with a database
  3516. ** connection that are in need of being reset. This can be used,
  3517. ** for example, in diagnostic routines to search for prepared
  3518. ** statements that are holding a transaction open.
  3519. */
  3520. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
  3521. /*
  3522. ** CAPI3REF: Dynamically Typed Value Object
  3523. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3524. **
  3525. ** SQLite uses the sqlite3_value object to represent all values
  3526. ** that can be stored in a database table. SQLite uses dynamic typing
  3527. ** for the values it stores. ^Values stored in sqlite3_value objects
  3528. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3529. **
  3530. ** An sqlite3_value object may be either "protected" or "unprotected".
  3531. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3532. ** will accept either a protected or an unprotected sqlite3_value.
  3533. ** Every interface that accepts sqlite3_value arguments specifies
  3534. ** whether or not it requires a protected sqlite3_value. The
  3535. ** [sqlite3_value_dup()] interface can be used to construct a new
  3536. ** protected sqlite3_value from an unprotected sqlite3_value.
  3537. **
  3538. ** The terms "protected" and "unprotected" refer to whether or not
  3539. ** a mutex is held. An internal mutex is held for a protected
  3540. ** sqlite3_value object but no mutex is held for an unprotected
  3541. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3542. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3543. ** or if SQLite is run in one of reduced mutex modes
  3544. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3545. ** then there is no distinction between protected and unprotected
  3546. ** sqlite3_value objects and they can be used interchangeably. However,
  3547. ** for maximum code portability it is recommended that applications
  3548. ** still make the distinction between protected and unprotected
  3549. ** sqlite3_value objects even when not strictly required.
  3550. **
  3551. ** ^The sqlite3_value objects that are passed as parameters into the
  3552. ** implementation of [application-defined SQL functions] are protected.
  3553. ** ^The sqlite3_value object returned by
  3554. ** [sqlite3_column_value()] is unprotected.
  3555. ** Unprotected sqlite3_value objects may only be used with
  3556. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3557. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3558. ** interfaces require protected sqlite3_value objects.
  3559. */
  3560. typedef struct Mem sqlite3_value;
  3561. /*
  3562. ** CAPI3REF: SQL Function Context Object
  3563. **
  3564. ** The context in which an SQL function executes is stored in an
  3565. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3566. ** is always first parameter to [application-defined SQL functions].
  3567. ** The application-defined SQL function implementation will pass this
  3568. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3569. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3570. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3571. ** and/or [sqlite3_set_auxdata()].
  3572. */
  3573. typedef struct sqlite3_context sqlite3_context;
  3574. /*
  3575. ** CAPI3REF: Binding Values To Prepared Statements
  3576. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3577. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3578. ** METHOD: sqlite3_stmt
  3579. **
  3580. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3581. ** literals may be replaced by a [parameter] that matches one of following
  3582. ** templates:
  3583. **
  3584. ** <ul>
  3585. ** <li> ?
  3586. ** <li> ?NNN
  3587. ** <li> :VVV
  3588. ** <li> @VVV
  3589. ** <li> $VVV
  3590. ** </ul>
  3591. **
  3592. ** In the templates above, NNN represents an integer literal,
  3593. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3594. ** parameters (also called "host parameter names" or "SQL parameters")
  3595. ** can be set using the sqlite3_bind_*() routines defined here.
  3596. **
  3597. ** ^The first argument to the sqlite3_bind_*() routines is always
  3598. ** a pointer to the [sqlite3_stmt] object returned from
  3599. ** [sqlite3_prepare_v2()] or its variants.
  3600. **
  3601. ** ^The second argument is the index of the SQL parameter to be set.
  3602. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3603. ** SQL parameter is used more than once, second and subsequent
  3604. ** occurrences have the same index as the first occurrence.
  3605. ** ^The index for named parameters can be looked up using the
  3606. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3607. ** for "?NNN" parameters is the value of NNN.
  3608. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3609. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3610. **
  3611. ** ^The third argument is the value to bind to the parameter.
  3612. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3613. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3614. ** is ignored and the end result is the same as sqlite3_bind_null().
  3615. **
  3616. ** ^(In those routines that have a fourth argument, its value is the
  3617. ** number of bytes in the parameter. To be clear: the value is the
  3618. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3619. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3620. ** is negative, then the length of the string is
  3621. ** the number of bytes up to the first zero terminator.
  3622. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3623. ** the behavior is undefined.
  3624. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3625. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3626. ** that parameter must be the byte offset
  3627. ** where the NUL terminator would occur assuming the string were NUL
  3628. ** terminated. If any NUL characters occur at byte offsets less than
  3629. ** the value of the fourth parameter then the resulting string value will
  3630. ** contain embedded NULs. The result of expressions involving strings
  3631. ** with embedded NULs is undefined.
  3632. **
  3633. ** ^The fifth argument to the BLOB and string binding interfaces
  3634. ** is a destructor used to dispose of the BLOB or
  3635. ** string after SQLite has finished with it. ^The destructor is called
  3636. ** to dispose of the BLOB or string even if the call to bind API fails.
  3637. ** ^If the fifth argument is
  3638. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3639. ** information is in static, unmanaged space and does not need to be freed.
  3640. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3641. ** SQLite makes its own private copy of the data immediately, before
  3642. ** the sqlite3_bind_*() routine returns.
  3643. **
  3644. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3645. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3646. ** to specify the encoding of the text in the third parameter. If
  3647. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3648. ** allowed values shown above, or if the text encoding is different
  3649. ** from the encoding specified by the sixth parameter, then the behavior
  3650. ** is undefined.
  3651. **
  3652. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3653. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3654. ** (just an integer to hold its size) while it is being processed.
  3655. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3656. ** content is later written using
  3657. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3658. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3659. **
  3660. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3661. ** for the [prepared statement] or with a prepared statement for which
  3662. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3663. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3664. ** routine is passed a [prepared statement] that has been finalized, the
  3665. ** result is undefined and probably harmful.
  3666. **
  3667. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3668. ** ^Unbound parameters are interpreted as NULL.
  3669. **
  3670. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3671. ** [error code] if anything goes wrong.
  3672. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  3673. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  3674. ** [SQLITE_MAX_LENGTH].
  3675. ** ^[SQLITE_RANGE] is returned if the parameter
  3676. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3677. **
  3678. ** See also: [sqlite3_bind_parameter_count()],
  3679. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3680. */
  3681. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3682. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  3683. void(*)(void*));
  3684. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
  3685. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
  3686. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3687. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
  3688. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  3689. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3690. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  3691. void(*)(void*), unsigned char encoding);
  3692. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3693. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3694. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt*, int, sqlite3_uint64);
  3695. /*
  3696. ** CAPI3REF: Number Of SQL Parameters
  3697. ** METHOD: sqlite3_stmt
  3698. **
  3699. ** ^This routine can be used to find the number of [SQL parameters]
  3700. ** in a [prepared statement]. SQL parameters are tokens of the
  3701. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3702. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3703. ** to the parameters at a later time.
  3704. **
  3705. ** ^(This routine actually returns the index of the largest (rightmost)
  3706. ** parameter. For all forms except ?NNN, this will correspond to the
  3707. ** number of unique parameters. If parameters of the ?NNN form are used,
  3708. ** there may be gaps in the list.)^
  3709. **
  3710. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3711. ** [sqlite3_bind_parameter_name()], and
  3712. ** [sqlite3_bind_parameter_index()].
  3713. */
  3714. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
  3715. /*
  3716. ** CAPI3REF: Name Of A Host Parameter
  3717. ** METHOD: sqlite3_stmt
  3718. **
  3719. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3720. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3721. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3722. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3723. ** respectively.
  3724. ** In other words, the initial ":" or "$" or "@" or "?"
  3725. ** is included as part of the name.)^
  3726. ** ^Parameters of the form "?" without a following integer have no name
  3727. ** and are referred to as "nameless" or "anonymous parameters".
  3728. **
  3729. ** ^The first host parameter has an index of 1, not 0.
  3730. **
  3731. ** ^If the value N is out of range or if the N-th parameter is
  3732. ** nameless, then NULL is returned. ^The returned string is
  3733. ** always in UTF-8 encoding even if the named parameter was
  3734. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3735. ** [sqlite3_prepare16_v2()].
  3736. **
  3737. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3738. ** [sqlite3_bind_parameter_count()], and
  3739. ** [sqlite3_bind_parameter_index()].
  3740. */
  3741. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3742. /*
  3743. ** CAPI3REF: Index Of A Parameter With A Given Name
  3744. ** METHOD: sqlite3_stmt
  3745. **
  3746. ** ^Return the index of an SQL parameter given its name. ^The
  3747. ** index value returned is suitable for use as the second
  3748. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3749. ** is returned if no matching parameter is found. ^The parameter
  3750. ** name must be given in UTF-8 even if the original statement
  3751. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3752. **
  3753. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3754. ** [sqlite3_bind_parameter_count()], and
  3755. ** [sqlite3_bind_parameter_index()].
  3756. */
  3757. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3758. /*
  3759. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3760. ** METHOD: sqlite3_stmt
  3761. **
  3762. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3763. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3764. ** ^Use this routine to reset all host parameters to NULL.
  3765. */
  3766. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
  3767. /*
  3768. ** CAPI3REF: Number Of Columns In A Result Set
  3769. ** METHOD: sqlite3_stmt
  3770. **
  3771. ** ^Return the number of columns in the result set returned by the
  3772. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3773. ** statement that does not return data (for example an [UPDATE]).
  3774. **
  3775. ** See also: [sqlite3_data_count()]
  3776. */
  3777. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
  3778. /*
  3779. ** CAPI3REF: Column Names In A Result Set
  3780. ** METHOD: sqlite3_stmt
  3781. **
  3782. ** ^These routines return the name assigned to a particular column
  3783. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3784. ** interface returns a pointer to a zero-terminated UTF-8 string
  3785. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3786. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3787. ** that implements the [SELECT] statement. ^The second parameter is the
  3788. ** column number. ^The leftmost column is number 0.
  3789. **
  3790. ** ^The returned string pointer is valid until either the [prepared statement]
  3791. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3792. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3793. ** or until the next call to
  3794. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3795. **
  3796. ** ^If sqlite3_malloc() fails during the processing of either routine
  3797. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3798. ** NULL pointer is returned.
  3799. **
  3800. ** ^The name of a result column is the value of the "AS" clause for
  3801. ** that column, if there is an AS clause. If there is no AS clause
  3802. ** then the name of the column is unspecified and may change from
  3803. ** one release of SQLite to the next.
  3804. */
  3805. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
  3806. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
  3807. /*
  3808. ** CAPI3REF: Source Of Data In A Query Result
  3809. ** METHOD: sqlite3_stmt
  3810. **
  3811. ** ^These routines provide a means to determine the database, table, and
  3812. ** table column that is the origin of a particular result column in
  3813. ** [SELECT] statement.
  3814. ** ^The name of the database or table or column can be returned as
  3815. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3816. ** the database name, the _table_ routines return the table name, and
  3817. ** the origin_ routines return the column name.
  3818. ** ^The returned string is valid until the [prepared statement] is destroyed
  3819. ** using [sqlite3_finalize()] or until the statement is automatically
  3820. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3821. ** or until the same information is requested
  3822. ** again in a different encoding.
  3823. **
  3824. ** ^The names returned are the original un-aliased names of the
  3825. ** database, table, and column.
  3826. **
  3827. ** ^The first argument to these interfaces is a [prepared statement].
  3828. ** ^These functions return information about the Nth result column returned by
  3829. ** the statement, where N is the second function argument.
  3830. ** ^The left-most column is column 0 for these routines.
  3831. **
  3832. ** ^If the Nth column returned by the statement is an expression or
  3833. ** subquery and is not a column value, then all of these functions return
  3834. ** NULL. ^These routine might also return NULL if a memory allocation error
  3835. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3836. ** or column that query result column was extracted from.
  3837. **
  3838. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3839. ** UTF-16 encoded strings and the other functions return UTF-8.
  3840. **
  3841. ** ^These APIs are only available if the library was compiled with the
  3842. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3843. **
  3844. ** If two or more threads call one or more of these routines against the same
  3845. ** prepared statement and column at the same time then the results are
  3846. ** undefined.
  3847. **
  3848. ** If two or more threads call one or more
  3849. ** [sqlite3_column_database_name | column metadata interfaces]
  3850. ** for the same [prepared statement] and result column
  3851. ** at the same time then the results are undefined.
  3852. */
  3853. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
  3854. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
  3855. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
  3856. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
  3857. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
  3858. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3859. /*
  3860. ** CAPI3REF: Declared Datatype Of A Query Result
  3861. ** METHOD: sqlite3_stmt
  3862. **
  3863. ** ^(The first parameter is a [prepared statement].
  3864. ** If this statement is a [SELECT] statement and the Nth column of the
  3865. ** returned result set of that [SELECT] is a table column (not an
  3866. ** expression or subquery) then the declared type of the table
  3867. ** column is returned.)^ ^If the Nth column of the result set is an
  3868. ** expression or subquery, then a NULL pointer is returned.
  3869. ** ^The returned string is always UTF-8 encoded.
  3870. **
  3871. ** ^(For example, given the database schema:
  3872. **
  3873. ** CREATE TABLE t1(c1 VARIANT);
  3874. **
  3875. ** and the following statement to be compiled:
  3876. **
  3877. ** SELECT c1 + 1, c1 FROM t1;
  3878. **
  3879. ** this routine would return the string "VARIANT" for the second result
  3880. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3881. **
  3882. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3883. ** is declared to contain a particular type does not mean that the
  3884. ** data stored in that column is of the declared type. SQLite is
  3885. ** strongly typed, but the typing is dynamic not static. ^Type
  3886. ** is associated with individual values, not with the containers
  3887. ** used to hold those values.
  3888. */
  3889. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
  3890. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
  3891. /*
  3892. ** CAPI3REF: Evaluate An SQL Statement
  3893. ** METHOD: sqlite3_stmt
  3894. **
  3895. ** After a [prepared statement] has been prepared using either
  3896. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3897. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3898. ** must be called one or more times to evaluate the statement.
  3899. **
  3900. ** The details of the behavior of the sqlite3_step() interface depend
  3901. ** on whether the statement was prepared using the newer "v2" interface
  3902. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3903. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3904. ** new "v2" interface is recommended for new applications but the legacy
  3905. ** interface will continue to be supported.
  3906. **
  3907. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3908. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3909. ** ^With the "v2" interface, any of the other [result codes] or
  3910. ** [extended result codes] might be returned as well.
  3911. **
  3912. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3913. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3914. ** or occurs outside of an explicit transaction, then you can retry the
  3915. ** statement. If the statement is not a [COMMIT] and occurs within an
  3916. ** explicit transaction then you should rollback the transaction before
  3917. ** continuing.
  3918. **
  3919. ** ^[SQLITE_DONE] means that the statement has finished executing
  3920. ** successfully. sqlite3_step() should not be called again on this virtual
  3921. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3922. ** machine back to its initial state.
  3923. **
  3924. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3925. ** is returned each time a new row of data is ready for processing by the
  3926. ** caller. The values may be accessed using the [column access functions].
  3927. ** sqlite3_step() is called again to retrieve the next row of data.
  3928. **
  3929. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3930. ** violation) has occurred. sqlite3_step() should not be called again on
  3931. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3932. ** ^With the legacy interface, a more specific error code (for example,
  3933. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3934. ** can be obtained by calling [sqlite3_reset()] on the
  3935. ** [prepared statement]. ^In the "v2" interface,
  3936. ** the more specific error code is returned directly by sqlite3_step().
  3937. **
  3938. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3939. ** Perhaps it was called on a [prepared statement] that has
  3940. ** already been [sqlite3_finalize | finalized] or on one that had
  3941. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3942. ** be the case that the same database connection is being used by two or
  3943. ** more threads at the same moment in time.
  3944. **
  3945. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3946. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3947. ** other than [SQLITE_ROW] before any subsequent invocation of
  3948. ** sqlite3_step(). Failure to reset the prepared statement using
  3949. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3950. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3951. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3952. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3953. ** break because any application that ever receives an SQLITE_MISUSE error
  3954. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3955. ** can be used to restore the legacy behavior.
  3956. **
  3957. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3958. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3959. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3960. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3961. ** specific [error codes] that better describes the error.
  3962. ** We admit that this is a goofy design. The problem has been fixed
  3963. ** with the "v2" interface. If you prepare all of your SQL statements
  3964. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3965. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3966. ** then the more specific [error codes] are returned directly
  3967. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3968. */
  3969. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
  3970. /*
  3971. ** CAPI3REF: Number of columns in a result set
  3972. ** METHOD: sqlite3_stmt
  3973. **
  3974. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3975. ** current row of the result set of [prepared statement] P.
  3976. ** ^If prepared statement P does not have results ready to return
  3977. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3978. ** interfaces) then sqlite3_data_count(P) returns 0.
  3979. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3980. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3981. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3982. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3983. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3984. ** where it always returns zero since each step of that multi-step
  3985. ** pragma returns 0 columns of data.
  3986. **
  3987. ** See also: [sqlite3_column_count()]
  3988. */
  3989. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
  3990. /*
  3991. ** CAPI3REF: Fundamental Datatypes
  3992. ** KEYWORDS: SQLITE_TEXT
  3993. **
  3994. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3995. **
  3996. ** <ul>
  3997. ** <li> 64-bit signed integer
  3998. ** <li> 64-bit IEEE floating point number
  3999. ** <li> string
  4000. ** <li> BLOB
  4001. ** <li> NULL
  4002. ** </ul>)^
  4003. **
  4004. ** These constants are codes for each of those types.
  4005. **
  4006. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  4007. ** for a completely different meaning. Software that links against both
  4008. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  4009. ** SQLITE_TEXT.
  4010. */
  4011. #define SQLITE_INTEGER 1
  4012. #define SQLITE_FLOAT 2
  4013. #define SQLITE_BLOB 4
  4014. #define SQLITE_NULL 5
  4015. #ifdef SQLITE_TEXT
  4016. # undef SQLITE_TEXT
  4017. #else
  4018. # define SQLITE_TEXT 3
  4019. #endif
  4020. #define SQLITE3_TEXT 3
  4021. /*
  4022. ** CAPI3REF: Result Values From A Query
  4023. ** KEYWORDS: {column access functions}
  4024. ** METHOD: sqlite3_stmt
  4025. **
  4026. ** ^These routines return information about a single column of the current
  4027. ** result row of a query. ^In every case the first argument is a pointer
  4028. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  4029. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  4030. ** and the second argument is the index of the column for which information
  4031. ** should be returned. ^The leftmost column of the result set has the index 0.
  4032. ** ^The number of columns in the result can be determined using
  4033. ** [sqlite3_column_count()].
  4034. **
  4035. ** If the SQL statement does not currently point to a valid row, or if the
  4036. ** column index is out of range, the result is undefined.
  4037. ** These routines may only be called when the most recent call to
  4038. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  4039. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  4040. ** If any of these routines are called after [sqlite3_reset()] or
  4041. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  4042. ** something other than [SQLITE_ROW], the results are undefined.
  4043. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  4044. ** are called from a different thread while any of these routines
  4045. ** are pending, then the results are undefined.
  4046. **
  4047. ** ^The sqlite3_column_type() routine returns the
  4048. ** [SQLITE_INTEGER | datatype code] for the initial data type
  4049. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  4050. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  4051. ** returned by sqlite3_column_type() is only meaningful if no type
  4052. ** conversions have occurred as described below. After a type conversion,
  4053. ** the value returned by sqlite3_column_type() is undefined. Future
  4054. ** versions of SQLite may change the behavior of sqlite3_column_type()
  4055. ** following a type conversion.
  4056. **
  4057. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  4058. ** routine returns the number of bytes in that BLOB or string.
  4059. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  4060. ** the string to UTF-8 and then returns the number of bytes.
  4061. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  4062. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  4063. ** the number of bytes in that string.
  4064. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  4065. **
  4066. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  4067. ** routine returns the number of bytes in that BLOB or string.
  4068. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  4069. ** the string to UTF-16 and then returns the number of bytes.
  4070. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  4071. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  4072. ** the number of bytes in that string.
  4073. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  4074. **
  4075. ** ^The values returned by [sqlite3_column_bytes()] and
  4076. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  4077. ** of the string. ^For clarity: the values returned by
  4078. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  4079. ** bytes in the string, not the number of characters.
  4080. **
  4081. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  4082. ** even empty strings, are always zero-terminated. ^The return
  4083. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  4084. **
  4085. ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
  4086. ** [unprotected sqlite3_value] object. In a multithreaded environment,
  4087. ** an unprotected sqlite3_value object may only be used safely with
  4088. ** [sqlite3_bind_value()] and [sqlite3_result_value()].
  4089. ** If the [unprotected sqlite3_value] object returned by
  4090. ** [sqlite3_column_value()] is used in any other way, including calls
  4091. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  4092. ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
  4093. **
  4094. ** These routines attempt to convert the value where appropriate. ^For
  4095. ** example, if the internal representation is FLOAT and a text result
  4096. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  4097. ** conversion automatically. ^(The following table details the conversions
  4098. ** that are applied:
  4099. **
  4100. ** <blockquote>
  4101. ** <table border="1">
  4102. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  4103. **
  4104. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  4105. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  4106. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  4107. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  4108. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  4109. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  4110. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  4111. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  4112. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  4113. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  4114. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  4115. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  4116. ** <tr><td> TEXT <td> BLOB <td> No change
  4117. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  4118. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  4119. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  4120. ** </table>
  4121. ** </blockquote>)^
  4122. **
  4123. ** Note that when type conversions occur, pointers returned by prior
  4124. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  4125. ** sqlite3_column_text16() may be invalidated.
  4126. ** Type conversions and pointer invalidations might occur
  4127. ** in the following cases:
  4128. **
  4129. ** <ul>
  4130. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  4131. ** sqlite3_column_text16() is called. A zero-terminator might
  4132. ** need to be added to the string.</li>
  4133. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  4134. ** sqlite3_column_text16() is called. The content must be converted
  4135. ** to UTF-16.</li>
  4136. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  4137. ** sqlite3_column_text() is called. The content must be converted
  4138. ** to UTF-8.</li>
  4139. ** </ul>
  4140. **
  4141. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  4142. ** not invalidate a prior pointer, though of course the content of the buffer
  4143. ** that the prior pointer references will have been modified. Other kinds
  4144. ** of conversion are done in place when it is possible, but sometimes they
  4145. ** are not possible and in those cases prior pointers are invalidated.
  4146. **
  4147. ** The safest policy is to invoke these routines
  4148. ** in one of the following ways:
  4149. **
  4150. ** <ul>
  4151. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  4152. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  4153. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  4154. ** </ul>
  4155. **
  4156. ** In other words, you should call sqlite3_column_text(),
  4157. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  4158. ** into the desired format, then invoke sqlite3_column_bytes() or
  4159. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  4160. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  4161. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  4162. ** with calls to sqlite3_column_bytes().
  4163. **
  4164. ** ^The pointers returned are valid until a type conversion occurs as
  4165. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  4166. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  4167. ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
  4168. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  4169. ** [sqlite3_free()].
  4170. **
  4171. ** ^(If a memory allocation error occurs during the evaluation of any
  4172. ** of these routines, a default value is returned. The default value
  4173. ** is either the integer 0, the floating point number 0.0, or a NULL
  4174. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  4175. ** [SQLITE_NOMEM].)^
  4176. */
  4177. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
  4178. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  4179. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  4180. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
  4181. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
  4182. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
  4183. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
  4184. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
  4185. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
  4186. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
  4187. /*
  4188. ** CAPI3REF: Destroy A Prepared Statement Object
  4189. ** DESTRUCTOR: sqlite3_stmt
  4190. **
  4191. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4192. ** ^If the most recent evaluation of the statement encountered no errors
  4193. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4194. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4195. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4196. ** [extended error code].
  4197. **
  4198. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4199. ** the life cycle of [prepared statement] S:
  4200. ** before statement S is ever evaluated, after
  4201. ** one or more calls to [sqlite3_reset()], or after any call
  4202. ** to [sqlite3_step()] regardless of whether or not the statement has
  4203. ** completed execution.
  4204. **
  4205. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4206. **
  4207. ** The application must finalize every [prepared statement] in order to avoid
  4208. ** resource leaks. It is a grievous error for the application to try to use
  4209. ** a prepared statement after it has been finalized. Any use of a prepared
  4210. ** statement after it has been finalized can result in undefined and
  4211. ** undesirable behavior such as segfaults and heap corruption.
  4212. */
  4213. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
  4214. /*
  4215. ** CAPI3REF: Reset A Prepared Statement Object
  4216. ** METHOD: sqlite3_stmt
  4217. **
  4218. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4219. ** object back to its initial state, ready to be re-executed.
  4220. ** ^Any SQL statement variables that had values bound to them using
  4221. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4222. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4223. **
  4224. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4225. ** back to the beginning of its program.
  4226. **
  4227. ** ^If the most recent call to [sqlite3_step(S)] for the
  4228. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4229. ** or if [sqlite3_step(S)] has never before been called on S,
  4230. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4231. **
  4232. ** ^If the most recent call to [sqlite3_step(S)] for the
  4233. ** [prepared statement] S indicated an error, then
  4234. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4235. **
  4236. ** ^The [sqlite3_reset(S)] interface does not change the values
  4237. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4238. */
  4239. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
  4240. /*
  4241. ** CAPI3REF: Create Or Redefine SQL Functions
  4242. ** KEYWORDS: {function creation routines}
  4243. ** KEYWORDS: {application-defined SQL function}
  4244. ** KEYWORDS: {application-defined SQL functions}
  4245. ** METHOD: sqlite3
  4246. **
  4247. ** ^These functions (collectively known as "function creation routines")
  4248. ** are used to add SQL functions or aggregates or to redefine the behavior
  4249. ** of existing SQL functions or aggregates. The only differences between
  4250. ** these routines are the text encoding expected for
  4251. ** the second parameter (the name of the function being created)
  4252. ** and the presence or absence of a destructor callback for
  4253. ** the application data pointer.
  4254. **
  4255. ** ^The first parameter is the [database connection] to which the SQL
  4256. ** function is to be added. ^If an application uses more than one database
  4257. ** connection then application-defined SQL functions must be added
  4258. ** to each database connection separately.
  4259. **
  4260. ** ^The second parameter is the name of the SQL function to be created or
  4261. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4262. ** representation, exclusive of the zero-terminator. ^Note that the name
  4263. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4264. ** ^Any attempt to create a function with a longer name
  4265. ** will result in [SQLITE_MISUSE] being returned.
  4266. **
  4267. ** ^The third parameter (nArg)
  4268. ** is the number of arguments that the SQL function or
  4269. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4270. ** aggregate may take any number of arguments between 0 and the limit
  4271. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4272. ** parameter is less than -1 or greater than 127 then the behavior is
  4273. ** undefined.
  4274. **
  4275. ** ^The fourth parameter, eTextRep, specifies what
  4276. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4277. ** its parameters. The application should set this parameter to
  4278. ** [SQLITE_UTF16LE] if the function implementation invokes
  4279. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4280. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4281. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4282. ** otherwise. ^The same SQL function may be registered multiple times using
  4283. ** different preferred text encodings, with different implementations for
  4284. ** each encoding.
  4285. ** ^When multiple implementations of the same function are available, SQLite
  4286. ** will pick the one that involves the least amount of data conversion.
  4287. **
  4288. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4289. ** to signal that the function will always return the same result given
  4290. ** the same inputs within a single SQL statement. Most SQL functions are
  4291. ** deterministic. The built-in [random()] SQL function is an example of a
  4292. ** function that is not deterministic. The SQLite query planner is able to
  4293. ** perform additional optimizations on deterministic functions, so use
  4294. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4295. **
  4296. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4297. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4298. **
  4299. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4300. ** pointers to C-language functions that implement the SQL function or
  4301. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4302. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4303. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4304. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4305. ** SQL function or aggregate, pass NULL pointers for all three function
  4306. ** callbacks.
  4307. **
  4308. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4309. ** then it is destructor for the application data pointer.
  4310. ** The destructor is invoked when the function is deleted, either by being
  4311. ** overloaded or when the database connection closes.)^
  4312. ** ^The destructor is also invoked if the call to
  4313. ** sqlite3_create_function_v2() fails.
  4314. ** ^When the destructor callback of the tenth parameter is invoked, it
  4315. ** is passed a single argument which is a copy of the application data
  4316. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4317. **
  4318. ** ^It is permitted to register multiple implementations of the same
  4319. ** functions with the same name but with either differing numbers of
  4320. ** arguments or differing preferred text encodings. ^SQLite will use
  4321. ** the implementation that most closely matches the way in which the
  4322. ** SQL function is used. ^A function implementation with a non-negative
  4323. ** nArg parameter is a better match than a function implementation with
  4324. ** a negative nArg. ^A function where the preferred text encoding
  4325. ** matches the database encoding is a better
  4326. ** match than a function where the encoding is different.
  4327. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4328. ** is a closer match than a function where the encoding difference is
  4329. ** between UTF8 and UTF16.
  4330. **
  4331. ** ^Built-in functions may be overloaded by new application-defined functions.
  4332. **
  4333. ** ^An application-defined function is permitted to call other
  4334. ** SQLite interfaces. However, such calls must not
  4335. ** close the database connection nor finalize or reset the prepared
  4336. ** statement in which the function is running.
  4337. */
  4338. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  4339. sqlite3 *db,
  4340. const char *zFunctionName,
  4341. int nArg,
  4342. int eTextRep,
  4343. void *pApp,
  4344. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4345. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4346. void (*xFinal)(sqlite3_context*)
  4347. );
  4348. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  4349. sqlite3 *db,
  4350. const void *zFunctionName,
  4351. int nArg,
  4352. int eTextRep,
  4353. void *pApp,
  4354. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4355. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4356. void (*xFinal)(sqlite3_context*)
  4357. );
  4358. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  4359. sqlite3 *db,
  4360. const char *zFunctionName,
  4361. int nArg,
  4362. int eTextRep,
  4363. void *pApp,
  4364. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4365. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4366. void (*xFinal)(sqlite3_context*),
  4367. void(*xDestroy)(void*)
  4368. );
  4369. /*
  4370. ** CAPI3REF: Text Encodings
  4371. **
  4372. ** These constant define integer codes that represent the various
  4373. ** text encodings supported by SQLite.
  4374. */
  4375. #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
  4376. #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
  4377. #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
  4378. #define SQLITE_UTF16 4 /* Use native byte order */
  4379. #define SQLITE_ANY 5 /* Deprecated */
  4380. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4381. /*
  4382. ** CAPI3REF: Function Flags
  4383. **
  4384. ** These constants may be ORed together with the
  4385. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4386. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4387. ** [sqlite3_create_function_v2()].
  4388. */
  4389. #define SQLITE_DETERMINISTIC 0x800
  4390. /*
  4391. ** CAPI3REF: Deprecated Functions
  4392. ** DEPRECATED
  4393. **
  4394. ** These functions are [deprecated]. In order to maintain
  4395. ** backwards compatibility with older code, these functions continue
  4396. ** to be supported. However, new applications should avoid
  4397. ** the use of these functions. To encourage programmers to avoid
  4398. ** these functions, we will not explain what they do.
  4399. */
  4400. #ifndef SQLITE_OMIT_DEPRECATED
  4401. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
  4402. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
  4403. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4404. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
  4405. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
  4406. SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4407. void*,sqlite3_int64);
  4408. #endif
  4409. /*
  4410. ** CAPI3REF: Obtaining SQL Values
  4411. ** METHOD: sqlite3_value
  4412. **
  4413. ** The C-language implementation of SQL functions and aggregates uses
  4414. ** this set of interface routines to access the parameter values on
  4415. ** the function or aggregate.
  4416. **
  4417. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4418. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4419. ** define callbacks that implement the SQL functions and aggregates.
  4420. ** The 3rd parameter to these callbacks is an array of pointers to
  4421. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4422. ** each parameter to the SQL function. These routines are used to
  4423. ** extract values from the [sqlite3_value] objects.
  4424. **
  4425. ** These routines work only with [protected sqlite3_value] objects.
  4426. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4427. ** object results in undefined behavior.
  4428. **
  4429. ** ^These routines work just like the corresponding [column access functions]
  4430. ** except that these routines take a single [protected sqlite3_value] object
  4431. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4432. **
  4433. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4434. ** in the native byte-order of the host machine. ^The
  4435. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4436. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4437. **
  4438. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4439. ** numeric affinity to the value. This means that an attempt is
  4440. ** made to convert the value to an integer or floating point. If
  4441. ** such a conversion is possible without loss of information (in other
  4442. ** words, if the value is a string that looks like a number)
  4443. ** then the conversion is performed. Otherwise no conversion occurs.
  4444. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4445. **
  4446. ** Please pay particular attention to the fact that the pointer returned
  4447. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4448. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4449. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4450. ** or [sqlite3_value_text16()].
  4451. **
  4452. ** These routines must be called from the same thread as
  4453. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4454. */
  4455. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
  4456. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
  4457. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
  4458. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
  4459. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
  4460. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
  4461. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
  4462. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
  4463. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
  4464. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
  4465. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
  4466. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
  4467. /*
  4468. ** CAPI3REF: Copy And Free SQL Values
  4469. ** METHOD: sqlite3_value
  4470. **
  4471. ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
  4472. ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
  4473. ** is a [protected sqlite3_value] object even if the input is not.
  4474. ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
  4475. ** memory allocation fails.
  4476. **
  4477. ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
  4478. ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
  4479. ** then sqlite3_value_free(V) is a harmless no-op.
  4480. */
  4481. SQLITE_API SQLITE_EXPERIMENTAL sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value*);
  4482. SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_value_free(sqlite3_value*);
  4483. /*
  4484. ** CAPI3REF: Obtain Aggregate Function Context
  4485. ** METHOD: sqlite3_context
  4486. **
  4487. ** Implementations of aggregate SQL functions use this
  4488. ** routine to allocate memory for storing their state.
  4489. **
  4490. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4491. ** for a particular aggregate function, SQLite
  4492. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4493. ** to the new memory. ^On second and subsequent calls to
  4494. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4495. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4496. ** called once for each invocation of the xStep callback and then one
  4497. ** last time when the xFinal callback is invoked. ^(When no rows match
  4498. ** an aggregate query, the xStep() callback of the aggregate function
  4499. ** implementation is never called and xFinal() is called exactly once.
  4500. ** In those cases, sqlite3_aggregate_context() might be called for the
  4501. ** first time from within xFinal().)^
  4502. **
  4503. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4504. ** when first called if N is less than or equal to zero or if a memory
  4505. ** allocate error occurs.
  4506. **
  4507. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4508. ** determined by the N parameter on first successful call. Changing the
  4509. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4510. ** the same aggregate function instance will not resize the memory
  4511. ** allocation.)^ Within the xFinal callback, it is customary to set
  4512. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4513. ** pointless memory allocations occur.
  4514. **
  4515. ** ^SQLite automatically frees the memory allocated by
  4516. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4517. **
  4518. ** The first parameter must be a copy of the
  4519. ** [sqlite3_context | SQL function context] that is the first parameter
  4520. ** to the xStep or xFinal callback routine that implements the aggregate
  4521. ** function.
  4522. **
  4523. ** This routine must be called from the same thread in which
  4524. ** the aggregate SQL function is running.
  4525. */
  4526. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4527. /*
  4528. ** CAPI3REF: User Data For Functions
  4529. ** METHOD: sqlite3_context
  4530. **
  4531. ** ^The sqlite3_user_data() interface returns a copy of
  4532. ** the pointer that was the pUserData parameter (the 5th parameter)
  4533. ** of the [sqlite3_create_function()]
  4534. ** and [sqlite3_create_function16()] routines that originally
  4535. ** registered the application defined function.
  4536. **
  4537. ** This routine must be called from the same thread in which
  4538. ** the application-defined function is running.
  4539. */
  4540. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
  4541. /*
  4542. ** CAPI3REF: Database Connection For Functions
  4543. ** METHOD: sqlite3_context
  4544. **
  4545. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4546. ** the pointer to the [database connection] (the 1st parameter)
  4547. ** of the [sqlite3_create_function()]
  4548. ** and [sqlite3_create_function16()] routines that originally
  4549. ** registered the application defined function.
  4550. */
  4551. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
  4552. /*
  4553. ** CAPI3REF: Function Auxiliary Data
  4554. ** METHOD: sqlite3_context
  4555. **
  4556. ** These functions may be used by (non-aggregate) SQL functions to
  4557. ** associate metadata with argument values. If the same value is passed to
  4558. ** multiple invocations of the same SQL function during query execution, under
  4559. ** some circumstances the associated metadata may be preserved. An example
  4560. ** of where this might be useful is in a regular-expression matching
  4561. ** function. The compiled version of the regular expression can be stored as
  4562. ** metadata associated with the pattern string.
  4563. ** Then as long as the pattern string remains the same,
  4564. ** the compiled regular expression can be reused on multiple
  4565. ** invocations of the same function.
  4566. **
  4567. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4568. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4569. ** value to the application-defined function. ^If there is no metadata
  4570. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4571. ** returns a NULL pointer.
  4572. **
  4573. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4574. ** argument of the application-defined function. ^Subsequent
  4575. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4576. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4577. ** NULL if the metadata has been discarded.
  4578. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4579. ** SQLite will invoke the destructor function X with parameter P exactly
  4580. ** once, when the metadata is discarded.
  4581. ** SQLite is free to discard the metadata at any time, including: <ul>
  4582. ** <li> when the corresponding function parameter changes, or
  4583. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4584. ** SQL statement, or
  4585. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4586. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4587. ** allocation error occurs. </ul>)^
  4588. **
  4589. ** Note the last bullet in particular. The destructor X in
  4590. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4591. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4592. ** should be called near the end of the function implementation and the
  4593. ** function implementation should not make any use of P after
  4594. ** sqlite3_set_auxdata() has been called.
  4595. **
  4596. ** ^(In practice, metadata is preserved between function calls for
  4597. ** function parameters that are compile-time constants, including literal
  4598. ** values and [parameters] and expressions composed from the same.)^
  4599. **
  4600. ** These routines must be called from the same thread in which
  4601. ** the SQL function is running.
  4602. */
  4603. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
  4604. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4605. /*
  4606. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4607. **
  4608. ** These are special values for the destructor that is passed in as the
  4609. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4610. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4611. ** and will never change. It does not need to be destroyed. ^The
  4612. ** SQLITE_TRANSIENT value means that the content will likely change in
  4613. ** the near future and that SQLite should make its own private copy of
  4614. ** the content before returning.
  4615. **
  4616. ** The typedef is necessary to work around problems in certain
  4617. ** C++ compilers.
  4618. */
  4619. typedef void (*sqlite3_destructor_type)(void*);
  4620. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4621. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4622. /*
  4623. ** CAPI3REF: Setting The Result Of An SQL Function
  4624. ** METHOD: sqlite3_context
  4625. **
  4626. ** These routines are used by the xFunc or xFinal callbacks that
  4627. ** implement SQL functions and aggregates. See
  4628. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4629. ** for additional information.
  4630. **
  4631. ** These functions work very much like the [parameter binding] family of
  4632. ** functions used to bind values to host parameters in prepared statements.
  4633. ** Refer to the [SQL parameter] documentation for additional information.
  4634. **
  4635. ** ^The sqlite3_result_blob() interface sets the result from
  4636. ** an application-defined function to be the BLOB whose content is pointed
  4637. ** to by the second parameter and which is N bytes long where N is the
  4638. ** third parameter.
  4639. **
  4640. ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
  4641. ** interfaces set the result of the application-defined function to be
  4642. ** a BLOB containing all zero bytes and N bytes in size.
  4643. **
  4644. ** ^The sqlite3_result_double() interface sets the result from
  4645. ** an application-defined function to be a floating point value specified
  4646. ** by its 2nd argument.
  4647. **
  4648. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4649. ** cause the implemented SQL function to throw an exception.
  4650. ** ^SQLite uses the string pointed to by the
  4651. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4652. ** as the text of an error message. ^SQLite interprets the error
  4653. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4654. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4655. ** byte order. ^If the third parameter to sqlite3_result_error()
  4656. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4657. ** message all text up through the first zero character.
  4658. ** ^If the third parameter to sqlite3_result_error() or
  4659. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4660. ** bytes (not characters) from the 2nd parameter as the error message.
  4661. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4662. ** routines make a private copy of the error message text before
  4663. ** they return. Hence, the calling function can deallocate or
  4664. ** modify the text after they return without harm.
  4665. ** ^The sqlite3_result_error_code() function changes the error code
  4666. ** returned by SQLite as a result of an error in a function. ^By default,
  4667. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4668. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4669. **
  4670. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4671. ** error indicating that a string or BLOB is too long to represent.
  4672. **
  4673. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4674. ** error indicating that a memory allocation failed.
  4675. **
  4676. ** ^The sqlite3_result_int() interface sets the return value
  4677. ** of the application-defined function to be the 32-bit signed integer
  4678. ** value given in the 2nd argument.
  4679. ** ^The sqlite3_result_int64() interface sets the return value
  4680. ** of the application-defined function to be the 64-bit signed integer
  4681. ** value given in the 2nd argument.
  4682. **
  4683. ** ^The sqlite3_result_null() interface sets the return value
  4684. ** of the application-defined function to be NULL.
  4685. **
  4686. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4687. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4688. ** set the return value of the application-defined function to be
  4689. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4690. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4691. ** ^The sqlite3_result_text64() interface sets the return value of an
  4692. ** application-defined function to be a text string in an encoding
  4693. ** specified by the fifth (and last) parameter, which must be one
  4694. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  4695. ** ^SQLite takes the text result from the application from
  4696. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4697. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4698. ** is negative, then SQLite takes result text from the 2nd parameter
  4699. ** through the first zero character.
  4700. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4701. ** is non-negative, then as many bytes (not characters) of the text
  4702. ** pointed to by the 2nd parameter are taken as the application-defined
  4703. ** function result. If the 3rd parameter is non-negative, then it
  4704. ** must be the byte offset into the string where the NUL terminator would
  4705. ** appear if the string where NUL terminated. If any NUL characters occur
  4706. ** in the string at a byte offset that is less than the value of the 3rd
  4707. ** parameter, then the resulting string will contain embedded NULs and the
  4708. ** result of expressions operating on strings with embedded NULs is undefined.
  4709. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4710. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4711. ** function as the destructor on the text or BLOB result when it has
  4712. ** finished using that result.
  4713. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4714. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4715. ** assumes that the text or BLOB result is in constant space and does not
  4716. ** copy the content of the parameter nor call a destructor on the content
  4717. ** when it has finished using that result.
  4718. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4719. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4720. ** then SQLite makes a copy of the result into space obtained from
  4721. ** from [sqlite3_malloc()] before it returns.
  4722. **
  4723. ** ^The sqlite3_result_value() interface sets the result of
  4724. ** the application-defined function to be a copy of the
  4725. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4726. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4727. ** so that the [sqlite3_value] specified in the parameter may change or
  4728. ** be deallocated after sqlite3_result_value() returns without harm.
  4729. ** ^A [protected sqlite3_value] object may always be used where an
  4730. ** [unprotected sqlite3_value] object is required, so either
  4731. ** kind of [sqlite3_value] object can be used with this interface.
  4732. **
  4733. ** If these routines are called from within the different thread
  4734. ** than the one containing the application-defined function that received
  4735. ** the [sqlite3_context] pointer, the results are undefined.
  4736. */
  4737. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4738. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
  4739. sqlite3_uint64,void(*)(void*));
  4740. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
  4741. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
  4742. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
  4743. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
  4744. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
  4745. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
  4746. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
  4747. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4748. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
  4749. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4750. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  4751. void(*)(void*), unsigned char encoding);
  4752. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4753. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4754. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4755. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4756. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
  4757. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context*, sqlite3_uint64 n);
  4758. /*
  4759. ** CAPI3REF: Define New Collating Sequences
  4760. ** METHOD: sqlite3
  4761. **
  4762. ** ^These functions add, remove, or modify a [collation] associated
  4763. ** with the [database connection] specified as the first argument.
  4764. **
  4765. ** ^The name of the collation is a UTF-8 string
  4766. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4767. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4768. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4769. ** considered to be the same name.
  4770. **
  4771. ** ^(The third argument (eTextRep) must be one of the constants:
  4772. ** <ul>
  4773. ** <li> [SQLITE_UTF8],
  4774. ** <li> [SQLITE_UTF16LE],
  4775. ** <li> [SQLITE_UTF16BE],
  4776. ** <li> [SQLITE_UTF16], or
  4777. ** <li> [SQLITE_UTF16_ALIGNED].
  4778. ** </ul>)^
  4779. ** ^The eTextRep argument determines the encoding of strings passed
  4780. ** to the collating function callback, xCallback.
  4781. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4782. ** force strings to be UTF16 with native byte order.
  4783. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4784. ** on an even byte address.
  4785. **
  4786. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4787. ** through as the first argument to the collating function callback.
  4788. **
  4789. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4790. ** ^Multiple collating functions can be registered using the same name but
  4791. ** with different eTextRep parameters and SQLite will use whichever
  4792. ** function requires the least amount of data transformation.
  4793. ** ^If the xCallback argument is NULL then the collating function is
  4794. ** deleted. ^When all collating functions having the same name are deleted,
  4795. ** that collation is no longer usable.
  4796. **
  4797. ** ^The collating function callback is invoked with a copy of the pArg
  4798. ** application data pointer and with two strings in the encoding specified
  4799. ** by the eTextRep argument. The collating function must return an
  4800. ** integer that is negative, zero, or positive
  4801. ** if the first string is less than, equal to, or greater than the second,
  4802. ** respectively. A collating function must always return the same answer
  4803. ** given the same inputs. If two or more collating functions are registered
  4804. ** to the same collation name (using different eTextRep values) then all
  4805. ** must give an equivalent answer when invoked with equivalent strings.
  4806. ** The collating function must obey the following properties for all
  4807. ** strings A, B, and C:
  4808. **
  4809. ** <ol>
  4810. ** <li> If A==B then B==A.
  4811. ** <li> If A==B and B==C then A==C.
  4812. ** <li> If A&lt;B THEN B&gt;A.
  4813. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4814. ** </ol>
  4815. **
  4816. ** If a collating function fails any of the above constraints and that
  4817. ** collating function is registered and used, then the behavior of SQLite
  4818. ** is undefined.
  4819. **
  4820. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4821. ** with the addition that the xDestroy callback is invoked on pArg when
  4822. ** the collating function is deleted.
  4823. ** ^Collating functions are deleted when they are overridden by later
  4824. ** calls to the collation creation functions or when the
  4825. ** [database connection] is closed using [sqlite3_close()].
  4826. **
  4827. ** ^The xDestroy callback is <u>not</u> called if the
  4828. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4829. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4830. ** check the return code and dispose of the application data pointer
  4831. ** themselves rather than expecting SQLite to deal with it for them.
  4832. ** This is different from every other SQLite interface. The inconsistency
  4833. ** is unfortunate but cannot be changed without breaking backwards
  4834. ** compatibility.
  4835. **
  4836. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4837. */
  4838. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  4839. sqlite3*,
  4840. const char *zName,
  4841. int eTextRep,
  4842. void *pArg,
  4843. int(*xCompare)(void*,int,const void*,int,const void*)
  4844. );
  4845. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  4846. sqlite3*,
  4847. const char *zName,
  4848. int eTextRep,
  4849. void *pArg,
  4850. int(*xCompare)(void*,int,const void*,int,const void*),
  4851. void(*xDestroy)(void*)
  4852. );
  4853. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  4854. sqlite3*,
  4855. const void *zName,
  4856. int eTextRep,
  4857. void *pArg,
  4858. int(*xCompare)(void*,int,const void*,int,const void*)
  4859. );
  4860. /*
  4861. ** CAPI3REF: Collation Needed Callbacks
  4862. ** METHOD: sqlite3
  4863. **
  4864. ** ^To avoid having to register all collation sequences before a database
  4865. ** can be used, a single callback function may be registered with the
  4866. ** [database connection] to be invoked whenever an undefined collation
  4867. ** sequence is required.
  4868. **
  4869. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4870. ** then it is passed the names of undefined collation sequences as strings
  4871. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4872. ** the names are passed as UTF-16 in machine native byte order.
  4873. ** ^A call to either function replaces the existing collation-needed callback.
  4874. **
  4875. ** ^(When the callback is invoked, the first argument passed is a copy
  4876. ** of the second argument to sqlite3_collation_needed() or
  4877. ** sqlite3_collation_needed16(). The second argument is the database
  4878. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4879. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4880. ** sequence function required. The fourth parameter is the name of the
  4881. ** required collation sequence.)^
  4882. **
  4883. ** The callback function should register the desired collation using
  4884. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4885. ** [sqlite3_create_collation_v2()].
  4886. */
  4887. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  4888. sqlite3*,
  4889. void*,
  4890. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4891. );
  4892. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  4893. sqlite3*,
  4894. void*,
  4895. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4896. );
  4897. #ifdef SQLITE_HAS_CODEC
  4898. /*
  4899. ** Specify the key for an encrypted database. This routine should be
  4900. ** called right after sqlite3_open().
  4901. **
  4902. ** The code to implement this API is not available in the public release
  4903. ** of SQLite.
  4904. */
  4905. SQLITE_API int SQLITE_STDCALL sqlite3_key(
  4906. sqlite3 *db, /* Database to be rekeyed */
  4907. const void *pKey, int nKey /* The key */
  4908. );
  4909. SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
  4910. sqlite3 *db, /* Database to be rekeyed */
  4911. const char *zDbName, /* Name of the database */
  4912. const void *pKey, int nKey /* The key */
  4913. );
  4914. /*
  4915. ** Change the key on an open database. If the current database is not
  4916. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4917. ** database is decrypted.
  4918. **
  4919. ** The code to implement this API is not available in the public release
  4920. ** of SQLite.
  4921. */
  4922. SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
  4923. sqlite3 *db, /* Database to be rekeyed */
  4924. const void *pKey, int nKey /* The new key */
  4925. );
  4926. SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
  4927. sqlite3 *db, /* Database to be rekeyed */
  4928. const char *zDbName, /* Name of the database */
  4929. const void *pKey, int nKey /* The new key */
  4930. );
  4931. /*
  4932. ** Specify the activation key for a SEE database. Unless
  4933. ** activated, none of the SEE routines will work.
  4934. */
  4935. SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
  4936. const char *zPassPhrase /* Activation phrase */
  4937. );
  4938. #endif
  4939. #ifdef SQLITE_ENABLE_CEROD
  4940. /*
  4941. ** Specify the activation key for a CEROD database. Unless
  4942. ** activated, none of the CEROD routines will work.
  4943. */
  4944. SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
  4945. const char *zPassPhrase /* Activation phrase */
  4946. );
  4947. #endif
  4948. /*
  4949. ** CAPI3REF: Suspend Execution For A Short Time
  4950. **
  4951. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4952. ** for at least a number of milliseconds specified in its parameter.
  4953. **
  4954. ** If the operating system does not support sleep requests with
  4955. ** millisecond time resolution, then the time will be rounded up to
  4956. ** the nearest second. The number of milliseconds of sleep actually
  4957. ** requested from the operating system is returned.
  4958. **
  4959. ** ^SQLite implements this interface by calling the xSleep()
  4960. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4961. ** of the default VFS is not implemented correctly, or not implemented at
  4962. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4963. ** in the previous paragraphs.
  4964. */
  4965. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
  4966. /*
  4967. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4968. **
  4969. ** ^(If this global variable is made to point to a string which is
  4970. ** the name of a folder (a.k.a. directory), then all temporary files
  4971. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4972. ** will be placed in that directory.)^ ^If this variable
  4973. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4974. ** temporary file directory.
  4975. **
  4976. ** Applications are strongly discouraged from using this global variable.
  4977. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  4978. ** But for all other platforms, it is highly recommended that applications
  4979. ** neither read nor write this variable. This global variable is a relic
  4980. ** that exists for backwards compatibility of legacy applications and should
  4981. ** be avoided in new projects.
  4982. **
  4983. ** It is not safe to read or modify this variable in more than one
  4984. ** thread at a time. It is not safe to read or modify this variable
  4985. ** if a [database connection] is being used at the same time in a separate
  4986. ** thread.
  4987. ** It is intended that this variable be set once
  4988. ** as part of process initialization and before any SQLite interface
  4989. ** routines have been called and that this variable remain unchanged
  4990. ** thereafter.
  4991. **
  4992. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4993. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4994. ** the [temp_store_directory pragma] always assumes that any string
  4995. ** that this variable points to is held in memory obtained from
  4996. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4997. ** using [sqlite3_free].
  4998. ** Hence, if this variable is modified directly, either it should be
  4999. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5000. ** or else the use of the [temp_store_directory pragma] should be avoided.
  5001. ** Except when requested by the [temp_store_directory pragma], SQLite
  5002. ** does not free the memory that sqlite3_temp_directory points to. If
  5003. ** the application wants that memory to be freed, it must do
  5004. ** so itself, taking care to only do so after all [database connection]
  5005. ** objects have been destroyed.
  5006. **
  5007. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  5008. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  5009. ** features that require the use of temporary files may fail. Here is an
  5010. ** example of how to do this using C++ with the Windows Runtime:
  5011. **
  5012. ** <blockquote><pre>
  5013. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  5014. ** &nbsp; TemporaryFolder->Path->Data();
  5015. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  5016. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  5017. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  5018. ** &nbsp; NULL, NULL);
  5019. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  5020. ** </pre></blockquote>
  5021. */
  5022. SQLITE_API char *sqlite3_temp_directory;
  5023. /*
  5024. ** CAPI3REF: Name Of The Folder Holding Database Files
  5025. **
  5026. ** ^(If this global variable is made to point to a string which is
  5027. ** the name of a folder (a.k.a. directory), then all database files
  5028. ** specified with a relative pathname and created or accessed by
  5029. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  5030. ** to be relative to that directory.)^ ^If this variable is a NULL
  5031. ** pointer, then SQLite assumes that all database files specified
  5032. ** with a relative pathname are relative to the current directory
  5033. ** for the process. Only the windows VFS makes use of this global
  5034. ** variable; it is ignored by the unix VFS.
  5035. **
  5036. ** Changing the value of this variable while a database connection is
  5037. ** open can result in a corrupt database.
  5038. **
  5039. ** It is not safe to read or modify this variable in more than one
  5040. ** thread at a time. It is not safe to read or modify this variable
  5041. ** if a [database connection] is being used at the same time in a separate
  5042. ** thread.
  5043. ** It is intended that this variable be set once
  5044. ** as part of process initialization and before any SQLite interface
  5045. ** routines have been called and that this variable remain unchanged
  5046. ** thereafter.
  5047. **
  5048. ** ^The [data_store_directory pragma] may modify this variable and cause
  5049. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  5050. ** the [data_store_directory pragma] always assumes that any string
  5051. ** that this variable points to is held in memory obtained from
  5052. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  5053. ** using [sqlite3_free].
  5054. ** Hence, if this variable is modified directly, either it should be
  5055. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  5056. ** or else the use of the [data_store_directory pragma] should be avoided.
  5057. */
  5058. SQLITE_API char *sqlite3_data_directory;
  5059. /*
  5060. ** CAPI3REF: Test For Auto-Commit Mode
  5061. ** KEYWORDS: {autocommit mode}
  5062. ** METHOD: sqlite3
  5063. **
  5064. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  5065. ** zero if the given database connection is or is not in autocommit mode,
  5066. ** respectively. ^Autocommit mode is on by default.
  5067. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  5068. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  5069. **
  5070. ** If certain kinds of errors occur on a statement within a multi-statement
  5071. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  5072. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  5073. ** transaction might be rolled back automatically. The only way to
  5074. ** find out whether SQLite automatically rolled back the transaction after
  5075. ** an error is to use this function.
  5076. **
  5077. ** If another thread changes the autocommit status of the database
  5078. ** connection while this routine is running, then the return value
  5079. ** is undefined.
  5080. */
  5081. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
  5082. /*
  5083. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  5084. ** METHOD: sqlite3_stmt
  5085. **
  5086. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  5087. ** to which a [prepared statement] belongs. ^The [database connection]
  5088. ** returned by sqlite3_db_handle is the same [database connection]
  5089. ** that was the first argument
  5090. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  5091. ** create the statement in the first place.
  5092. */
  5093. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
  5094. /*
  5095. ** CAPI3REF: Return The Filename For A Database Connection
  5096. ** METHOD: sqlite3
  5097. **
  5098. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  5099. ** associated with database N of connection D. ^The main database file
  5100. ** has the name "main". If there is no attached database N on the database
  5101. ** connection D, or if database N is a temporary or in-memory database, then
  5102. ** a NULL pointer is returned.
  5103. **
  5104. ** ^The filename returned by this function is the output of the
  5105. ** xFullPathname method of the [VFS]. ^In other words, the filename
  5106. ** will be an absolute pathname, even if the filename used
  5107. ** to open the database originally was a URI or relative pathname.
  5108. */
  5109. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  5110. /*
  5111. ** CAPI3REF: Determine if a database is read-only
  5112. ** METHOD: sqlite3
  5113. **
  5114. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  5115. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  5116. ** the name of a database on connection D.
  5117. */
  5118. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  5119. /*
  5120. ** CAPI3REF: Find the next prepared statement
  5121. ** METHOD: sqlite3
  5122. **
  5123. ** ^This interface returns a pointer to the next [prepared statement] after
  5124. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  5125. ** then this interface returns a pointer to the first prepared statement
  5126. ** associated with the database connection pDb. ^If no prepared statement
  5127. ** satisfies the conditions of this routine, it returns NULL.
  5128. **
  5129. ** The [database connection] pointer D in a call to
  5130. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  5131. ** connection and in particular must not be a NULL pointer.
  5132. */
  5133. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  5134. /*
  5135. ** CAPI3REF: Commit And Rollback Notification Callbacks
  5136. ** METHOD: sqlite3
  5137. **
  5138. ** ^The sqlite3_commit_hook() interface registers a callback
  5139. ** function to be invoked whenever a transaction is [COMMIT | committed].
  5140. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  5141. ** for the same database connection is overridden.
  5142. ** ^The sqlite3_rollback_hook() interface registers a callback
  5143. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  5144. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  5145. ** for the same database connection is overridden.
  5146. ** ^The pArg argument is passed through to the callback.
  5147. ** ^If the callback on a commit hook function returns non-zero,
  5148. ** then the commit is converted into a rollback.
  5149. **
  5150. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  5151. ** return the P argument from the previous call of the same function
  5152. ** on the same [database connection] D, or NULL for
  5153. ** the first call for each function on D.
  5154. **
  5155. ** The commit and rollback hook callbacks are not reentrant.
  5156. ** The callback implementation must not do anything that will modify
  5157. ** the database connection that invoked the callback. Any actions
  5158. ** to modify the database connection must be deferred until after the
  5159. ** completion of the [sqlite3_step()] call that triggered the commit
  5160. ** or rollback hook in the first place.
  5161. ** Note that running any other SQL statements, including SELECT statements,
  5162. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  5163. ** the database connections for the meaning of "modify" in this paragraph.
  5164. **
  5165. ** ^Registering a NULL function disables the callback.
  5166. **
  5167. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  5168. ** operation is allowed to continue normally. ^If the commit hook
  5169. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  5170. ** ^The rollback hook is invoked on a rollback that results from a commit
  5171. ** hook returning non-zero, just as it would be with any other rollback.
  5172. **
  5173. ** ^For the purposes of this API, a transaction is said to have been
  5174. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  5175. ** an error or constraint causes an implicit rollback to occur.
  5176. ** ^The rollback callback is not invoked if a transaction is
  5177. ** automatically rolled back because the database connection is closed.
  5178. **
  5179. ** See also the [sqlite3_update_hook()] interface.
  5180. */
  5181. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  5182. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  5183. /*
  5184. ** CAPI3REF: Data Change Notification Callbacks
  5185. ** METHOD: sqlite3
  5186. **
  5187. ** ^The sqlite3_update_hook() interface registers a callback function
  5188. ** with the [database connection] identified by the first argument
  5189. ** to be invoked whenever a row is updated, inserted or deleted in
  5190. ** a rowid table.
  5191. ** ^Any callback set by a previous call to this function
  5192. ** for the same database connection is overridden.
  5193. **
  5194. ** ^The second argument is a pointer to the function to invoke when a
  5195. ** row is updated, inserted or deleted in a rowid table.
  5196. ** ^The first argument to the callback is a copy of the third argument
  5197. ** to sqlite3_update_hook().
  5198. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  5199. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  5200. ** to be invoked.
  5201. ** ^The third and fourth arguments to the callback contain pointers to the
  5202. ** database and table name containing the affected row.
  5203. ** ^The final callback parameter is the [rowid] of the row.
  5204. ** ^In the case of an update, this is the [rowid] after the update takes place.
  5205. **
  5206. ** ^(The update hook is not invoked when internal system tables are
  5207. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  5208. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  5209. **
  5210. ** ^In the current implementation, the update hook
  5211. ** is not invoked when duplication rows are deleted because of an
  5212. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  5213. ** invoked when rows are deleted using the [truncate optimization].
  5214. ** The exceptions defined in this paragraph might change in a future
  5215. ** release of SQLite.
  5216. **
  5217. ** The update hook implementation must not do anything that will modify
  5218. ** the database connection that invoked the update hook. Any actions
  5219. ** to modify the database connection must be deferred until after the
  5220. ** completion of the [sqlite3_step()] call that triggered the update hook.
  5221. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  5222. ** database connections for the meaning of "modify" in this paragraph.
  5223. **
  5224. ** ^The sqlite3_update_hook(D,C,P) function
  5225. ** returns the P argument from the previous call
  5226. ** on the same [database connection] D, or NULL for
  5227. ** the first call on D.
  5228. **
  5229. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5230. ** interfaces.
  5231. */
  5232. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  5233. sqlite3*,
  5234. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5235. void*
  5236. );
  5237. /*
  5238. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5239. **
  5240. ** ^(This routine enables or disables the sharing of the database cache
  5241. ** and schema data structures between [database connection | connections]
  5242. ** to the same database. Sharing is enabled if the argument is true
  5243. ** and disabled if the argument is false.)^
  5244. **
  5245. ** ^Cache sharing is enabled and disabled for an entire process.
  5246. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5247. ** sharing was enabled or disabled for each thread separately.
  5248. **
  5249. ** ^(The cache sharing mode set by this interface effects all subsequent
  5250. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5251. ** Existing database connections continue use the sharing mode
  5252. ** that was in effect at the time they were opened.)^
  5253. **
  5254. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5255. ** successfully. An [error code] is returned otherwise.)^
  5256. **
  5257. ** ^Shared cache is disabled by default. But this might change in
  5258. ** future releases of SQLite. Applications that care about shared
  5259. ** cache setting should set it explicitly.
  5260. **
  5261. ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
  5262. ** and will always return SQLITE_MISUSE. On those systems,
  5263. ** shared cache mode should be enabled per-database connection via
  5264. ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
  5265. **
  5266. ** This interface is threadsafe on processors where writing a
  5267. ** 32-bit integer is atomic.
  5268. **
  5269. ** See Also: [SQLite Shared-Cache Mode]
  5270. */
  5271. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
  5272. /*
  5273. ** CAPI3REF: Attempt To Free Heap Memory
  5274. **
  5275. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5276. ** of heap memory by deallocating non-essential memory allocations
  5277. ** held by the database library. Memory used to cache database
  5278. ** pages to improve performance is an example of non-essential memory.
  5279. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5280. ** which might be more or less than the amount requested.
  5281. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5282. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5283. **
  5284. ** See also: [sqlite3_db_release_memory()]
  5285. */
  5286. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
  5287. /*
  5288. ** CAPI3REF: Free Memory Used By A Database Connection
  5289. ** METHOD: sqlite3
  5290. **
  5291. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5292. ** memory as possible from database connection D. Unlike the
  5293. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5294. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5295. ** omitted.
  5296. **
  5297. ** See also: [sqlite3_release_memory()]
  5298. */
  5299. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
  5300. /*
  5301. ** CAPI3REF: Impose A Limit On Heap Size
  5302. **
  5303. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5304. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5305. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5306. ** limit by reducing the number of pages held in the page cache
  5307. ** as heap memory usages approaches the limit.
  5308. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5309. ** below the limit, it will exceed the limit rather than generate
  5310. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5311. ** is advisory only.
  5312. **
  5313. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5314. ** the soft heap limit prior to the call, or negative in the case of an
  5315. ** error. ^If the argument N is negative
  5316. ** then no change is made to the soft heap limit. Hence, the current
  5317. ** size of the soft heap limit can be determined by invoking
  5318. ** sqlite3_soft_heap_limit64() with a negative argument.
  5319. **
  5320. ** ^If the argument N is zero then the soft heap limit is disabled.
  5321. **
  5322. ** ^(The soft heap limit is not enforced in the current implementation
  5323. ** if one or more of following conditions are true:
  5324. **
  5325. ** <ul>
  5326. ** <li> The soft heap limit is set to zero.
  5327. ** <li> Memory accounting is disabled using a combination of the
  5328. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5329. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5330. ** <li> An alternative page cache implementation is specified using
  5331. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5332. ** <li> The page cache allocates from its own memory pool supplied
  5333. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5334. ** from the heap.
  5335. ** </ul>)^
  5336. **
  5337. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5338. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5339. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5340. ** the soft heap limit is enforced on every memory allocation. Without
  5341. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5342. ** when memory is allocated by the page cache. Testing suggests that because
  5343. ** the page cache is the predominate memory user in SQLite, most
  5344. ** applications will achieve adequate soft heap limit enforcement without
  5345. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5346. **
  5347. ** The circumstances under which SQLite will enforce the soft heap limit may
  5348. ** changes in future releases of SQLite.
  5349. */
  5350. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5351. /*
  5352. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5353. ** DEPRECATED
  5354. **
  5355. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5356. ** interface. This routine is provided for historical compatibility
  5357. ** only. All new applications should use the
  5358. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5359. */
  5360. SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
  5361. /*
  5362. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5363. ** METHOD: sqlite3
  5364. **
  5365. ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
  5366. ** information about column C of table T in database D
  5367. ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
  5368. ** interface returns SQLITE_OK and fills in the non-NULL pointers in
  5369. ** the final five arguments with appropriate values if the specified
  5370. ** column exists. ^The sqlite3_table_column_metadata() interface returns
  5371. ** SQLITE_ERROR and if the specified column does not exist.
  5372. ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
  5373. ** NULL pointer, then this routine simply checks for the existance of the
  5374. ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
  5375. ** does not.
  5376. **
  5377. ** ^The column is identified by the second, third and fourth parameters to
  5378. ** this function. ^(The second parameter is either the name of the database
  5379. ** (i.e. "main", "temp", or an attached database) containing the specified
  5380. ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
  5381. ** for the table using the same algorithm used by the database engine to
  5382. ** resolve unqualified table references.
  5383. **
  5384. ** ^The third and fourth parameters to this function are the table and column
  5385. ** name of the desired column, respectively.
  5386. **
  5387. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5388. ** and subsequent parameters to this function. ^Any of these arguments may be
  5389. ** NULL, in which case the corresponding element of metadata is omitted.
  5390. **
  5391. ** ^(<blockquote>
  5392. ** <table border="1">
  5393. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5394. **
  5395. ** <tr><td> 5th <td> const char* <td> Data type
  5396. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5397. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5398. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5399. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5400. ** </table>
  5401. ** </blockquote>)^
  5402. **
  5403. ** ^The memory pointed to by the character pointers returned for the
  5404. ** declaration type and collation sequence is valid until the next
  5405. ** call to any SQLite API function.
  5406. **
  5407. ** ^If the specified table is actually a view, an [error code] is returned.
  5408. **
  5409. ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
  5410. ** is not a [WITHOUT ROWID] table and an
  5411. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5412. ** parameters are set for the explicitly declared column. ^(If there is no
  5413. ** [INTEGER PRIMARY KEY] column, then the outputs
  5414. ** for the [rowid] are set as follows:
  5415. **
  5416. ** <pre>
  5417. ** data type: "INTEGER"
  5418. ** collation sequence: "BINARY"
  5419. ** not null: 0
  5420. ** primary key: 1
  5421. ** auto increment: 0
  5422. ** </pre>)^
  5423. **
  5424. ** ^This function causes all database schemas to be read from disk and
  5425. ** parsed, if that has not already been done, and returns an error if
  5426. ** any errors are encountered while loading the schema.
  5427. */
  5428. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  5429. sqlite3 *db, /* Connection handle */
  5430. const char *zDbName, /* Database name or NULL */
  5431. const char *zTableName, /* Table name */
  5432. const char *zColumnName, /* Column name */
  5433. char const **pzDataType, /* OUTPUT: Declared data type */
  5434. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5435. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5436. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5437. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5438. );
  5439. /*
  5440. ** CAPI3REF: Load An Extension
  5441. ** METHOD: sqlite3
  5442. **
  5443. ** ^This interface loads an SQLite extension library from the named file.
  5444. **
  5445. ** ^The sqlite3_load_extension() interface attempts to load an
  5446. ** [SQLite extension] library contained in the file zFile. If
  5447. ** the file cannot be loaded directly, attempts are made to load
  5448. ** with various operating-system specific extensions added.
  5449. ** So for example, if "samplelib" cannot be loaded, then names like
  5450. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5451. ** be tried also.
  5452. **
  5453. ** ^The entry point is zProc.
  5454. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5455. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5456. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5457. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5458. ** characters in the filename from the last "/" to the first following
  5459. ** "." and omitting any initial "lib".)^
  5460. ** ^The sqlite3_load_extension() interface returns
  5461. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5462. ** ^If an error occurs and pzErrMsg is not 0, then the
  5463. ** [sqlite3_load_extension()] interface shall attempt to
  5464. ** fill *pzErrMsg with error message text stored in memory
  5465. ** obtained from [sqlite3_malloc()]. The calling function
  5466. ** should free this memory by calling [sqlite3_free()].
  5467. **
  5468. ** ^Extension loading must be enabled using
  5469. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5470. ** otherwise an error will be returned.
  5471. **
  5472. ** See also the [load_extension() SQL function].
  5473. */
  5474. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  5475. sqlite3 *db, /* Load the extension into this database connection */
  5476. const char *zFile, /* Name of the shared library containing extension */
  5477. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5478. char **pzErrMsg /* Put error message here if not 0 */
  5479. );
  5480. /*
  5481. ** CAPI3REF: Enable Or Disable Extension Loading
  5482. ** METHOD: sqlite3
  5483. **
  5484. ** ^So as not to open security holes in older applications that are
  5485. ** unprepared to deal with [extension loading], and as a means of disabling
  5486. ** [extension loading] while evaluating user-entered SQL, the following API
  5487. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5488. **
  5489. ** ^Extension loading is off by default.
  5490. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5491. ** to turn extension loading on and call it with onoff==0 to turn
  5492. ** it back off again.
  5493. */
  5494. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5495. /*
  5496. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5497. **
  5498. ** ^This interface causes the xEntryPoint() function to be invoked for
  5499. ** each new [database connection] that is created. The idea here is that
  5500. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5501. ** that is to be automatically loaded into all new database connections.
  5502. **
  5503. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5504. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5505. ** arguments and expects and integer result as if the signature of the
  5506. ** entry point where as follows:
  5507. **
  5508. ** <blockquote><pre>
  5509. ** &nbsp; int xEntryPoint(
  5510. ** &nbsp; sqlite3 *db,
  5511. ** &nbsp; const char **pzErrMsg,
  5512. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5513. ** &nbsp; );
  5514. ** </pre></blockquote>)^
  5515. **
  5516. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5517. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5518. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5519. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5520. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5521. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5522. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5523. **
  5524. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5525. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5526. ** will be called more than once for each database connection that is opened.
  5527. **
  5528. ** See also: [sqlite3_reset_auto_extension()]
  5529. ** and [sqlite3_cancel_auto_extension()]
  5530. */
  5531. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
  5532. /*
  5533. ** CAPI3REF: Cancel Automatic Extension Loading
  5534. **
  5535. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5536. ** initialization routine X that was registered using a prior call to
  5537. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5538. ** routine returns 1 if initialization routine X was successfully
  5539. ** unregistered and it returns 0 if X was not on the list of initialization
  5540. ** routines.
  5541. */
  5542. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5543. /*
  5544. ** CAPI3REF: Reset Automatic Extension Loading
  5545. **
  5546. ** ^This interface disables all automatic extensions previously
  5547. ** registered using [sqlite3_auto_extension()].
  5548. */
  5549. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
  5550. /*
  5551. ** The interface to the virtual-table mechanism is currently considered
  5552. ** to be experimental. The interface might change in incompatible ways.
  5553. ** If this is a problem for you, do not use the interface at this time.
  5554. **
  5555. ** When the virtual-table mechanism stabilizes, we will declare the
  5556. ** interface fixed, support it indefinitely, and remove this comment.
  5557. */
  5558. /*
  5559. ** Structures used by the virtual table interface
  5560. */
  5561. typedef struct sqlite3_vtab sqlite3_vtab;
  5562. typedef struct sqlite3_index_info sqlite3_index_info;
  5563. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5564. typedef struct sqlite3_module sqlite3_module;
  5565. /*
  5566. ** CAPI3REF: Virtual Table Object
  5567. ** KEYWORDS: sqlite3_module {virtual table module}
  5568. **
  5569. ** This structure, sometimes called a "virtual table module",
  5570. ** defines the implementation of a [virtual tables].
  5571. ** This structure consists mostly of methods for the module.
  5572. **
  5573. ** ^A virtual table module is created by filling in a persistent
  5574. ** instance of this structure and passing a pointer to that instance
  5575. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5576. ** ^The registration remains valid until it is replaced by a different
  5577. ** module or until the [database connection] closes. The content
  5578. ** of this structure must not change while it is registered with
  5579. ** any database connection.
  5580. */
  5581. struct sqlite3_module {
  5582. int iVersion;
  5583. int (*xCreate)(sqlite3*, void *pAux,
  5584. int argc, const char *const*argv,
  5585. sqlite3_vtab **ppVTab, char**);
  5586. int (*xConnect)(sqlite3*, void *pAux,
  5587. int argc, const char *const*argv,
  5588. sqlite3_vtab **ppVTab, char**);
  5589. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5590. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5591. int (*xDestroy)(sqlite3_vtab *pVTab);
  5592. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5593. int (*xClose)(sqlite3_vtab_cursor*);
  5594. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5595. int argc, sqlite3_value **argv);
  5596. int (*xNext)(sqlite3_vtab_cursor*);
  5597. int (*xEof)(sqlite3_vtab_cursor*);
  5598. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5599. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5600. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5601. int (*xBegin)(sqlite3_vtab *pVTab);
  5602. int (*xSync)(sqlite3_vtab *pVTab);
  5603. int (*xCommit)(sqlite3_vtab *pVTab);
  5604. int (*xRollback)(sqlite3_vtab *pVTab);
  5605. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5606. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5607. void **ppArg);
  5608. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5609. /* The methods above are in version 1 of the sqlite_module object. Those
  5610. ** below are for version 2 and greater. */
  5611. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5612. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5613. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5614. };
  5615. /*
  5616. ** CAPI3REF: Virtual Table Indexing Information
  5617. ** KEYWORDS: sqlite3_index_info
  5618. **
  5619. ** The sqlite3_index_info structure and its substructures is used as part
  5620. ** of the [virtual table] interface to
  5621. ** pass information into and receive the reply from the [xBestIndex]
  5622. ** method of a [virtual table module]. The fields under **Inputs** are the
  5623. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5624. ** results into the **Outputs** fields.
  5625. **
  5626. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5627. **
  5628. ** <blockquote>column OP expr</blockquote>
  5629. **
  5630. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5631. ** stored in aConstraint[].op using one of the
  5632. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5633. ** ^(The index of the column is stored in
  5634. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5635. ** expr on the right-hand side can be evaluated (and thus the constraint
  5636. ** is usable) and false if it cannot.)^
  5637. **
  5638. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5639. ** and makes other simplifications to the WHERE clause in an attempt to
  5640. ** get as many WHERE clause terms into the form shown above as possible.
  5641. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5642. ** relevant to the particular virtual table being queried.
  5643. **
  5644. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5645. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5646. **
  5647. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5648. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5649. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5650. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5651. ** is true, then the constraint is assumed to be fully handled by the
  5652. ** virtual table and is not checked again by SQLite.)^
  5653. **
  5654. ** ^The idxNum and idxPtr values are recorded and passed into the
  5655. ** [xFilter] method.
  5656. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5657. ** needToFreeIdxPtr is true.
  5658. **
  5659. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5660. ** the correct order to satisfy the ORDER BY clause so that no separate
  5661. ** sorting step is required.
  5662. **
  5663. ** ^The estimatedCost value is an estimate of the cost of a particular
  5664. ** strategy. A cost of N indicates that the cost of the strategy is similar
  5665. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  5666. ** indicates that the expense of the operation is similar to that of a
  5667. ** binary search on a unique indexed field of an SQLite table with N rows.
  5668. **
  5669. ** ^The estimatedRows value is an estimate of the number of rows that
  5670. ** will be returned by the strategy.
  5671. **
  5672. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  5673. ** structure for SQLite version 3.8.2. If a virtual table extension is
  5674. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  5675. ** to read or write the estimatedRows field are undefined (but are likely
  5676. ** to included crashing the application). The estimatedRows field should
  5677. ** therefore only be used if [sqlite3_libversion_number()] returns a
  5678. ** value greater than or equal to 3008002.
  5679. */
  5680. struct sqlite3_index_info {
  5681. /* Inputs */
  5682. int nConstraint; /* Number of entries in aConstraint */
  5683. struct sqlite3_index_constraint {
  5684. int iColumn; /* Column on left-hand side of constraint */
  5685. unsigned char op; /* Constraint operator */
  5686. unsigned char usable; /* True if this constraint is usable */
  5687. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5688. } *aConstraint; /* Table of WHERE clause constraints */
  5689. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5690. struct sqlite3_index_orderby {
  5691. int iColumn; /* Column number */
  5692. unsigned char desc; /* True for DESC. False for ASC. */
  5693. } *aOrderBy; /* The ORDER BY clause */
  5694. /* Outputs */
  5695. struct sqlite3_index_constraint_usage {
  5696. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5697. unsigned char omit; /* Do not code a test for this constraint */
  5698. } *aConstraintUsage;
  5699. int idxNum; /* Number used to identify the index */
  5700. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5701. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5702. int orderByConsumed; /* True if output is already ordered */
  5703. double estimatedCost; /* Estimated cost of using this index */
  5704. /* Fields below are only available in SQLite 3.8.2 and later */
  5705. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  5706. };
  5707. /*
  5708. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5709. **
  5710. ** These macros defined the allowed values for the
  5711. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5712. ** an operator that is part of a constraint term in the wHERE clause of
  5713. ** a query that uses a [virtual table].
  5714. */
  5715. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5716. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5717. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5718. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5719. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5720. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5721. /*
  5722. ** CAPI3REF: Register A Virtual Table Implementation
  5723. ** METHOD: sqlite3
  5724. **
  5725. ** ^These routines are used to register a new [virtual table module] name.
  5726. ** ^Module names must be registered before
  5727. ** creating a new [virtual table] using the module and before using a
  5728. ** preexisting [virtual table] for the module.
  5729. **
  5730. ** ^The module name is registered on the [database connection] specified
  5731. ** by the first parameter. ^The name of the module is given by the
  5732. ** second parameter. ^The third parameter is a pointer to
  5733. ** the implementation of the [virtual table module]. ^The fourth
  5734. ** parameter is an arbitrary client data pointer that is passed through
  5735. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5736. ** when a new virtual table is be being created or reinitialized.
  5737. **
  5738. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5739. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5740. ** invoke the destructor function (if it is not NULL) when SQLite
  5741. ** no longer needs the pClientData pointer. ^The destructor will also
  5742. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5743. ** ^The sqlite3_create_module()
  5744. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5745. ** destructor.
  5746. */
  5747. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  5748. sqlite3 *db, /* SQLite connection to register module with */
  5749. const char *zName, /* Name of the module */
  5750. const sqlite3_module *p, /* Methods for the module */
  5751. void *pClientData /* Client data for xCreate/xConnect */
  5752. );
  5753. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  5754. sqlite3 *db, /* SQLite connection to register module with */
  5755. const char *zName, /* Name of the module */
  5756. const sqlite3_module *p, /* Methods for the module */
  5757. void *pClientData, /* Client data for xCreate/xConnect */
  5758. void(*xDestroy)(void*) /* Module destructor function */
  5759. );
  5760. /*
  5761. ** CAPI3REF: Virtual Table Instance Object
  5762. ** KEYWORDS: sqlite3_vtab
  5763. **
  5764. ** Every [virtual table module] implementation uses a subclass
  5765. ** of this object to describe a particular instance
  5766. ** of the [virtual table]. Each subclass will
  5767. ** be tailored to the specific needs of the module implementation.
  5768. ** The purpose of this superclass is to define certain fields that are
  5769. ** common to all module implementations.
  5770. **
  5771. ** ^Virtual tables methods can set an error message by assigning a
  5772. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5773. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5774. ** prior to assigning a new string to zErrMsg. ^After the error message
  5775. ** is delivered up to the client application, the string will be automatically
  5776. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5777. */
  5778. struct sqlite3_vtab {
  5779. const sqlite3_module *pModule; /* The module for this virtual table */
  5780. int nRef; /* Number of open cursors */
  5781. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5782. /* Virtual table implementations will typically add additional fields */
  5783. };
  5784. /*
  5785. ** CAPI3REF: Virtual Table Cursor Object
  5786. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5787. **
  5788. ** Every [virtual table module] implementation uses a subclass of the
  5789. ** following structure to describe cursors that point into the
  5790. ** [virtual table] and are used
  5791. ** to loop through the virtual table. Cursors are created using the
  5792. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5793. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5794. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5795. ** of the module. Each module implementation will define
  5796. ** the content of a cursor structure to suit its own needs.
  5797. **
  5798. ** This superclass exists in order to define fields of the cursor that
  5799. ** are common to all implementations.
  5800. */
  5801. struct sqlite3_vtab_cursor {
  5802. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5803. /* Virtual table implementations will typically add additional fields */
  5804. };
  5805. /*
  5806. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5807. **
  5808. ** ^The [xCreate] and [xConnect] methods of a
  5809. ** [virtual table module] call this interface
  5810. ** to declare the format (the names and datatypes of the columns) of
  5811. ** the virtual tables they implement.
  5812. */
  5813. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5814. /*
  5815. ** CAPI3REF: Overload A Function For A Virtual Table
  5816. ** METHOD: sqlite3
  5817. **
  5818. ** ^(Virtual tables can provide alternative implementations of functions
  5819. ** using the [xFindFunction] method of the [virtual table module].
  5820. ** But global versions of those functions
  5821. ** must exist in order to be overloaded.)^
  5822. **
  5823. ** ^(This API makes sure a global version of a function with a particular
  5824. ** name and number of parameters exists. If no such function exists
  5825. ** before this API is called, a new function is created.)^ ^The implementation
  5826. ** of the new function always causes an exception to be thrown. So
  5827. ** the new function is not good for anything by itself. Its only
  5828. ** purpose is to be a placeholder function that can be overloaded
  5829. ** by a [virtual table].
  5830. */
  5831. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5832. /*
  5833. ** The interface to the virtual-table mechanism defined above (back up
  5834. ** to a comment remarkably similar to this one) is currently considered
  5835. ** to be experimental. The interface might change in incompatible ways.
  5836. ** If this is a problem for you, do not use the interface at this time.
  5837. **
  5838. ** When the virtual-table mechanism stabilizes, we will declare the
  5839. ** interface fixed, support it indefinitely, and remove this comment.
  5840. */
  5841. /*
  5842. ** CAPI3REF: A Handle To An Open BLOB
  5843. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5844. **
  5845. ** An instance of this object represents an open BLOB on which
  5846. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5847. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5848. ** and destroyed by [sqlite3_blob_close()].
  5849. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5850. ** can be used to read or write small subsections of the BLOB.
  5851. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5852. */
  5853. typedef struct sqlite3_blob sqlite3_blob;
  5854. /*
  5855. ** CAPI3REF: Open A BLOB For Incremental I/O
  5856. ** METHOD: sqlite3
  5857. ** CONSTRUCTOR: sqlite3_blob
  5858. **
  5859. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5860. ** in row iRow, column zColumn, table zTable in database zDb;
  5861. ** in other words, the same BLOB that would be selected by:
  5862. **
  5863. ** <pre>
  5864. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5865. ** </pre>)^
  5866. **
  5867. ** ^(Parameter zDb is not the filename that contains the database, but
  5868. ** rather the symbolic name of the database. For attached databases, this is
  5869. ** the name that appears after the AS keyword in the [ATTACH] statement.
  5870. ** For the main database file, the database name is "main". For TEMP
  5871. ** tables, the database name is "temp".)^
  5872. **
  5873. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5874. ** and write access. ^If the flags parameter is zero, the BLOB is opened for
  5875. ** read-only access.
  5876. **
  5877. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
  5878. ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
  5879. ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
  5880. ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
  5881. ** on *ppBlob after this function it returns.
  5882. **
  5883. ** This function fails with SQLITE_ERROR if any of the following are true:
  5884. ** <ul>
  5885. ** <li> ^(Database zDb does not exist)^,
  5886. ** <li> ^(Table zTable does not exist within database zDb)^,
  5887. ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
  5888. ** <li> ^(Column zColumn does not exist)^,
  5889. ** <li> ^(Row iRow is not present in the table)^,
  5890. ** <li> ^(The specified column of row iRow contains a value that is not
  5891. ** a TEXT or BLOB value)^,
  5892. ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
  5893. ** constraint and the blob is being opened for read/write access)^,
  5894. ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
  5895. ** column zColumn is part of a [child key] definition and the blob is
  5896. ** being opened for read/write access)^.
  5897. ** </ul>
  5898. **
  5899. ** ^Unless it returns SQLITE_MISUSE, this function sets the
  5900. ** [database connection] error code and message accessible via
  5901. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  5902. **
  5903. **
  5904. ** ^(If the row that a BLOB handle points to is modified by an
  5905. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5906. ** then the BLOB handle is marked as "expired".
  5907. ** This is true if any column of the row is changed, even a column
  5908. ** other than the one the BLOB handle is open on.)^
  5909. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5910. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5911. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5912. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5913. ** commit if the transaction continues to completion.)^
  5914. **
  5915. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5916. ** the opened blob. ^The size of a blob may not be changed by this
  5917. ** interface. Use the [UPDATE] SQL command to change the size of a
  5918. ** blob.
  5919. **
  5920. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5921. ** and the built-in [zeroblob] SQL function may be used to create a
  5922. ** zero-filled blob to read or write using the incremental-blob interface.
  5923. **
  5924. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5925. ** be released by a call to [sqlite3_blob_close()].
  5926. */
  5927. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  5928. sqlite3*,
  5929. const char *zDb,
  5930. const char *zTable,
  5931. const char *zColumn,
  5932. sqlite3_int64 iRow,
  5933. int flags,
  5934. sqlite3_blob **ppBlob
  5935. );
  5936. /*
  5937. ** CAPI3REF: Move a BLOB Handle to a New Row
  5938. ** METHOD: sqlite3_blob
  5939. **
  5940. ** ^This function is used to move an existing blob handle so that it points
  5941. ** to a different row of the same database table. ^The new row is identified
  5942. ** by the rowid value passed as the second argument. Only the row can be
  5943. ** changed. ^The database, table and column on which the blob handle is open
  5944. ** remain the same. Moving an existing blob handle to a new row can be
  5945. ** faster than closing the existing handle and opening a new one.
  5946. **
  5947. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5948. ** it must exist and there must be either a blob or text value stored in
  5949. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5950. ** it does not contain a blob or text value, or if another error occurs, an
  5951. ** SQLite error code is returned and the blob handle is considered aborted.
  5952. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5953. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5954. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5955. ** always returns zero.
  5956. **
  5957. ** ^This function sets the database handle error code and message.
  5958. */
  5959. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5960. /*
  5961. ** CAPI3REF: Close A BLOB Handle
  5962. ** DESTRUCTOR: sqlite3_blob
  5963. **
  5964. ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
  5965. ** unconditionally. Even if this routine returns an error code, the
  5966. ** handle is still closed.)^
  5967. **
  5968. ** ^If the blob handle being closed was opened for read-write access, and if
  5969. ** the database is in auto-commit mode and there are no other open read-write
  5970. ** blob handles or active write statements, the current transaction is
  5971. ** committed. ^If an error occurs while committing the transaction, an error
  5972. ** code is returned and the transaction rolled back.
  5973. **
  5974. ** Calling this function with an argument that is not a NULL pointer or an
  5975. ** open blob handle results in undefined behaviour. ^Calling this routine
  5976. ** with a null pointer (such as would be returned by a failed call to
  5977. ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
  5978. ** is passed a valid open blob handle, the values returned by the
  5979. ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
  5980. */
  5981. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
  5982. /*
  5983. ** CAPI3REF: Return The Size Of An Open BLOB
  5984. ** METHOD: sqlite3_blob
  5985. **
  5986. ** ^Returns the size in bytes of the BLOB accessible via the
  5987. ** successfully opened [BLOB handle] in its only argument. ^The
  5988. ** incremental blob I/O routines can only read or overwriting existing
  5989. ** blob content; they cannot change the size of a blob.
  5990. **
  5991. ** This routine only works on a [BLOB handle] which has been created
  5992. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5993. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5994. ** to this routine results in undefined and probably undesirable behavior.
  5995. */
  5996. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
  5997. /*
  5998. ** CAPI3REF: Read Data From A BLOB Incrementally
  5999. ** METHOD: sqlite3_blob
  6000. **
  6001. ** ^(This function is used to read data from an open [BLOB handle] into a
  6002. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  6003. ** from the open BLOB, starting at offset iOffset.)^
  6004. **
  6005. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6006. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  6007. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  6008. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  6009. ** can be determined using the [sqlite3_blob_bytes()] interface.
  6010. **
  6011. ** ^An attempt to read from an expired [BLOB handle] fails with an
  6012. ** error code of [SQLITE_ABORT].
  6013. **
  6014. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  6015. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6016. **
  6017. ** This routine only works on a [BLOB handle] which has been created
  6018. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6019. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6020. ** to this routine results in undefined and probably undesirable behavior.
  6021. **
  6022. ** See also: [sqlite3_blob_write()].
  6023. */
  6024. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  6025. /*
  6026. ** CAPI3REF: Write Data Into A BLOB Incrementally
  6027. ** METHOD: sqlite3_blob
  6028. **
  6029. ** ^(This function is used to write data into an open [BLOB handle] from a
  6030. ** caller-supplied buffer. N bytes of data are copied from the buffer Z
  6031. ** into the open BLOB, starting at offset iOffset.)^
  6032. **
  6033. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  6034. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  6035. ** ^Unless SQLITE_MISUSE is returned, this function sets the
  6036. ** [database connection] error code and message accessible via
  6037. ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
  6038. **
  6039. ** ^If the [BLOB handle] passed as the first argument was not opened for
  6040. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  6041. ** this function returns [SQLITE_READONLY].
  6042. **
  6043. ** This function may only modify the contents of the BLOB; it is
  6044. ** not possible to increase the size of a BLOB using this API.
  6045. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  6046. ** [SQLITE_ERROR] is returned and no data is written. The size of the
  6047. ** BLOB (and hence the maximum value of N+iOffset) can be determined
  6048. ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
  6049. ** than zero [SQLITE_ERROR] is returned and no data is written.
  6050. **
  6051. ** ^An attempt to write to an expired [BLOB handle] fails with an
  6052. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  6053. ** before the [BLOB handle] expired are not rolled back by the
  6054. ** expiration of the handle, though of course those changes might
  6055. ** have been overwritten by the statement that expired the BLOB handle
  6056. ** or by other independent statements.
  6057. **
  6058. ** This routine only works on a [BLOB handle] which has been created
  6059. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  6060. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  6061. ** to this routine results in undefined and probably undesirable behavior.
  6062. **
  6063. ** See also: [sqlite3_blob_read()].
  6064. */
  6065. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  6066. /*
  6067. ** CAPI3REF: Virtual File System Objects
  6068. **
  6069. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  6070. ** that SQLite uses to interact
  6071. ** with the underlying operating system. Most SQLite builds come with a
  6072. ** single default VFS that is appropriate for the host computer.
  6073. ** New VFSes can be registered and existing VFSes can be unregistered.
  6074. ** The following interfaces are provided.
  6075. **
  6076. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  6077. ** ^Names are case sensitive.
  6078. ** ^Names are zero-terminated UTF-8 strings.
  6079. ** ^If there is no match, a NULL pointer is returned.
  6080. ** ^If zVfsName is NULL then the default VFS is returned.
  6081. **
  6082. ** ^New VFSes are registered with sqlite3_vfs_register().
  6083. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  6084. ** ^The same VFS can be registered multiple times without injury.
  6085. ** ^To make an existing VFS into the default VFS, register it again
  6086. ** with the makeDflt flag set. If two different VFSes with the
  6087. ** same name are registered, the behavior is undefined. If a
  6088. ** VFS is registered with a name that is NULL or an empty string,
  6089. ** then the behavior is undefined.
  6090. **
  6091. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  6092. ** ^(If the default VFS is unregistered, another VFS is chosen as
  6093. ** the default. The choice for the new VFS is arbitrary.)^
  6094. */
  6095. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
  6096. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  6097. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
  6098. /*
  6099. ** CAPI3REF: Mutexes
  6100. **
  6101. ** The SQLite core uses these routines for thread
  6102. ** synchronization. Though they are intended for internal
  6103. ** use by SQLite, code that links against SQLite is
  6104. ** permitted to use any of these routines.
  6105. **
  6106. ** The SQLite source code contains multiple implementations
  6107. ** of these mutex routines. An appropriate implementation
  6108. ** is selected automatically at compile-time. The following
  6109. ** implementations are available in the SQLite core:
  6110. **
  6111. ** <ul>
  6112. ** <li> SQLITE_MUTEX_PTHREADS
  6113. ** <li> SQLITE_MUTEX_W32
  6114. ** <li> SQLITE_MUTEX_NOOP
  6115. ** </ul>
  6116. **
  6117. ** The SQLITE_MUTEX_NOOP implementation is a set of routines
  6118. ** that does no real locking and is appropriate for use in
  6119. ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
  6120. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  6121. ** and Windows.
  6122. **
  6123. ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  6124. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  6125. ** implementation is included with the library. In this case the
  6126. ** application must supply a custom mutex implementation using the
  6127. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  6128. ** before calling sqlite3_initialize() or any other public sqlite3_
  6129. ** function that calls sqlite3_initialize().
  6130. **
  6131. ** ^The sqlite3_mutex_alloc() routine allocates a new
  6132. ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
  6133. ** routine returns NULL if it is unable to allocate the requested
  6134. ** mutex. The argument to sqlite3_mutex_alloc() must one of these
  6135. ** integer constants:
  6136. **
  6137. ** <ul>
  6138. ** <li> SQLITE_MUTEX_FAST
  6139. ** <li> SQLITE_MUTEX_RECURSIVE
  6140. ** <li> SQLITE_MUTEX_STATIC_MASTER
  6141. ** <li> SQLITE_MUTEX_STATIC_MEM
  6142. ** <li> SQLITE_MUTEX_STATIC_OPEN
  6143. ** <li> SQLITE_MUTEX_STATIC_PRNG
  6144. ** <li> SQLITE_MUTEX_STATIC_LRU
  6145. ** <li> SQLITE_MUTEX_STATIC_PMEM
  6146. ** <li> SQLITE_MUTEX_STATIC_APP1
  6147. ** <li> SQLITE_MUTEX_STATIC_APP2
  6148. ** <li> SQLITE_MUTEX_STATIC_APP3
  6149. ** </ul>
  6150. **
  6151. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  6152. ** cause sqlite3_mutex_alloc() to create
  6153. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  6154. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  6155. ** The mutex implementation does not need to make a distinction
  6156. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  6157. ** not want to. SQLite will only request a recursive mutex in
  6158. ** cases where it really needs one. If a faster non-recursive mutex
  6159. ** implementation is available on the host platform, the mutex subsystem
  6160. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  6161. **
  6162. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  6163. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  6164. ** a pointer to a static preexisting mutex. ^Nine static mutexes are
  6165. ** used by the current version of SQLite. Future versions of SQLite
  6166. ** may add additional static mutexes. Static mutexes are for internal
  6167. ** use by SQLite only. Applications that use SQLite mutexes should
  6168. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  6169. ** SQLITE_MUTEX_RECURSIVE.
  6170. **
  6171. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  6172. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  6173. ** returns a different mutex on every call. ^For the static
  6174. ** mutex types, the same mutex is returned on every call that has
  6175. ** the same type number.
  6176. **
  6177. ** ^The sqlite3_mutex_free() routine deallocates a previously
  6178. ** allocated dynamic mutex. Attempting to deallocate a static
  6179. ** mutex results in undefined behavior.
  6180. **
  6181. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  6182. ** to enter a mutex. ^If another thread is already within the mutex,
  6183. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  6184. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  6185. ** upon successful entry. ^(Mutexes created using
  6186. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  6187. ** In such cases, the
  6188. ** mutex must be exited an equal number of times before another thread
  6189. ** can enter.)^ If the same thread tries to enter any mutex other
  6190. ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
  6191. **
  6192. ** ^(Some systems (for example, Windows 95) do not support the operation
  6193. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  6194. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  6195. ** sqlite3_mutex_try() as an optimization so this is acceptable
  6196. ** behavior.)^
  6197. **
  6198. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  6199. ** previously entered by the same thread. The behavior
  6200. ** is undefined if the mutex is not currently entered by the
  6201. ** calling thread or is not currently allocated.
  6202. **
  6203. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  6204. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  6205. ** behave as no-ops.
  6206. **
  6207. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  6208. */
  6209. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
  6210. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
  6211. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
  6212. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
  6213. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
  6214. /*
  6215. ** CAPI3REF: Mutex Methods Object
  6216. **
  6217. ** An instance of this structure defines the low-level routines
  6218. ** used to allocate and use mutexes.
  6219. **
  6220. ** Usually, the default mutex implementations provided by SQLite are
  6221. ** sufficient, however the application has the option of substituting a custom
  6222. ** implementation for specialized deployments or systems for which SQLite
  6223. ** does not provide a suitable implementation. In this case, the application
  6224. ** creates and populates an instance of this structure to pass
  6225. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  6226. ** Additionally, an instance of this structure can be used as an
  6227. ** output variable when querying the system for the current mutex
  6228. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  6229. **
  6230. ** ^The xMutexInit method defined by this structure is invoked as
  6231. ** part of system initialization by the sqlite3_initialize() function.
  6232. ** ^The xMutexInit routine is called by SQLite exactly once for each
  6233. ** effective call to [sqlite3_initialize()].
  6234. **
  6235. ** ^The xMutexEnd method defined by this structure is invoked as
  6236. ** part of system shutdown by the sqlite3_shutdown() function. The
  6237. ** implementation of this method is expected to release all outstanding
  6238. ** resources obtained by the mutex methods implementation, especially
  6239. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  6240. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  6241. **
  6242. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  6243. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  6244. ** xMutexNotheld) implement the following interfaces (respectively):
  6245. **
  6246. ** <ul>
  6247. ** <li> [sqlite3_mutex_alloc()] </li>
  6248. ** <li> [sqlite3_mutex_free()] </li>
  6249. ** <li> [sqlite3_mutex_enter()] </li>
  6250. ** <li> [sqlite3_mutex_try()] </li>
  6251. ** <li> [sqlite3_mutex_leave()] </li>
  6252. ** <li> [sqlite3_mutex_held()] </li>
  6253. ** <li> [sqlite3_mutex_notheld()] </li>
  6254. ** </ul>)^
  6255. **
  6256. ** The only difference is that the public sqlite3_XXX functions enumerated
  6257. ** above silently ignore any invocations that pass a NULL pointer instead
  6258. ** of a valid mutex handle. The implementations of the methods defined
  6259. ** by this structure are not required to handle this case, the results
  6260. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6261. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6262. ** it is passed a NULL pointer).
  6263. **
  6264. ** The xMutexInit() method must be threadsafe. It must be harmless to
  6265. ** invoke xMutexInit() multiple times within the same process and without
  6266. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6267. ** xMutexInit() must be no-ops.
  6268. **
  6269. ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6270. ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
  6271. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6272. ** memory allocation for a fast or recursive mutex.
  6273. **
  6274. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6275. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6276. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6277. ** prior to returning.
  6278. */
  6279. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6280. struct sqlite3_mutex_methods {
  6281. int (*xMutexInit)(void);
  6282. int (*xMutexEnd)(void);
  6283. sqlite3_mutex *(*xMutexAlloc)(int);
  6284. void (*xMutexFree)(sqlite3_mutex *);
  6285. void (*xMutexEnter)(sqlite3_mutex *);
  6286. int (*xMutexTry)(sqlite3_mutex *);
  6287. void (*xMutexLeave)(sqlite3_mutex *);
  6288. int (*xMutexHeld)(sqlite3_mutex *);
  6289. int (*xMutexNotheld)(sqlite3_mutex *);
  6290. };
  6291. /*
  6292. ** CAPI3REF: Mutex Verification Routines
  6293. **
  6294. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6295. ** are intended for use inside assert() statements. The SQLite core
  6296. ** never uses these routines except inside an assert() and applications
  6297. ** are advised to follow the lead of the core. The SQLite core only
  6298. ** provides implementations for these routines when it is compiled
  6299. ** with the SQLITE_DEBUG flag. External mutex implementations
  6300. ** are only required to provide these routines if SQLITE_DEBUG is
  6301. ** defined and if NDEBUG is not defined.
  6302. **
  6303. ** These routines should return true if the mutex in their argument
  6304. ** is held or not held, respectively, by the calling thread.
  6305. **
  6306. ** The implementation is not required to provide versions of these
  6307. ** routines that actually work. If the implementation does not provide working
  6308. ** versions of these routines, it should at least provide stubs that always
  6309. ** return true so that one does not get spurious assertion failures.
  6310. **
  6311. ** If the argument to sqlite3_mutex_held() is a NULL pointer then
  6312. ** the routine should return 1. This seems counter-intuitive since
  6313. ** clearly the mutex cannot be held if it does not exist. But
  6314. ** the reason the mutex does not exist is because the build is not
  6315. ** using mutexes. And we do not want the assert() containing the
  6316. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6317. ** the appropriate thing to do. The sqlite3_mutex_notheld()
  6318. ** interface should also return 1 when given a NULL pointer.
  6319. */
  6320. #ifndef NDEBUG
  6321. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
  6322. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
  6323. #endif
  6324. /*
  6325. ** CAPI3REF: Mutex Types
  6326. **
  6327. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6328. ** which is one of these integer constants.
  6329. **
  6330. ** The set of static mutexes may change from one SQLite release to the
  6331. ** next. Applications that override the built-in mutex logic must be
  6332. ** prepared to accommodate additional static mutexes.
  6333. */
  6334. #define SQLITE_MUTEX_FAST 0
  6335. #define SQLITE_MUTEX_RECURSIVE 1
  6336. #define SQLITE_MUTEX_STATIC_MASTER 2
  6337. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6338. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6339. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6340. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6341. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6342. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6343. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6344. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6345. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6346. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6347. #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
  6348. #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
  6349. #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
  6350. /*
  6351. ** CAPI3REF: Retrieve the mutex for a database connection
  6352. ** METHOD: sqlite3
  6353. **
  6354. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6355. ** serializes access to the [database connection] given in the argument
  6356. ** when the [threading mode] is Serialized.
  6357. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6358. ** routine returns a NULL pointer.
  6359. */
  6360. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
  6361. /*
  6362. ** CAPI3REF: Low-Level Control Of Database Files
  6363. ** METHOD: sqlite3
  6364. **
  6365. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6366. ** xFileControl method for the [sqlite3_io_methods] object associated
  6367. ** with a particular database identified by the second argument. ^The
  6368. ** name of the database is "main" for the main database or "temp" for the
  6369. ** TEMP database, or the name that appears after the AS keyword for
  6370. ** databases that are added using the [ATTACH] SQL command.
  6371. ** ^A NULL pointer can be used in place of "main" to refer to the
  6372. ** main database file.
  6373. ** ^The third and fourth parameters to this routine
  6374. ** are passed directly through to the second and third parameters of
  6375. ** the xFileControl method. ^The return value of the xFileControl
  6376. ** method becomes the return value of this routine.
  6377. **
  6378. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6379. ** a pointer to the underlying [sqlite3_file] object to be written into
  6380. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6381. ** case is a short-circuit path which does not actually invoke the
  6382. ** underlying sqlite3_io_methods.xFileControl method.
  6383. **
  6384. ** ^If the second parameter (zDbName) does not match the name of any
  6385. ** open database file, then SQLITE_ERROR is returned. ^This error
  6386. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6387. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6388. ** also return SQLITE_ERROR. There is no way to distinguish between
  6389. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6390. ** xFileControl method.
  6391. **
  6392. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6393. */
  6394. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6395. /*
  6396. ** CAPI3REF: Testing Interface
  6397. **
  6398. ** ^The sqlite3_test_control() interface is used to read out internal
  6399. ** state of SQLite and to inject faults into SQLite for testing
  6400. ** purposes. ^The first parameter is an operation code that determines
  6401. ** the number, meaning, and operation of all subsequent parameters.
  6402. **
  6403. ** This interface is not for use by applications. It exists solely
  6404. ** for verifying the correct operation of the SQLite library. Depending
  6405. ** on how the SQLite library is compiled, this interface might not exist.
  6406. **
  6407. ** The details of the operation codes, their meanings, the parameters
  6408. ** they take, and what they do are all subject to change without notice.
  6409. ** Unlike most of the SQLite API, this function is not guaranteed to
  6410. ** operate consistently from one release to the next.
  6411. */
  6412. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
  6413. /*
  6414. ** CAPI3REF: Testing Interface Operation Codes
  6415. **
  6416. ** These constants are the valid operation code parameters used
  6417. ** as the first argument to [sqlite3_test_control()].
  6418. **
  6419. ** These parameters and their meanings are subject to change
  6420. ** without notice. These values are for testing purposes only.
  6421. ** Applications should not use any of these parameters or the
  6422. ** [sqlite3_test_control()] interface.
  6423. */
  6424. #define SQLITE_TESTCTRL_FIRST 5
  6425. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6426. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6427. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6428. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6429. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6430. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6431. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6432. #define SQLITE_TESTCTRL_ASSERT 12
  6433. #define SQLITE_TESTCTRL_ALWAYS 13
  6434. #define SQLITE_TESTCTRL_RESERVE 14
  6435. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6436. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6437. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6438. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6439. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6440. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6441. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6442. #define SQLITE_TESTCTRL_BYTEORDER 22
  6443. #define SQLITE_TESTCTRL_ISINIT 23
  6444. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6445. #define SQLITE_TESTCTRL_IMPOSTER 25
  6446. #define SQLITE_TESTCTRL_LAST 25
  6447. /*
  6448. ** CAPI3REF: SQLite Runtime Status
  6449. **
  6450. ** ^These interfaces are used to retrieve runtime status information
  6451. ** about the performance of SQLite, and optionally to reset various
  6452. ** highwater marks. ^The first argument is an integer code for
  6453. ** the specific parameter to measure. ^(Recognized integer codes
  6454. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6455. ** ^The current value of the parameter is returned into *pCurrent.
  6456. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6457. ** resetFlag is true, then the highest record value is reset after
  6458. ** *pHighwater is written. ^(Some parameters do not record the highest
  6459. ** value. For those parameters
  6460. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6461. ** ^(Other parameters record only the highwater mark and not the current
  6462. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6463. **
  6464. ** ^The sqlite3_status() and sqlite3_status64() routines return
  6465. ** SQLITE_OK on success and a non-zero [error code] on failure.
  6466. **
  6467. ** If either the current value or the highwater mark is too large to
  6468. ** be represented by a 32-bit integer, then the values returned by
  6469. ** sqlite3_status() are undefined.
  6470. **
  6471. ** See also: [sqlite3_db_status()]
  6472. */
  6473. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6474. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  6475. int op,
  6476. sqlite3_int64 *pCurrent,
  6477. sqlite3_int64 *pHighwater,
  6478. int resetFlag
  6479. );
  6480. /*
  6481. ** CAPI3REF: Status Parameters
  6482. ** KEYWORDS: {status parameters}
  6483. **
  6484. ** These integer constants designate various run-time status parameters
  6485. ** that can be returned by [sqlite3_status()].
  6486. **
  6487. ** <dl>
  6488. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6489. ** <dd>This parameter is the current amount of memory checked out
  6490. ** using [sqlite3_malloc()], either directly or indirectly. The
  6491. ** figure includes calls made to [sqlite3_malloc()] by the application
  6492. ** and internal memory usage by the SQLite library. Scratch memory
  6493. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6494. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6495. ** this parameter. The amount returned is the sum of the allocation
  6496. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6497. **
  6498. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6499. ** <dd>This parameter records the largest memory allocation request
  6500. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6501. ** internal equivalents). Only the value returned in the
  6502. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6503. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6504. **
  6505. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6506. ** <dd>This parameter records the number of separate memory allocations
  6507. ** currently checked out.</dd>)^
  6508. **
  6509. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6510. ** <dd>This parameter returns the number of pages used out of the
  6511. ** [pagecache memory allocator] that was configured using
  6512. ** [SQLITE_CONFIG_PAGECACHE]. The
  6513. ** value returned is in pages, not in bytes.</dd>)^
  6514. **
  6515. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6516. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6517. ** <dd>This parameter returns the number of bytes of page cache
  6518. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6519. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6520. ** returned value includes allocations that overflowed because they
  6521. ** where too large (they were larger than the "sz" parameter to
  6522. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6523. ** no space was left in the page cache.</dd>)^
  6524. **
  6525. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6526. ** <dd>This parameter records the largest memory allocation request
  6527. ** handed to [pagecache memory allocator]. Only the value returned in the
  6528. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6529. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6530. **
  6531. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6532. ** <dd>This parameter returns the number of allocations used out of the
  6533. ** [scratch memory allocator] configured using
  6534. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6535. ** in bytes. Since a single thread may only have one scratch allocation
  6536. ** outstanding at time, this parameter also reports the number of threads
  6537. ** using scratch memory at the same time.</dd>)^
  6538. **
  6539. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6540. ** <dd>This parameter returns the number of bytes of scratch memory
  6541. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6542. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6543. ** returned include overflows because the requested allocation was too
  6544. ** larger (that is, because the requested allocation was larger than the
  6545. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6546. ** slots were available.
  6547. ** </dd>)^
  6548. **
  6549. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6550. ** <dd>This parameter records the largest memory allocation request
  6551. ** handed to [scratch memory allocator]. Only the value returned in the
  6552. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6553. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6554. **
  6555. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6556. ** <dd>This parameter records the deepest parser stack. It is only
  6557. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6558. ** </dl>
  6559. **
  6560. ** New status parameters may be added from time to time.
  6561. */
  6562. #define SQLITE_STATUS_MEMORY_USED 0
  6563. #define SQLITE_STATUS_PAGECACHE_USED 1
  6564. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6565. #define SQLITE_STATUS_SCRATCH_USED 3
  6566. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6567. #define SQLITE_STATUS_MALLOC_SIZE 5
  6568. #define SQLITE_STATUS_PARSER_STACK 6
  6569. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6570. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6571. #define SQLITE_STATUS_MALLOC_COUNT 9
  6572. /*
  6573. ** CAPI3REF: Database Connection Status
  6574. ** METHOD: sqlite3
  6575. **
  6576. ** ^This interface is used to retrieve runtime status information
  6577. ** about a single [database connection]. ^The first argument is the
  6578. ** database connection object to be interrogated. ^The second argument
  6579. ** is an integer constant, taken from the set of
  6580. ** [SQLITE_DBSTATUS options], that
  6581. ** determines the parameter to interrogate. The set of
  6582. ** [SQLITE_DBSTATUS options] is likely
  6583. ** to grow in future releases of SQLite.
  6584. **
  6585. ** ^The current value of the requested parameter is written into *pCur
  6586. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6587. ** the resetFlg is true, then the highest instantaneous value is
  6588. ** reset back down to the current value.
  6589. **
  6590. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6591. ** non-zero [error code] on failure.
  6592. **
  6593. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6594. */
  6595. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6596. /*
  6597. ** CAPI3REF: Status Parameters for database connections
  6598. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6599. **
  6600. ** These constants are the available integer "verbs" that can be passed as
  6601. ** the second argument to the [sqlite3_db_status()] interface.
  6602. **
  6603. ** New verbs may be added in future releases of SQLite. Existing verbs
  6604. ** might be discontinued. Applications should check the return code from
  6605. ** [sqlite3_db_status()] to make sure that the call worked.
  6606. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6607. ** if a discontinued or unsupported verb is invoked.
  6608. **
  6609. ** <dl>
  6610. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6611. ** <dd>This parameter returns the number of lookaside memory slots currently
  6612. ** checked out.</dd>)^
  6613. **
  6614. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6615. ** <dd>This parameter returns the number malloc attempts that were
  6616. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6617. ** the current value is always zero.)^
  6618. **
  6619. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6620. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6621. ** <dd>This parameter returns the number malloc attempts that might have
  6622. ** been satisfied using lookaside memory but failed due to the amount of
  6623. ** memory requested being larger than the lookaside slot size.
  6624. ** Only the high-water value is meaningful;
  6625. ** the current value is always zero.)^
  6626. **
  6627. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6628. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6629. ** <dd>This parameter returns the number malloc attempts that might have
  6630. ** been satisfied using lookaside memory but failed due to all lookaside
  6631. ** memory already being in use.
  6632. ** Only the high-water value is meaningful;
  6633. ** the current value is always zero.)^
  6634. **
  6635. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6636. ** <dd>This parameter returns the approximate number of bytes of heap
  6637. ** memory used by all pager caches associated with the database connection.)^
  6638. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6639. **
  6640. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6641. ** <dd>This parameter returns the approximate number of bytes of heap
  6642. ** memory used to store the schema for all databases associated
  6643. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6644. ** ^The full amount of memory used by the schemas is reported, even if the
  6645. ** schema memory is shared with other database connections due to
  6646. ** [shared cache mode] being enabled.
  6647. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6648. **
  6649. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6650. ** <dd>This parameter returns the approximate number of bytes of heap
  6651. ** and lookaside memory used by all prepared statements associated with
  6652. ** the database connection.)^
  6653. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6654. ** </dd>
  6655. **
  6656. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6657. ** <dd>This parameter returns the number of pager cache hits that have
  6658. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6659. ** is always 0.
  6660. ** </dd>
  6661. **
  6662. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6663. ** <dd>This parameter returns the number of pager cache misses that have
  6664. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6665. ** is always 0.
  6666. ** </dd>
  6667. **
  6668. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6669. ** <dd>This parameter returns the number of dirty cache entries that have
  6670. ** been written to disk. Specifically, the number of pages written to the
  6671. ** wal file in wal mode databases, or the number of pages written to the
  6672. ** database file in rollback mode databases. Any pages written as part of
  6673. ** transaction rollback or database recovery operations are not included.
  6674. ** If an IO or other error occurs while writing a page to disk, the effect
  6675. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6676. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6677. ** </dd>
  6678. **
  6679. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6680. ** <dd>This parameter returns zero for the current value if and only if
  6681. ** all foreign key constraints (deferred or immediate) have been
  6682. ** resolved.)^ ^The highwater mark is always 0.
  6683. ** </dd>
  6684. ** </dl>
  6685. */
  6686. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6687. #define SQLITE_DBSTATUS_CACHE_USED 1
  6688. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6689. #define SQLITE_DBSTATUS_STMT_USED 3
  6690. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6691. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6692. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6693. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6694. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6695. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6696. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6697. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6698. /*
  6699. ** CAPI3REF: Prepared Statement Status
  6700. ** METHOD: sqlite3_stmt
  6701. **
  6702. ** ^(Each prepared statement maintains various
  6703. ** [SQLITE_STMTSTATUS counters] that measure the number
  6704. ** of times it has performed specific operations.)^ These counters can
  6705. ** be used to monitor the performance characteristics of the prepared
  6706. ** statements. For example, if the number of table steps greatly exceeds
  6707. ** the number of table searches or result rows, that would tend to indicate
  6708. ** that the prepared statement is using a full table scan rather than
  6709. ** an index.
  6710. **
  6711. ** ^(This interface is used to retrieve and reset counter values from
  6712. ** a [prepared statement]. The first argument is the prepared statement
  6713. ** object to be interrogated. The second argument
  6714. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6715. ** to be interrogated.)^
  6716. ** ^The current value of the requested counter is returned.
  6717. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6718. ** interface call returns.
  6719. **
  6720. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6721. */
  6722. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6723. /*
  6724. ** CAPI3REF: Status Parameters for prepared statements
  6725. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6726. **
  6727. ** These preprocessor macros define integer codes that name counter
  6728. ** values associated with the [sqlite3_stmt_status()] interface.
  6729. ** The meanings of the various counters are as follows:
  6730. **
  6731. ** <dl>
  6732. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6733. ** <dd>^This is the number of times that SQLite has stepped forward in
  6734. ** a table as part of a full table scan. Large numbers for this counter
  6735. ** may indicate opportunities for performance improvement through
  6736. ** careful use of indices.</dd>
  6737. **
  6738. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6739. ** <dd>^This is the number of sort operations that have occurred.
  6740. ** A non-zero value in this counter may indicate an opportunity to
  6741. ** improvement performance through careful use of indices.</dd>
  6742. **
  6743. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6744. ** <dd>^This is the number of rows inserted into transient indices that
  6745. ** were created automatically in order to help joins run faster.
  6746. ** A non-zero value in this counter may indicate an opportunity to
  6747. ** improvement performance by adding permanent indices that do not
  6748. ** need to be reinitialized each time the statement is run.</dd>
  6749. **
  6750. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6751. ** <dd>^This is the number of virtual machine operations executed
  6752. ** by the prepared statement if that number is less than or equal
  6753. ** to 2147483647. The number of virtual machine operations can be
  6754. ** used as a proxy for the total work done by the prepared statement.
  6755. ** If the number of virtual machine operations exceeds 2147483647
  6756. ** then the value returned by this statement status code is undefined.
  6757. ** </dd>
  6758. ** </dl>
  6759. */
  6760. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6761. #define SQLITE_STMTSTATUS_SORT 2
  6762. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6763. #define SQLITE_STMTSTATUS_VM_STEP 4
  6764. /*
  6765. ** CAPI3REF: Custom Page Cache Object
  6766. **
  6767. ** The sqlite3_pcache type is opaque. It is implemented by
  6768. ** the pluggable module. The SQLite core has no knowledge of
  6769. ** its size or internal structure and never deals with the
  6770. ** sqlite3_pcache object except by holding and passing pointers
  6771. ** to the object.
  6772. **
  6773. ** See [sqlite3_pcache_methods2] for additional information.
  6774. */
  6775. typedef struct sqlite3_pcache sqlite3_pcache;
  6776. /*
  6777. ** CAPI3REF: Custom Page Cache Object
  6778. **
  6779. ** The sqlite3_pcache_page object represents a single page in the
  6780. ** page cache. The page cache will allocate instances of this
  6781. ** object. Various methods of the page cache use pointers to instances
  6782. ** of this object as parameters or as their return value.
  6783. **
  6784. ** See [sqlite3_pcache_methods2] for additional information.
  6785. */
  6786. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6787. struct sqlite3_pcache_page {
  6788. void *pBuf; /* The content of the page */
  6789. void *pExtra; /* Extra information associated with the page */
  6790. };
  6791. /*
  6792. ** CAPI3REF: Application Defined Page Cache.
  6793. ** KEYWORDS: {page cache}
  6794. **
  6795. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6796. ** register an alternative page cache implementation by passing in an
  6797. ** instance of the sqlite3_pcache_methods2 structure.)^
  6798. ** In many applications, most of the heap memory allocated by
  6799. ** SQLite is used for the page cache.
  6800. ** By implementing a
  6801. ** custom page cache using this API, an application can better control
  6802. ** the amount of memory consumed by SQLite, the way in which
  6803. ** that memory is allocated and released, and the policies used to
  6804. ** determine exactly which parts of a database file are cached and for
  6805. ** how long.
  6806. **
  6807. ** The alternative page cache mechanism is an
  6808. ** extreme measure that is only needed by the most demanding applications.
  6809. ** The built-in page cache is recommended for most uses.
  6810. **
  6811. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6812. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6813. ** the application may discard the parameter after the call to
  6814. ** [sqlite3_config()] returns.)^
  6815. **
  6816. ** [[the xInit() page cache method]]
  6817. ** ^(The xInit() method is called once for each effective
  6818. ** call to [sqlite3_initialize()])^
  6819. ** (usually only once during the lifetime of the process). ^(The xInit()
  6820. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6821. ** The intent of the xInit() method is to set up global data structures
  6822. ** required by the custom page cache implementation.
  6823. ** ^(If the xInit() method is NULL, then the
  6824. ** built-in default page cache is used instead of the application defined
  6825. ** page cache.)^
  6826. **
  6827. ** [[the xShutdown() page cache method]]
  6828. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6829. ** It can be used to clean up
  6830. ** any outstanding resources before process shutdown, if required.
  6831. ** ^The xShutdown() method may be NULL.
  6832. **
  6833. ** ^SQLite automatically serializes calls to the xInit method,
  6834. ** so the xInit method need not be threadsafe. ^The
  6835. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6836. ** not need to be threadsafe either. All other methods must be threadsafe
  6837. ** in multithreaded applications.
  6838. **
  6839. ** ^SQLite will never invoke xInit() more than once without an intervening
  6840. ** call to xShutdown().
  6841. **
  6842. ** [[the xCreate() page cache methods]]
  6843. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6844. ** SQLite will typically create one cache instance for each open database file,
  6845. ** though this is not guaranteed. ^The
  6846. ** first parameter, szPage, is the size in bytes of the pages that must
  6847. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6848. ** second parameter szExtra is a number of bytes of extra storage
  6849. ** associated with each page cache entry. ^The szExtra parameter will
  6850. ** a number less than 250. SQLite will use the
  6851. ** extra szExtra bytes on each page to store metadata about the underlying
  6852. ** database page on disk. The value passed into szExtra depends
  6853. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6854. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6855. ** created will be used to cache database pages of a file stored on disk, or
  6856. ** false if it is used for an in-memory database. The cache implementation
  6857. ** does not have to do anything special based with the value of bPurgeable;
  6858. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6859. ** never invoke xUnpin() except to deliberately delete a page.
  6860. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6861. ** false will always have the "discard" flag set to true.
  6862. ** ^Hence, a cache created with bPurgeable false will
  6863. ** never contain any unpinned pages.
  6864. **
  6865. ** [[the xCachesize() page cache method]]
  6866. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6867. ** suggested maximum cache-size (number of pages stored by) the cache
  6868. ** instance passed as the first argument. This is the value configured using
  6869. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6870. ** parameter, the implementation is not required to do anything with this
  6871. ** value; it is advisory only.
  6872. **
  6873. ** [[the xPagecount() page cache methods]]
  6874. ** The xPagecount() method must return the number of pages currently
  6875. ** stored in the cache, both pinned and unpinned.
  6876. **
  6877. ** [[the xFetch() page cache methods]]
  6878. ** The xFetch() method locates a page in the cache and returns a pointer to
  6879. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6880. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6881. ** pointer to a buffer of szPage bytes used to store the content of a
  6882. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6883. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6884. ** for each entry in the page cache.
  6885. **
  6886. ** The page to be fetched is determined by the key. ^The minimum key value
  6887. ** is 1. After it has been retrieved using xFetch, the page is considered
  6888. ** to be "pinned".
  6889. **
  6890. ** If the requested page is already in the page cache, then the page cache
  6891. ** implementation must return a pointer to the page buffer with its content
  6892. ** intact. If the requested page is not already in the cache, then the
  6893. ** cache implementation should use the value of the createFlag
  6894. ** parameter to help it determined what action to take:
  6895. **
  6896. ** <table border=1 width=85% align=center>
  6897. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6898. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6899. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6900. ** Otherwise return NULL.
  6901. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6902. ** NULL if allocating a new page is effectively impossible.
  6903. ** </table>
  6904. **
  6905. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6906. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6907. ** failed.)^ In between the to xFetch() calls, SQLite may
  6908. ** attempt to unpin one or more cache pages by spilling the content of
  6909. ** pinned pages to disk and synching the operating system disk cache.
  6910. **
  6911. ** [[the xUnpin() page cache method]]
  6912. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6913. ** as its second argument. If the third parameter, discard, is non-zero,
  6914. ** then the page must be evicted from the cache.
  6915. ** ^If the discard parameter is
  6916. ** zero, then the page may be discarded or retained at the discretion of
  6917. ** page cache implementation. ^The page cache implementation
  6918. ** may choose to evict unpinned pages at any time.
  6919. **
  6920. ** The cache must not perform any reference counting. A single
  6921. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6922. ** to xFetch().
  6923. **
  6924. ** [[the xRekey() page cache methods]]
  6925. ** The xRekey() method is used to change the key value associated with the
  6926. ** page passed as the second argument. If the cache
  6927. ** previously contains an entry associated with newKey, it must be
  6928. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6929. ** to be pinned.
  6930. **
  6931. ** When SQLite calls the xTruncate() method, the cache must discard all
  6932. ** existing cache entries with page numbers (keys) greater than or equal
  6933. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6934. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6935. ** they can be safely discarded.
  6936. **
  6937. ** [[the xDestroy() page cache method]]
  6938. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6939. ** All resources associated with the specified cache should be freed. ^After
  6940. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6941. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6942. ** functions.
  6943. **
  6944. ** [[the xShrink() page cache method]]
  6945. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6946. ** free up as much of heap memory as possible. The page cache implementation
  6947. ** is not obligated to free any memory, but well-behaved implementations should
  6948. ** do their best.
  6949. */
  6950. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6951. struct sqlite3_pcache_methods2 {
  6952. int iVersion;
  6953. void *pArg;
  6954. int (*xInit)(void*);
  6955. void (*xShutdown)(void*);
  6956. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6957. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6958. int (*xPagecount)(sqlite3_pcache*);
  6959. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6960. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6961. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6962. unsigned oldKey, unsigned newKey);
  6963. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6964. void (*xDestroy)(sqlite3_pcache*);
  6965. void (*xShrink)(sqlite3_pcache*);
  6966. };
  6967. /*
  6968. ** This is the obsolete pcache_methods object that has now been replaced
  6969. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6970. ** retained in the header file for backwards compatibility only.
  6971. */
  6972. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6973. struct sqlite3_pcache_methods {
  6974. void *pArg;
  6975. int (*xInit)(void*);
  6976. void (*xShutdown)(void*);
  6977. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6978. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6979. int (*xPagecount)(sqlite3_pcache*);
  6980. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6981. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6982. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6983. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6984. void (*xDestroy)(sqlite3_pcache*);
  6985. };
  6986. /*
  6987. ** CAPI3REF: Online Backup Object
  6988. **
  6989. ** The sqlite3_backup object records state information about an ongoing
  6990. ** online backup operation. ^The sqlite3_backup object is created by
  6991. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6992. ** [sqlite3_backup_finish()].
  6993. **
  6994. ** See Also: [Using the SQLite Online Backup API]
  6995. */
  6996. typedef struct sqlite3_backup sqlite3_backup;
  6997. /*
  6998. ** CAPI3REF: Online Backup API.
  6999. **
  7000. ** The backup API copies the content of one database into another.
  7001. ** It is useful either for creating backups of databases or
  7002. ** for copying in-memory databases to or from persistent files.
  7003. **
  7004. ** See Also: [Using the SQLite Online Backup API]
  7005. **
  7006. ** ^SQLite holds a write transaction open on the destination database file
  7007. ** for the duration of the backup operation.
  7008. ** ^The source database is read-locked only while it is being read;
  7009. ** it is not locked continuously for the entire backup operation.
  7010. ** ^Thus, the backup may be performed on a live source database without
  7011. ** preventing other database connections from
  7012. ** reading or writing to the source database while the backup is underway.
  7013. **
  7014. ** ^(To perform a backup operation:
  7015. ** <ol>
  7016. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  7017. ** backup,
  7018. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  7019. ** the data between the two databases, and finally
  7020. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  7021. ** associated with the backup operation.
  7022. ** </ol>)^
  7023. ** There should be exactly one call to sqlite3_backup_finish() for each
  7024. ** successful call to sqlite3_backup_init().
  7025. **
  7026. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  7027. **
  7028. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  7029. ** [database connection] associated with the destination database
  7030. ** and the database name, respectively.
  7031. ** ^The database name is "main" for the main database, "temp" for the
  7032. ** temporary database, or the name specified after the AS keyword in
  7033. ** an [ATTACH] statement for an attached database.
  7034. ** ^The S and M arguments passed to
  7035. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  7036. ** and database name of the source database, respectively.
  7037. ** ^The source and destination [database connections] (parameters S and D)
  7038. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  7039. ** an error.
  7040. **
  7041. ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if
  7042. ** there is already a read or read-write transaction open on the
  7043. ** destination database.
  7044. **
  7045. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  7046. ** returned and an error code and error message are stored in the
  7047. ** destination [database connection] D.
  7048. ** ^The error code and message for the failed call to sqlite3_backup_init()
  7049. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  7050. ** [sqlite3_errmsg16()] functions.
  7051. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  7052. ** [sqlite3_backup] object.
  7053. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  7054. ** sqlite3_backup_finish() functions to perform the specified backup
  7055. ** operation.
  7056. **
  7057. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  7058. **
  7059. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  7060. ** the source and destination databases specified by [sqlite3_backup] object B.
  7061. ** ^If N is negative, all remaining source pages are copied.
  7062. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  7063. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  7064. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  7065. ** from source to destination, then it returns [SQLITE_DONE].
  7066. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  7067. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  7068. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  7069. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  7070. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  7071. **
  7072. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  7073. ** <ol>
  7074. ** <li> the destination database was opened read-only, or
  7075. ** <li> the destination database is using write-ahead-log journaling
  7076. ** and the destination and source page sizes differ, or
  7077. ** <li> the destination database is an in-memory database and the
  7078. ** destination and source page sizes differ.
  7079. ** </ol>)^
  7080. **
  7081. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  7082. ** the [sqlite3_busy_handler | busy-handler function]
  7083. ** is invoked (if one is specified). ^If the
  7084. ** busy-handler returns non-zero before the lock is available, then
  7085. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  7086. ** sqlite3_backup_step() can be retried later. ^If the source
  7087. ** [database connection]
  7088. ** is being used to write to the source database when sqlite3_backup_step()
  7089. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  7090. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  7091. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  7092. ** [SQLITE_READONLY] is returned, then
  7093. ** there is no point in retrying the call to sqlite3_backup_step(). These
  7094. ** errors are considered fatal.)^ The application must accept
  7095. ** that the backup operation has failed and pass the backup operation handle
  7096. ** to the sqlite3_backup_finish() to release associated resources.
  7097. **
  7098. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  7099. ** on the destination file. ^The exclusive lock is not released until either
  7100. ** sqlite3_backup_finish() is called or the backup operation is complete
  7101. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  7102. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  7103. ** lasts for the duration of the sqlite3_backup_step() call.
  7104. ** ^Because the source database is not locked between calls to
  7105. ** sqlite3_backup_step(), the source database may be modified mid-way
  7106. ** through the backup process. ^If the source database is modified by an
  7107. ** external process or via a database connection other than the one being
  7108. ** used by the backup operation, then the backup will be automatically
  7109. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  7110. ** database is modified by the using the same database connection as is used
  7111. ** by the backup operation, then the backup database is automatically
  7112. ** updated at the same time.
  7113. **
  7114. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  7115. **
  7116. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  7117. ** application wishes to abandon the backup operation, the application
  7118. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  7119. ** ^The sqlite3_backup_finish() interfaces releases all
  7120. ** resources associated with the [sqlite3_backup] object.
  7121. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  7122. ** active write-transaction on the destination database is rolled back.
  7123. ** The [sqlite3_backup] object is invalid
  7124. ** and may not be used following a call to sqlite3_backup_finish().
  7125. **
  7126. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  7127. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  7128. ** sqlite3_backup_step() completed.
  7129. ** ^If an out-of-memory condition or IO error occurred during any prior
  7130. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  7131. ** sqlite3_backup_finish() returns the corresponding [error code].
  7132. **
  7133. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  7134. ** is not a permanent error and does not affect the return value of
  7135. ** sqlite3_backup_finish().
  7136. **
  7137. ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
  7138. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  7139. **
  7140. ** ^The sqlite3_backup_remaining() routine returns the number of pages still
  7141. ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
  7142. ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
  7143. ** in the source database at the conclusion of the most recent
  7144. ** sqlite3_backup_step().
  7145. ** ^(The values returned by these functions are only updated by
  7146. ** sqlite3_backup_step(). If the source database is modified in a way that
  7147. ** changes the size of the source database or the number of pages remaining,
  7148. ** those changes are not reflected in the output of sqlite3_backup_pagecount()
  7149. ** and sqlite3_backup_remaining() until after the next
  7150. ** sqlite3_backup_step().)^
  7151. **
  7152. ** <b>Concurrent Usage of Database Handles</b>
  7153. **
  7154. ** ^The source [database connection] may be used by the application for other
  7155. ** purposes while a backup operation is underway or being initialized.
  7156. ** ^If SQLite is compiled and configured to support threadsafe database
  7157. ** connections, then the source database connection may be used concurrently
  7158. ** from within other threads.
  7159. **
  7160. ** However, the application must guarantee that the destination
  7161. ** [database connection] is not passed to any other API (by any thread) after
  7162. ** sqlite3_backup_init() is called and before the corresponding call to
  7163. ** sqlite3_backup_finish(). SQLite does not currently check to see
  7164. ** if the application incorrectly accesses the destination [database connection]
  7165. ** and so no error code is reported, but the operations may malfunction
  7166. ** nevertheless. Use of the destination database connection while a
  7167. ** backup is in progress might also also cause a mutex deadlock.
  7168. **
  7169. ** If running in [shared cache mode], the application must
  7170. ** guarantee that the shared cache used by the destination database
  7171. ** is not accessed while the backup is running. In practice this means
  7172. ** that the application must guarantee that the disk file being
  7173. ** backed up to is not accessed by any connection within the process,
  7174. ** not just the specific connection that was passed to sqlite3_backup_init().
  7175. **
  7176. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  7177. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  7178. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  7179. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  7180. ** same time as another thread is invoking sqlite3_backup_step() it is
  7181. ** possible that they return invalid values.
  7182. */
  7183. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  7184. sqlite3 *pDest, /* Destination database handle */
  7185. const char *zDestName, /* Destination database name */
  7186. sqlite3 *pSource, /* Source database handle */
  7187. const char *zSourceName /* Source database name */
  7188. );
  7189. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
  7190. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
  7191. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
  7192. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
  7193. /*
  7194. ** CAPI3REF: Unlock Notification
  7195. ** METHOD: sqlite3
  7196. **
  7197. ** ^When running in shared-cache mode, a database operation may fail with
  7198. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  7199. ** individual tables within the shared-cache cannot be obtained. See
  7200. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  7201. ** ^This API may be used to register a callback that SQLite will invoke
  7202. ** when the connection currently holding the required lock relinquishes it.
  7203. ** ^This API is only available if the library was compiled with the
  7204. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  7205. **
  7206. ** See Also: [Using the SQLite Unlock Notification Feature].
  7207. **
  7208. ** ^Shared-cache locks are released when a database connection concludes
  7209. ** its current transaction, either by committing it or rolling it back.
  7210. **
  7211. ** ^When a connection (known as the blocked connection) fails to obtain a
  7212. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  7213. ** identity of the database connection (the blocking connection) that
  7214. ** has locked the required resource is stored internally. ^After an
  7215. ** application receives an SQLITE_LOCKED error, it may call the
  7216. ** sqlite3_unlock_notify() method with the blocked connection handle as
  7217. ** the first argument to register for a callback that will be invoked
  7218. ** when the blocking connections current transaction is concluded. ^The
  7219. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  7220. ** call that concludes the blocking connections transaction.
  7221. **
  7222. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  7223. ** there is a chance that the blocking connection will have already
  7224. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  7225. ** If this happens, then the specified callback is invoked immediately,
  7226. ** from within the call to sqlite3_unlock_notify().)^
  7227. **
  7228. ** ^If the blocked connection is attempting to obtain a write-lock on a
  7229. ** shared-cache table, and more than one other connection currently holds
  7230. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  7231. ** the other connections to use as the blocking connection.
  7232. **
  7233. ** ^(There may be at most one unlock-notify callback registered by a
  7234. ** blocked connection. If sqlite3_unlock_notify() is called when the
  7235. ** blocked connection already has a registered unlock-notify callback,
  7236. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  7237. ** called with a NULL pointer as its second argument, then any existing
  7238. ** unlock-notify callback is canceled. ^The blocked connections
  7239. ** unlock-notify callback may also be canceled by closing the blocked
  7240. ** connection using [sqlite3_close()].
  7241. **
  7242. ** The unlock-notify callback is not reentrant. If an application invokes
  7243. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  7244. ** crash or deadlock may be the result.
  7245. **
  7246. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  7247. ** returns SQLITE_OK.
  7248. **
  7249. ** <b>Callback Invocation Details</b>
  7250. **
  7251. ** When an unlock-notify callback is registered, the application provides a
  7252. ** single void* pointer that is passed to the callback when it is invoked.
  7253. ** However, the signature of the callback function allows SQLite to pass
  7254. ** it an array of void* context pointers. The first argument passed to
  7255. ** an unlock-notify callback is a pointer to an array of void* pointers,
  7256. ** and the second is the number of entries in the array.
  7257. **
  7258. ** When a blocking connections transaction is concluded, there may be
  7259. ** more than one blocked connection that has registered for an unlock-notify
  7260. ** callback. ^If two or more such blocked connections have specified the
  7261. ** same callback function, then instead of invoking the callback function
  7262. ** multiple times, it is invoked once with the set of void* context pointers
  7263. ** specified by the blocked connections bundled together into an array.
  7264. ** This gives the application an opportunity to prioritize any actions
  7265. ** related to the set of unblocked database connections.
  7266. **
  7267. ** <b>Deadlock Detection</b>
  7268. **
  7269. ** Assuming that after registering for an unlock-notify callback a
  7270. ** database waits for the callback to be issued before taking any further
  7271. ** action (a reasonable assumption), then using this API may cause the
  7272. ** application to deadlock. For example, if connection X is waiting for
  7273. ** connection Y's transaction to be concluded, and similarly connection
  7274. ** Y is waiting on connection X's transaction, then neither connection
  7275. ** will proceed and the system may remain deadlocked indefinitely.
  7276. **
  7277. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7278. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7279. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7280. ** unlock-notify callback is registered. The system is said to be in
  7281. ** a deadlocked state if connection A has registered for an unlock-notify
  7282. ** callback on the conclusion of connection B's transaction, and connection
  7283. ** B has itself registered for an unlock-notify callback when connection
  7284. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7285. ** the system is also considered to be deadlocked if connection B has
  7286. ** registered for an unlock-notify callback on the conclusion of connection
  7287. ** C's transaction, where connection C is waiting on connection A. ^Any
  7288. ** number of levels of indirection are allowed.
  7289. **
  7290. ** <b>The "DROP TABLE" Exception</b>
  7291. **
  7292. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7293. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7294. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7295. ** SQLite checks if there are any currently executing SELECT statements
  7296. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7297. ** returned. In this case there is no "blocking connection", so invoking
  7298. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7299. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7300. ** or "DROP INDEX" query, an infinite loop might be the result.
  7301. **
  7302. ** One way around this problem is to check the extended error code returned
  7303. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7304. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7305. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7306. ** SQLITE_LOCKED.)^
  7307. */
  7308. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  7309. sqlite3 *pBlocked, /* Waiting connection */
  7310. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7311. void *pNotifyArg /* Argument to pass to xNotify */
  7312. );
  7313. /*
  7314. ** CAPI3REF: String Comparison
  7315. **
  7316. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7317. ** and extensions to compare the contents of two buffers containing UTF-8
  7318. ** strings in a case-independent fashion, using the same definition of "case
  7319. ** independence" that SQLite uses internally when comparing identifiers.
  7320. */
  7321. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
  7322. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
  7323. /*
  7324. ** CAPI3REF: String Globbing
  7325. *
  7326. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  7327. ** the glob pattern P, and it returns non-zero if string X does not match
  7328. ** the glob pattern P. ^The definition of glob pattern matching used in
  7329. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7330. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  7331. ** sensitive.
  7332. **
  7333. ** Note that this routine returns zero on a match and non-zero if the strings
  7334. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7335. */
  7336. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
  7337. /*
  7338. ** CAPI3REF: Error Logging Interface
  7339. **
  7340. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7341. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7342. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7343. ** used with [sqlite3_snprintf()] to generate the final output string.
  7344. **
  7345. ** The sqlite3_log() interface is intended for use by extensions such as
  7346. ** virtual tables, collating functions, and SQL functions. While there is
  7347. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7348. ** is considered bad form.
  7349. **
  7350. ** The zFormat string must not be NULL.
  7351. **
  7352. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7353. ** will not use dynamically allocated memory. The log message is stored in
  7354. ** a fixed-length buffer on the stack. If the log message is longer than
  7355. ** a few hundred characters, it will be truncated to the length of the
  7356. ** buffer.
  7357. */
  7358. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
  7359. /*
  7360. ** CAPI3REF: Write-Ahead Log Commit Hook
  7361. ** METHOD: sqlite3
  7362. **
  7363. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7364. ** is invoked each time data is committed to a database in wal mode.
  7365. **
  7366. ** ^(The callback is invoked by SQLite after the commit has taken place and
  7367. ** the associated write-lock on the database released)^, so the implementation
  7368. ** may read, write or [checkpoint] the database as required.
  7369. **
  7370. ** ^The first parameter passed to the callback function when it is invoked
  7371. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7372. ** registering the callback. ^The second is a copy of the database handle.
  7373. ** ^The third parameter is the name of the database that was written to -
  7374. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7375. ** is the number of pages currently in the write-ahead log file,
  7376. ** including those that were just committed.
  7377. **
  7378. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7379. ** code is returned, that error will propagate back up through the
  7380. ** SQLite code base to cause the statement that provoked the callback
  7381. ** to report an error, though the commit will have still occurred. If the
  7382. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7383. ** that does not correspond to any valid SQLite error code, the results
  7384. ** are undefined.
  7385. **
  7386. ** A single database handle may have at most a single write-ahead log callback
  7387. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7388. ** previously registered write-ahead log callback. ^Note that the
  7389. ** [sqlite3_wal_autocheckpoint()] interface and the
  7390. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7391. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7392. */
  7393. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  7394. sqlite3*,
  7395. int(*)(void *,sqlite3*,const char*,int),
  7396. void*
  7397. );
  7398. /*
  7399. ** CAPI3REF: Configure an auto-checkpoint
  7400. ** METHOD: sqlite3
  7401. **
  7402. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7403. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7404. ** to automatically [checkpoint]
  7405. ** after committing a transaction if there are N or
  7406. ** more frames in the [write-ahead log] file. ^Passing zero or
  7407. ** a negative value as the nFrame parameter disables automatic
  7408. ** checkpoints entirely.
  7409. **
  7410. ** ^The callback registered by this function replaces any existing callback
  7411. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7412. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7413. ** configured by this function.
  7414. **
  7415. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7416. ** from SQL.
  7417. **
  7418. ** ^Checkpoints initiated by this mechanism are
  7419. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7420. **
  7421. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7422. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7423. ** pages. The use of this interface
  7424. ** is only necessary if the default setting is found to be suboptimal
  7425. ** for a particular application.
  7426. */
  7427. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7428. /*
  7429. ** CAPI3REF: Checkpoint a database
  7430. ** METHOD: sqlite3
  7431. **
  7432. ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
  7433. ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
  7434. **
  7435. ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
  7436. ** [write-ahead log] for database X on [database connection] D to be
  7437. ** transferred into the database file and for the write-ahead log to
  7438. ** be reset. See the [checkpointing] documentation for addition
  7439. ** information.
  7440. **
  7441. ** This interface used to be the only way to cause a checkpoint to
  7442. ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
  7443. ** interface was added. This interface is retained for backwards
  7444. ** compatibility and as a convenience for applications that need to manually
  7445. ** start a callback but which do not need the full power (and corresponding
  7446. ** complication) of [sqlite3_wal_checkpoint_v2()].
  7447. */
  7448. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7449. /*
  7450. ** CAPI3REF: Checkpoint a database
  7451. ** METHOD: sqlite3
  7452. **
  7453. ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
  7454. ** operation on database X of [database connection] D in mode M. Status
  7455. ** information is written back into integers pointed to by L and C.)^
  7456. ** ^(The M parameter must be a valid [checkpoint mode]:)^
  7457. **
  7458. ** <dl>
  7459. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7460. ** ^Checkpoint as many frames as possible without waiting for any database
  7461. ** readers or writers to finish, then sync the database file if all frames
  7462. ** in the log were checkpointed. ^The [busy-handler callback]
  7463. ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
  7464. ** ^On the other hand, passive mode might leave the checkpoint unfinished
  7465. ** if there are concurrent readers or writers.
  7466. **
  7467. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7468. ** ^This mode blocks (it invokes the
  7469. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7470. ** database writer and all readers are reading from the most recent database
  7471. ** snapshot. ^It then checkpoints all frames in the log file and syncs the
  7472. ** database file. ^This mode blocks new database writers while it is pending,
  7473. ** but new database readers are allowed to continue unimpeded.
  7474. **
  7475. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7476. ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
  7477. ** that after checkpointing the log file it blocks (calls the
  7478. ** [busy-handler callback])
  7479. ** until all readers are reading from the database file only. ^This ensures
  7480. ** that the next writer will restart the log file from the beginning.
  7481. ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
  7482. ** database writer attempts while it is pending, but does not impede readers.
  7483. **
  7484. ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
  7485. ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
  7486. ** addition that it also truncates the log file to zero bytes just prior
  7487. ** to a successful return.
  7488. ** </dl>
  7489. **
  7490. ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7491. ** the log file or to -1 if the checkpoint could not run because
  7492. ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
  7493. ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
  7494. ** log file (including any that were already checkpointed before the function
  7495. ** was called) or to -1 if the checkpoint could not run due to an error or
  7496. ** because the database is not in WAL mode. ^Note that upon successful
  7497. ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
  7498. ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
  7499. **
  7500. ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
  7501. ** any other process is running a checkpoint operation at the same time, the
  7502. ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
  7503. ** busy-handler configured, it will not be invoked in this case.
  7504. **
  7505. ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
  7506. ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
  7507. ** obtained immediately, and a busy-handler is configured, it is invoked and
  7508. ** the writer lock retried until either the busy-handler returns 0 or the lock
  7509. ** is successfully obtained. ^The busy-handler is also invoked while waiting for
  7510. ** database readers as described above. ^If the busy-handler returns 0 before
  7511. ** the writer lock is obtained or while waiting for database readers, the
  7512. ** checkpoint operation proceeds from that point in the same way as
  7513. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7514. ** without blocking any further. ^SQLITE_BUSY is returned in this case.
  7515. **
  7516. ** ^If parameter zDb is NULL or points to a zero length string, then the
  7517. ** specified operation is attempted on all WAL databases [attached] to
  7518. ** [database connection] db. In this case the
  7519. ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
  7520. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7521. ** attached WAL databases, the operation is still attempted on any remaining
  7522. ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
  7523. ** error occurs while processing an attached database, processing is abandoned
  7524. ** and the error code is returned to the caller immediately. ^If no error
  7525. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7526. ** databases, SQLITE_OK is returned.
  7527. **
  7528. ** ^If database zDb is the name of an attached database that is not in WAL
  7529. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
  7530. ** zDb is not NULL (or a zero length string) and is not the name of any
  7531. ** attached database, SQLITE_ERROR is returned to the caller.
  7532. **
  7533. ** ^Unless it returns SQLITE_MISUSE,
  7534. ** the sqlite3_wal_checkpoint_v2() interface
  7535. ** sets the error information that is queried by
  7536. ** [sqlite3_errcode()] and [sqlite3_errmsg()].
  7537. **
  7538. ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
  7539. ** from SQL.
  7540. */
  7541. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  7542. sqlite3 *db, /* Database handle */
  7543. const char *zDb, /* Name of attached database (or NULL) */
  7544. int eMode, /* SQLITE_CHECKPOINT_* value */
  7545. int *pnLog, /* OUT: Size of WAL log in frames */
  7546. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7547. );
  7548. /*
  7549. ** CAPI3REF: Checkpoint Mode Values
  7550. ** KEYWORDS: {checkpoint mode}
  7551. **
  7552. ** These constants define all valid values for the "checkpoint mode" passed
  7553. ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
  7554. ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
  7555. ** meaning of each of these checkpoint modes.
  7556. */
  7557. #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
  7558. #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
  7559. #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
  7560. #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
  7561. /*
  7562. ** CAPI3REF: Virtual Table Interface Configuration
  7563. **
  7564. ** This function may be called by either the [xConnect] or [xCreate] method
  7565. ** of a [virtual table] implementation to configure
  7566. ** various facets of the virtual table interface.
  7567. **
  7568. ** If this interface is invoked outside the context of an xConnect or
  7569. ** xCreate virtual table method then the behavior is undefined.
  7570. **
  7571. ** At present, there is only one option that may be configured using
  7572. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7573. ** may be added in the future.
  7574. */
  7575. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
  7576. /*
  7577. ** CAPI3REF: Virtual Table Configuration Options
  7578. **
  7579. ** These macros define the various options to the
  7580. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7581. ** can use to customize and optimize their behavior.
  7582. **
  7583. ** <dl>
  7584. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7585. ** <dd>Calls of the form
  7586. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7587. ** where X is an integer. If X is zero, then the [virtual table] whose
  7588. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7589. ** support constraints. In this configuration (which is the default) if
  7590. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7591. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7592. ** specified as part of the users SQL statement, regardless of the actual
  7593. ** ON CONFLICT mode specified.
  7594. **
  7595. ** If X is non-zero, then the virtual table implementation guarantees
  7596. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7597. ** any modifications to internal or persistent data structures have been made.
  7598. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7599. ** is able to roll back a statement or database transaction, and abandon
  7600. ** or continue processing the current SQL statement as appropriate.
  7601. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7602. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7603. ** had been ABORT.
  7604. **
  7605. ** Virtual table implementations that are required to handle OR REPLACE
  7606. ** must do so within the [xUpdate] method. If a call to the
  7607. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7608. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7609. ** silently replace the appropriate rows within the xUpdate callback and
  7610. ** return SQLITE_OK. Or, if this is not possible, it may return
  7611. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7612. ** constraint handling.
  7613. ** </dl>
  7614. */
  7615. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7616. /*
  7617. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7618. **
  7619. ** This function may only be called from within a call to the [xUpdate] method
  7620. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7621. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7622. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7623. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7624. ** [virtual table].
  7625. */
  7626. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
  7627. /*
  7628. ** CAPI3REF: Conflict resolution modes
  7629. ** KEYWORDS: {conflict resolution mode}
  7630. **
  7631. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7632. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7633. ** is for the SQL statement being evaluated.
  7634. **
  7635. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7636. ** return value from the [sqlite3_set_authorizer()] callback and that
  7637. ** [SQLITE_ABORT] is also a [result code].
  7638. */
  7639. #define SQLITE_ROLLBACK 1
  7640. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7641. #define SQLITE_FAIL 3
  7642. /* #define SQLITE_ABORT 4 // Also an error code */
  7643. #define SQLITE_REPLACE 5
  7644. /*
  7645. ** CAPI3REF: Prepared Statement Scan Status Opcodes
  7646. ** KEYWORDS: {scanstatus options}
  7647. **
  7648. ** The following constants can be used for the T parameter to the
  7649. ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
  7650. ** different metric for sqlite3_stmt_scanstatus() to return.
  7651. **
  7652. ** When the value returned to V is a string, space to hold that string is
  7653. ** managed by the prepared statement S and will be automatically freed when
  7654. ** S is finalized.
  7655. **
  7656. ** <dl>
  7657. ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
  7658. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
  7659. ** set to the total number of times that the X-th loop has run.</dd>
  7660. **
  7661. ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
  7662. ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
  7663. ** to the total number of rows examined by all iterations of the X-th loop.</dd>
  7664. **
  7665. ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
  7666. ** <dd>^The "double" variable pointed to by the T parameter will be set to the
  7667. ** query planner's estimate for the average number of rows output from each
  7668. ** iteration of the X-th loop. If the query planner's estimates was accurate,
  7669. ** then this value will approximate the quotient NVISIT/NLOOP and the
  7670. ** product of this value for all prior loops with the same SELECTID will
  7671. ** be the NLOOP value for the current loop.
  7672. **
  7673. ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
  7674. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7675. ** to a zero-terminated UTF-8 string containing the name of the index or table
  7676. ** used for the X-th loop.
  7677. **
  7678. ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
  7679. ** <dd>^The "const char *" variable pointed to by the T parameter will be set
  7680. ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
  7681. ** description for the X-th loop.
  7682. **
  7683. ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
  7684. ** <dd>^The "int" variable pointed to by the T parameter will be set to the
  7685. ** "select-id" for the X-th loop. The select-id identifies which query or
  7686. ** subquery the loop is part of. The main query has a select-id of zero.
  7687. ** The select-id is the same value as is output in the first column
  7688. ** of an [EXPLAIN QUERY PLAN] query.
  7689. ** </dl>
  7690. */
  7691. #define SQLITE_SCANSTAT_NLOOP 0
  7692. #define SQLITE_SCANSTAT_NVISIT 1
  7693. #define SQLITE_SCANSTAT_EST 2
  7694. #define SQLITE_SCANSTAT_NAME 3
  7695. #define SQLITE_SCANSTAT_EXPLAIN 4
  7696. #define SQLITE_SCANSTAT_SELECTID 5
  7697. /*
  7698. ** CAPI3REF: Prepared Statement Scan Status
  7699. ** METHOD: sqlite3_stmt
  7700. **
  7701. ** This interface returns information about the predicted and measured
  7702. ** performance for pStmt. Advanced applications can use this
  7703. ** interface to compare the predicted and the measured performance and
  7704. ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
  7705. **
  7706. ** Since this interface is expected to be rarely used, it is only
  7707. ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
  7708. ** compile-time option.
  7709. **
  7710. ** The "iScanStatusOp" parameter determines which status information to return.
  7711. ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
  7712. ** of this interface is undefined.
  7713. ** ^The requested measurement is written into a variable pointed to by
  7714. ** the "pOut" parameter.
  7715. ** Parameter "idx" identifies the specific loop to retrieve statistics for.
  7716. ** Loops are numbered starting from zero. ^If idx is out of range - less than
  7717. ** zero or greater than or equal to the total number of loops used to implement
  7718. ** the statement - a non-zero value is returned and the variable that pOut
  7719. ** points to is unchanged.
  7720. **
  7721. ** ^Statistics might not be available for all loops in all statements. ^In cases
  7722. ** where there exist loops with no available statistics, this function behaves
  7723. ** as if the loop did not exist - it returns non-zero and leave the variable
  7724. ** that pOut points to unchanged.
  7725. **
  7726. ** See also: [sqlite3_stmt_scanstatus_reset()]
  7727. */
  7728. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  7729. sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
  7730. int idx, /* Index of loop to report on */
  7731. int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
  7732. void *pOut /* Result written here */
  7733. );
  7734. /*
  7735. ** CAPI3REF: Zero Scan-Status Counters
  7736. ** METHOD: sqlite3_stmt
  7737. **
  7738. ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
  7739. **
  7740. ** This API is only available if the library is built with pre-processor
  7741. ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
  7742. */
  7743. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
  7744. /*
  7745. ** Undo the hack that converts floating point types to integer for
  7746. ** builds on processors without floating point support.
  7747. */
  7748. #ifdef SQLITE_OMIT_FLOATING_POINT
  7749. # undef double
  7750. #endif
  7751. #if 0
  7752. } /* End of the 'extern "C"' block */
  7753. #endif
  7754. #endif /* _SQLITE3_H_ */
  7755. /*
  7756. ** 2010 August 30
  7757. **
  7758. ** The author disclaims copyright to this source code. In place of
  7759. ** a legal notice, here is a blessing:
  7760. **
  7761. ** May you do good and not evil.
  7762. ** May you find forgiveness for yourself and forgive others.
  7763. ** May you share freely, never taking more than you give.
  7764. **
  7765. *************************************************************************
  7766. */
  7767. #ifndef _SQLITE3RTREE_H_
  7768. #define _SQLITE3RTREE_H_
  7769. #if 0
  7770. extern "C" {
  7771. #endif
  7772. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7773. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  7774. /* The double-precision datatype used by RTree depends on the
  7775. ** SQLITE_RTREE_INT_ONLY compile-time option.
  7776. */
  7777. #ifdef SQLITE_RTREE_INT_ONLY
  7778. typedef sqlite3_int64 sqlite3_rtree_dbl;
  7779. #else
  7780. typedef double sqlite3_rtree_dbl;
  7781. #endif
  7782. /*
  7783. ** Register a geometry callback named zGeom that can be used as part of an
  7784. ** R-Tree geometry query as follows:
  7785. **
  7786. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7787. */
  7788. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  7789. sqlite3 *db,
  7790. const char *zGeom,
  7791. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  7792. void *pContext
  7793. );
  7794. /*
  7795. ** A pointer to a structure of the following type is passed as the first
  7796. ** argument to callbacks registered using rtree_geometry_callback().
  7797. */
  7798. struct sqlite3_rtree_geometry {
  7799. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7800. int nParam; /* Size of array aParam[] */
  7801. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  7802. void *pUser; /* Callback implementation user data */
  7803. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7804. };
  7805. /*
  7806. ** Register a 2nd-generation geometry callback named zScore that can be
  7807. ** used as part of an R-Tree geometry query as follows:
  7808. **
  7809. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  7810. */
  7811. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  7812. sqlite3 *db,
  7813. const char *zQueryFunc,
  7814. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  7815. void *pContext,
  7816. void (*xDestructor)(void*)
  7817. );
  7818. /*
  7819. ** A pointer to a structure of the following type is passed as the
  7820. ** argument to scored geometry callback registered using
  7821. ** sqlite3_rtree_query_callback().
  7822. **
  7823. ** Note that the first 5 fields of this structure are identical to
  7824. ** sqlite3_rtree_geometry. This structure is a subclass of
  7825. ** sqlite3_rtree_geometry.
  7826. */
  7827. struct sqlite3_rtree_query_info {
  7828. void *pContext; /* pContext from when function registered */
  7829. int nParam; /* Number of function parameters */
  7830. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  7831. void *pUser; /* callback can use this, if desired */
  7832. void (*xDelUser)(void*); /* function to free pUser */
  7833. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  7834. unsigned int *anQueue; /* Number of pending entries in the queue */
  7835. int nCoord; /* Number of coordinates */
  7836. int iLevel; /* Level of current node or entry */
  7837. int mxLevel; /* The largest iLevel value in the tree */
  7838. sqlite3_int64 iRowid; /* Rowid for current entry */
  7839. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  7840. int eParentWithin; /* Visibility of parent node */
  7841. int eWithin; /* OUT: Visiblity */
  7842. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  7843. /* The following fields are only available in 3.8.11 and later */
  7844. sqlite3_value **apSqlParam; /* Original SQL values of parameters */
  7845. };
  7846. /*
  7847. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  7848. */
  7849. #define NOT_WITHIN 0 /* Object completely outside of query region */
  7850. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  7851. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  7852. #if 0
  7853. } /* end of the 'extern "C"' block */
  7854. #endif
  7855. #endif /* ifndef _SQLITE3RTREE_H_ */
  7856. /************** End of sqlite3.h *********************************************/
  7857. /************** Continuing where we left off in sqliteInt.h ******************/
  7858. /*
  7859. ** Include the configuration header output by 'configure' if we're using the
  7860. ** autoconf-based build
  7861. */
  7862. #ifdef _HAVE_SQLITE_CONFIG_H
  7863. #include "config.h"
  7864. #endif
  7865. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7866. /************** Begin file sqliteLimit.h *************************************/
  7867. /*
  7868. ** 2007 May 7
  7869. **
  7870. ** The author disclaims copyright to this source code. In place of
  7871. ** a legal notice, here is a blessing:
  7872. **
  7873. ** May you do good and not evil.
  7874. ** May you find forgiveness for yourself and forgive others.
  7875. ** May you share freely, never taking more than you give.
  7876. **
  7877. *************************************************************************
  7878. **
  7879. ** This file defines various limits of what SQLite can process.
  7880. */
  7881. /*
  7882. ** The maximum length of a TEXT or BLOB in bytes. This also
  7883. ** limits the size of a row in a table or index.
  7884. **
  7885. ** The hard limit is the ability of a 32-bit signed integer
  7886. ** to count the size: 2^31-1 or 2147483647.
  7887. */
  7888. #ifndef SQLITE_MAX_LENGTH
  7889. # define SQLITE_MAX_LENGTH 1000000000
  7890. #endif
  7891. /*
  7892. ** This is the maximum number of
  7893. **
  7894. ** * Columns in a table
  7895. ** * Columns in an index
  7896. ** * Columns in a view
  7897. ** * Terms in the SET clause of an UPDATE statement
  7898. ** * Terms in the result set of a SELECT statement
  7899. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7900. ** * Terms in the VALUES clause of an INSERT statement
  7901. **
  7902. ** The hard upper limit here is 32676. Most database people will
  7903. ** tell you that in a well-normalized database, you usually should
  7904. ** not have more than a dozen or so columns in any table. And if
  7905. ** that is the case, there is no point in having more than a few
  7906. ** dozen values in any of the other situations described above.
  7907. */
  7908. #ifndef SQLITE_MAX_COLUMN
  7909. # define SQLITE_MAX_COLUMN 2000
  7910. #endif
  7911. /*
  7912. ** The maximum length of a single SQL statement in bytes.
  7913. **
  7914. ** It used to be the case that setting this value to zero would
  7915. ** turn the limit off. That is no longer true. It is not possible
  7916. ** to turn this limit off.
  7917. */
  7918. #ifndef SQLITE_MAX_SQL_LENGTH
  7919. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7920. #endif
  7921. /*
  7922. ** The maximum depth of an expression tree. This is limited to
  7923. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7924. ** want to place more severe limits on the complexity of an
  7925. ** expression.
  7926. **
  7927. ** A value of 0 used to mean that the limit was not enforced.
  7928. ** But that is no longer true. The limit is now strictly enforced
  7929. ** at all times.
  7930. */
  7931. #ifndef SQLITE_MAX_EXPR_DEPTH
  7932. # define SQLITE_MAX_EXPR_DEPTH 1000
  7933. #endif
  7934. /*
  7935. ** The maximum number of terms in a compound SELECT statement.
  7936. ** The code generator for compound SELECT statements does one
  7937. ** level of recursion for each term. A stack overflow can result
  7938. ** if the number of terms is too large. In practice, most SQL
  7939. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7940. ** any limit on the number of terms in a compount SELECT.
  7941. */
  7942. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7943. # define SQLITE_MAX_COMPOUND_SELECT 500
  7944. #endif
  7945. /*
  7946. ** The maximum number of opcodes in a VDBE program.
  7947. ** Not currently enforced.
  7948. */
  7949. #ifndef SQLITE_MAX_VDBE_OP
  7950. # define SQLITE_MAX_VDBE_OP 25000
  7951. #endif
  7952. /*
  7953. ** The maximum number of arguments to an SQL function.
  7954. */
  7955. #ifndef SQLITE_MAX_FUNCTION_ARG
  7956. # define SQLITE_MAX_FUNCTION_ARG 127
  7957. #endif
  7958. /*
  7959. ** The suggested maximum number of in-memory pages to use for
  7960. ** the main database table and for temporary tables.
  7961. **
  7962. ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
  7963. ** is 2000 pages.
  7964. ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
  7965. ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
  7966. */
  7967. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7968. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7969. #endif
  7970. /*
  7971. ** The default number of frames to accumulate in the log file before
  7972. ** checkpointing the database in WAL mode.
  7973. */
  7974. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7975. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7976. #endif
  7977. /*
  7978. ** The maximum number of attached databases. This must be between 0
  7979. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7980. ** is used internally to track attached databases.
  7981. */
  7982. #ifndef SQLITE_MAX_ATTACHED
  7983. # define SQLITE_MAX_ATTACHED 10
  7984. #endif
  7985. /*
  7986. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7987. */
  7988. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7989. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7990. #endif
  7991. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7992. ** imposed by the use of 16-bit offsets within each page.
  7993. **
  7994. ** Earlier versions of SQLite allowed the user to change this value at
  7995. ** compile time. This is no longer permitted, on the grounds that it creates
  7996. ** a library that is technically incompatible with an SQLite library
  7997. ** compiled with a different limit. If a process operating on a database
  7998. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7999. ** compiled with the default page-size limit will not be able to rollback
  8000. ** the aborted transaction. This could lead to database corruption.
  8001. */
  8002. #ifdef SQLITE_MAX_PAGE_SIZE
  8003. # undef SQLITE_MAX_PAGE_SIZE
  8004. #endif
  8005. #define SQLITE_MAX_PAGE_SIZE 65536
  8006. /*
  8007. ** The default size of a database page.
  8008. */
  8009. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  8010. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  8011. #endif
  8012. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8013. # undef SQLITE_DEFAULT_PAGE_SIZE
  8014. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8015. #endif
  8016. /*
  8017. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  8018. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  8019. ** device characteristics (sector-size and atomic write() support),
  8020. ** SQLite may choose a larger value. This constant is the maximum value
  8021. ** SQLite will choose on its own.
  8022. */
  8023. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8024. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  8025. #endif
  8026. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  8027. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  8028. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  8029. #endif
  8030. /*
  8031. ** Maximum number of pages in one database file.
  8032. **
  8033. ** This is really just the default value for the max_page_count pragma.
  8034. ** This value can be lowered (or raised) at run-time using that the
  8035. ** max_page_count macro.
  8036. */
  8037. #ifndef SQLITE_MAX_PAGE_COUNT
  8038. # define SQLITE_MAX_PAGE_COUNT 1073741823
  8039. #endif
  8040. /*
  8041. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  8042. ** operator.
  8043. */
  8044. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  8045. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  8046. #endif
  8047. /*
  8048. ** Maximum depth of recursion for triggers.
  8049. **
  8050. ** A value of 1 means that a trigger program will not be able to itself
  8051. ** fire any triggers. A value of 0 means that no trigger programs at all
  8052. ** may be executed.
  8053. */
  8054. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  8055. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  8056. #endif
  8057. /************** End of sqliteLimit.h *****************************************/
  8058. /************** Continuing where we left off in sqliteInt.h ******************/
  8059. /* Disable nuisance warnings on Borland compilers */
  8060. #if defined(__BORLANDC__)
  8061. #pragma warn -rch /* unreachable code */
  8062. #pragma warn -ccc /* Condition is always true or false */
  8063. #pragma warn -aus /* Assigned value is never used */
  8064. #pragma warn -csu /* Comparing signed and unsigned */
  8065. #pragma warn -spa /* Suspicious pointer arithmetic */
  8066. #endif
  8067. /*
  8068. ** Include standard header files as necessary
  8069. */
  8070. #ifdef HAVE_STDINT_H
  8071. #include <stdint.h>
  8072. #endif
  8073. #ifdef HAVE_INTTYPES_H
  8074. #include <inttypes.h>
  8075. #endif
  8076. /*
  8077. ** The following macros are used to cast pointers to integers and
  8078. ** integers to pointers. The way you do this varies from one compiler
  8079. ** to the next, so we have developed the following set of #if statements
  8080. ** to generate appropriate macros for a wide range of compilers.
  8081. **
  8082. ** The correct "ANSI" way to do this is to use the intptr_t type.
  8083. ** Unfortunately, that typedef is not available on all compilers, or
  8084. ** if it is available, it requires an #include of specific headers
  8085. ** that vary from one machine to the next.
  8086. **
  8087. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  8088. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  8089. ** So we have to define the macros in different ways depending on the
  8090. ** compiler.
  8091. */
  8092. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  8093. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  8094. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  8095. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  8096. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  8097. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  8098. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  8099. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  8100. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  8101. #else /* Generates a warning - but it always works */
  8102. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  8103. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  8104. #endif
  8105. /*
  8106. ** A macro to hint to the compiler that a function should not be
  8107. ** inlined.
  8108. */
  8109. #if defined(__GNUC__)
  8110. # define SQLITE_NOINLINE __attribute__((noinline))
  8111. #elif defined(_MSC_VER) && _MSC_VER>=1310
  8112. # define SQLITE_NOINLINE __declspec(noinline)
  8113. #else
  8114. # define SQLITE_NOINLINE
  8115. #endif
  8116. /*
  8117. ** Make sure that the compiler intrinsics we desire are enabled when
  8118. ** compiling with an appropriate version of MSVC.
  8119. */
  8120. #if defined(_MSC_VER) && _MSC_VER>=1300
  8121. # if !defined(_WIN32_WCE)
  8122. # include <intrin.h>
  8123. # pragma intrinsic(_byteswap_ushort)
  8124. # pragma intrinsic(_byteswap_ulong)
  8125. # else
  8126. # include <cmnintrin.h>
  8127. # endif
  8128. #endif
  8129. /*
  8130. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  8131. ** 0 means mutexes are permanently disable and the library is never
  8132. ** threadsafe. 1 means the library is serialized which is the highest
  8133. ** level of threadsafety. 2 means the library is multithreaded - multiple
  8134. ** threads can use SQLite as long as no two threads try to use the same
  8135. ** database connection at the same time.
  8136. **
  8137. ** Older versions of SQLite used an optional THREADSAFE macro.
  8138. ** We support that for legacy.
  8139. */
  8140. #if !defined(SQLITE_THREADSAFE)
  8141. # if defined(THREADSAFE)
  8142. # define SQLITE_THREADSAFE THREADSAFE
  8143. # else
  8144. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  8145. # endif
  8146. #endif
  8147. /*
  8148. ** Powersafe overwrite is on by default. But can be turned off using
  8149. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  8150. */
  8151. #ifndef SQLITE_POWERSAFE_OVERWRITE
  8152. # define SQLITE_POWERSAFE_OVERWRITE 1
  8153. #endif
  8154. /*
  8155. ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
  8156. ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
  8157. ** which case memory allocation statistics are disabled by default.
  8158. */
  8159. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  8160. # define SQLITE_DEFAULT_MEMSTATUS 1
  8161. #endif
  8162. /*
  8163. ** Exactly one of the following macros must be defined in order to
  8164. ** specify which memory allocation subsystem to use.
  8165. **
  8166. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  8167. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  8168. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  8169. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  8170. **
  8171. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  8172. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  8173. ** will cause HeapValidate to be called. If heap validation should fail, an
  8174. ** assertion will be triggered.
  8175. **
  8176. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  8177. ** the default.
  8178. */
  8179. #if defined(SQLITE_SYSTEM_MALLOC) \
  8180. + defined(SQLITE_WIN32_MALLOC) \
  8181. + defined(SQLITE_ZERO_MALLOC) \
  8182. + defined(SQLITE_MEMDEBUG)>1
  8183. # error "Two or more of the following compile-time configuration options\
  8184. are defined but at most one is allowed:\
  8185. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  8186. SQLITE_ZERO_MALLOC"
  8187. #endif
  8188. #if defined(SQLITE_SYSTEM_MALLOC) \
  8189. + defined(SQLITE_WIN32_MALLOC) \
  8190. + defined(SQLITE_ZERO_MALLOC) \
  8191. + defined(SQLITE_MEMDEBUG)==0
  8192. # define SQLITE_SYSTEM_MALLOC 1
  8193. #endif
  8194. /*
  8195. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  8196. ** sizes of memory allocations below this value where possible.
  8197. */
  8198. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  8199. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  8200. #endif
  8201. /*
  8202. ** We need to define _XOPEN_SOURCE as follows in order to enable
  8203. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  8204. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  8205. ** it.
  8206. */
  8207. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  8208. # define _XOPEN_SOURCE 600
  8209. #endif
  8210. /*
  8211. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  8212. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  8213. ** make it true by defining or undefining NDEBUG.
  8214. **
  8215. ** Setting NDEBUG makes the code smaller and faster by disabling the
  8216. ** assert() statements in the code. So we want the default action
  8217. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  8218. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  8219. ** feature.
  8220. */
  8221. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  8222. # define NDEBUG 1
  8223. #endif
  8224. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  8225. # undef NDEBUG
  8226. #endif
  8227. /*
  8228. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  8229. */
  8230. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  8231. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  8232. #endif
  8233. /*
  8234. ** The testcase() macro is used to aid in coverage testing. When
  8235. ** doing coverage testing, the condition inside the argument to
  8236. ** testcase() must be evaluated both true and false in order to
  8237. ** get full branch coverage. The testcase() macro is inserted
  8238. ** to help ensure adequate test coverage in places where simple
  8239. ** condition/decision coverage is inadequate. For example, testcase()
  8240. ** can be used to make sure boundary values are tested. For
  8241. ** bitmask tests, testcase() can be used to make sure each bit
  8242. ** is significant and used at least once. On switch statements
  8243. ** where multiple cases go to the same block of code, testcase()
  8244. ** can insure that all cases are evaluated.
  8245. **
  8246. */
  8247. #ifdef SQLITE_COVERAGE_TEST
  8248. SQLITE_PRIVATE void sqlite3Coverage(int);
  8249. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  8250. #else
  8251. # define testcase(X)
  8252. #endif
  8253. /*
  8254. ** The TESTONLY macro is used to enclose variable declarations or
  8255. ** other bits of code that are needed to support the arguments
  8256. ** within testcase() and assert() macros.
  8257. */
  8258. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  8259. # define TESTONLY(X) X
  8260. #else
  8261. # define TESTONLY(X)
  8262. #endif
  8263. /*
  8264. ** Sometimes we need a small amount of code such as a variable initialization
  8265. ** to setup for a later assert() statement. We do not want this code to
  8266. ** appear when assert() is disabled. The following macro is therefore
  8267. ** used to contain that setup code. The "VVA" acronym stands for
  8268. ** "Verification, Validation, and Accreditation". In other words, the
  8269. ** code within VVA_ONLY() will only run during verification processes.
  8270. */
  8271. #ifndef NDEBUG
  8272. # define VVA_ONLY(X) X
  8273. #else
  8274. # define VVA_ONLY(X)
  8275. #endif
  8276. /*
  8277. ** The ALWAYS and NEVER macros surround boolean expressions which
  8278. ** are intended to always be true or false, respectively. Such
  8279. ** expressions could be omitted from the code completely. But they
  8280. ** are included in a few cases in order to enhance the resilience
  8281. ** of SQLite to unexpected behavior - to make the code "self-healing"
  8282. ** or "ductile" rather than being "brittle" and crashing at the first
  8283. ** hint of unplanned behavior.
  8284. **
  8285. ** In other words, ALWAYS and NEVER are added for defensive code.
  8286. **
  8287. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  8288. ** be true and false so that the unreachable code they specify will
  8289. ** not be counted as untested code.
  8290. */
  8291. #if defined(SQLITE_COVERAGE_TEST)
  8292. # define ALWAYS(X) (1)
  8293. # define NEVER(X) (0)
  8294. #elif !defined(NDEBUG)
  8295. # define ALWAYS(X) ((X)?1:(assert(0),0))
  8296. # define NEVER(X) ((X)?(assert(0),1):0)
  8297. #else
  8298. # define ALWAYS(X) (X)
  8299. # define NEVER(X) (X)
  8300. #endif
  8301. /*
  8302. ** Declarations used for tracing the operating system interfaces.
  8303. */
  8304. #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
  8305. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  8306. extern int sqlite3OSTrace;
  8307. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  8308. # define SQLITE_HAVE_OS_TRACE
  8309. #else
  8310. # define OSTRACE(X)
  8311. # undef SQLITE_HAVE_OS_TRACE
  8312. #endif
  8313. /*
  8314. ** Is the sqlite3ErrName() function needed in the build? Currently,
  8315. ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
  8316. ** OSTRACE is enabled), and by several "test*.c" files (which are
  8317. ** compiled using SQLITE_TEST).
  8318. */
  8319. #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
  8320. (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
  8321. # define SQLITE_NEED_ERR_NAME
  8322. #else
  8323. # undef SQLITE_NEED_ERR_NAME
  8324. #endif
  8325. /*
  8326. ** Return true (non-zero) if the input is an integer that is too large
  8327. ** to fit in 32-bits. This macro is used inside of various testcase()
  8328. ** macros to verify that we have tested SQLite for large-file support.
  8329. */
  8330. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  8331. /*
  8332. ** The macro unlikely() is a hint that surrounds a boolean
  8333. ** expression that is usually false. Macro likely() surrounds
  8334. ** a boolean expression that is usually true. These hints could,
  8335. ** in theory, be used by the compiler to generate better code, but
  8336. ** currently they are just comments for human readers.
  8337. */
  8338. #define likely(X) (X)
  8339. #define unlikely(X) (X)
  8340. /************** Include hash.h in the middle of sqliteInt.h ******************/
  8341. /************** Begin file hash.h ********************************************/
  8342. /*
  8343. ** 2001 September 22
  8344. **
  8345. ** The author disclaims copyright to this source code. In place of
  8346. ** a legal notice, here is a blessing:
  8347. **
  8348. ** May you do good and not evil.
  8349. ** May you find forgiveness for yourself and forgive others.
  8350. ** May you share freely, never taking more than you give.
  8351. **
  8352. *************************************************************************
  8353. ** This is the header file for the generic hash-table implementation
  8354. ** used in SQLite.
  8355. */
  8356. #ifndef _SQLITE_HASH_H_
  8357. #define _SQLITE_HASH_H_
  8358. /* Forward declarations of structures. */
  8359. typedef struct Hash Hash;
  8360. typedef struct HashElem HashElem;
  8361. /* A complete hash table is an instance of the following structure.
  8362. ** The internals of this structure are intended to be opaque -- client
  8363. ** code should not attempt to access or modify the fields of this structure
  8364. ** directly. Change this structure only by using the routines below.
  8365. ** However, some of the "procedures" and "functions" for modifying and
  8366. ** accessing this structure are really macros, so we can't really make
  8367. ** this structure opaque.
  8368. **
  8369. ** All elements of the hash table are on a single doubly-linked list.
  8370. ** Hash.first points to the head of this list.
  8371. **
  8372. ** There are Hash.htsize buckets. Each bucket points to a spot in
  8373. ** the global doubly-linked list. The contents of the bucket are the
  8374. ** element pointed to plus the next _ht.count-1 elements in the list.
  8375. **
  8376. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  8377. ** by a linear search of the global list. For small tables, the
  8378. ** Hash.ht table is never allocated because if there are few elements
  8379. ** in the table, it is faster to do a linear search than to manage
  8380. ** the hash table.
  8381. */
  8382. struct Hash {
  8383. unsigned int htsize; /* Number of buckets in the hash table */
  8384. unsigned int count; /* Number of entries in this table */
  8385. HashElem *first; /* The first element of the array */
  8386. struct _ht { /* the hash table */
  8387. int count; /* Number of entries with this hash */
  8388. HashElem *chain; /* Pointer to first entry with this hash */
  8389. } *ht;
  8390. };
  8391. /* Each element in the hash table is an instance of the following
  8392. ** structure. All elements are stored on a single doubly-linked list.
  8393. **
  8394. ** Again, this structure is intended to be opaque, but it can't really
  8395. ** be opaque because it is used by macros.
  8396. */
  8397. struct HashElem {
  8398. HashElem *next, *prev; /* Next and previous elements in the table */
  8399. void *data; /* Data associated with this element */
  8400. const char *pKey; /* Key associated with this element */
  8401. };
  8402. /*
  8403. ** Access routines. To delete, insert a NULL pointer.
  8404. */
  8405. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  8406. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  8407. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  8408. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  8409. /*
  8410. ** Macros for looping over all elements of a hash table. The idiom is
  8411. ** like this:
  8412. **
  8413. ** Hash h;
  8414. ** HashElem *p;
  8415. ** ...
  8416. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  8417. ** SomeStructure *pData = sqliteHashData(p);
  8418. ** // do something with pData
  8419. ** }
  8420. */
  8421. #define sqliteHashFirst(H) ((H)->first)
  8422. #define sqliteHashNext(E) ((E)->next)
  8423. #define sqliteHashData(E) ((E)->data)
  8424. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  8425. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  8426. /*
  8427. ** Number of entries in a hash table
  8428. */
  8429. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  8430. #endif /* _SQLITE_HASH_H_ */
  8431. /************** End of hash.h ************************************************/
  8432. /************** Continuing where we left off in sqliteInt.h ******************/
  8433. /************** Include parse.h in the middle of sqliteInt.h *****************/
  8434. /************** Begin file parse.h *******************************************/
  8435. #define TK_SEMI 1
  8436. #define TK_EXPLAIN 2
  8437. #define TK_QUERY 3
  8438. #define TK_PLAN 4
  8439. #define TK_BEGIN 5
  8440. #define TK_TRANSACTION 6
  8441. #define TK_DEFERRED 7
  8442. #define TK_IMMEDIATE 8
  8443. #define TK_EXCLUSIVE 9
  8444. #define TK_COMMIT 10
  8445. #define TK_END 11
  8446. #define TK_ROLLBACK 12
  8447. #define TK_SAVEPOINT 13
  8448. #define TK_RELEASE 14
  8449. #define TK_TO 15
  8450. #define TK_TABLE 16
  8451. #define TK_CREATE 17
  8452. #define TK_IF 18
  8453. #define TK_NOT 19
  8454. #define TK_EXISTS 20
  8455. #define TK_TEMP 21
  8456. #define TK_LP 22
  8457. #define TK_RP 23
  8458. #define TK_AS 24
  8459. #define TK_WITHOUT 25
  8460. #define TK_COMMA 26
  8461. #define TK_ID 27
  8462. #define TK_INDEXED 28
  8463. #define TK_ABORT 29
  8464. #define TK_ACTION 30
  8465. #define TK_AFTER 31
  8466. #define TK_ANALYZE 32
  8467. #define TK_ASC 33
  8468. #define TK_ATTACH 34
  8469. #define TK_BEFORE 35
  8470. #define TK_BY 36
  8471. #define TK_CASCADE 37
  8472. #define TK_CAST 38
  8473. #define TK_COLUMNKW 39
  8474. #define TK_CONFLICT 40
  8475. #define TK_DATABASE 41
  8476. #define TK_DESC 42
  8477. #define TK_DETACH 43
  8478. #define TK_EACH 44
  8479. #define TK_FAIL 45
  8480. #define TK_FOR 46
  8481. #define TK_IGNORE 47
  8482. #define TK_INITIALLY 48
  8483. #define TK_INSTEAD 49
  8484. #define TK_LIKE_KW 50
  8485. #define TK_MATCH 51
  8486. #define TK_NO 52
  8487. #define TK_KEY 53
  8488. #define TK_OF 54
  8489. #define TK_OFFSET 55
  8490. #define TK_PRAGMA 56
  8491. #define TK_RAISE 57
  8492. #define TK_RECURSIVE 58
  8493. #define TK_REPLACE 59
  8494. #define TK_RESTRICT 60
  8495. #define TK_ROW 61
  8496. #define TK_TRIGGER 62
  8497. #define TK_VACUUM 63
  8498. #define TK_VIEW 64
  8499. #define TK_VIRTUAL 65
  8500. #define TK_WITH 66
  8501. #define TK_REINDEX 67
  8502. #define TK_RENAME 68
  8503. #define TK_CTIME_KW 69
  8504. #define TK_ANY 70
  8505. #define TK_OR 71
  8506. #define TK_AND 72
  8507. #define TK_IS 73
  8508. #define TK_BETWEEN 74
  8509. #define TK_IN 75
  8510. #define TK_ISNULL 76
  8511. #define TK_NOTNULL 77
  8512. #define TK_NE 78
  8513. #define TK_EQ 79
  8514. #define TK_GT 80
  8515. #define TK_LE 81
  8516. #define TK_LT 82
  8517. #define TK_GE 83
  8518. #define TK_ESCAPE 84
  8519. #define TK_BITAND 85
  8520. #define TK_BITOR 86
  8521. #define TK_LSHIFT 87
  8522. #define TK_RSHIFT 88
  8523. #define TK_PLUS 89
  8524. #define TK_MINUS 90
  8525. #define TK_STAR 91
  8526. #define TK_SLASH 92
  8527. #define TK_REM 93
  8528. #define TK_CONCAT 94
  8529. #define TK_COLLATE 95
  8530. #define TK_BITNOT 96
  8531. #define TK_STRING 97
  8532. #define TK_JOIN_KW 98
  8533. #define TK_CONSTRAINT 99
  8534. #define TK_DEFAULT 100
  8535. #define TK_NULL 101
  8536. #define TK_PRIMARY 102
  8537. #define TK_UNIQUE 103
  8538. #define TK_CHECK 104
  8539. #define TK_REFERENCES 105
  8540. #define TK_AUTOINCR 106
  8541. #define TK_ON 107
  8542. #define TK_INSERT 108
  8543. #define TK_DELETE 109
  8544. #define TK_UPDATE 110
  8545. #define TK_SET 111
  8546. #define TK_DEFERRABLE 112
  8547. #define TK_FOREIGN 113
  8548. #define TK_DROP 114
  8549. #define TK_UNION 115
  8550. #define TK_ALL 116
  8551. #define TK_EXCEPT 117
  8552. #define TK_INTERSECT 118
  8553. #define TK_SELECT 119
  8554. #define TK_VALUES 120
  8555. #define TK_DISTINCT 121
  8556. #define TK_DOT 122
  8557. #define TK_FROM 123
  8558. #define TK_JOIN 124
  8559. #define TK_USING 125
  8560. #define TK_ORDER 126
  8561. #define TK_GROUP 127
  8562. #define TK_HAVING 128
  8563. #define TK_LIMIT 129
  8564. #define TK_WHERE 130
  8565. #define TK_INTO 131
  8566. #define TK_INTEGER 132
  8567. #define TK_FLOAT 133
  8568. #define TK_BLOB 134
  8569. #define TK_VARIABLE 135
  8570. #define TK_CASE 136
  8571. #define TK_WHEN 137
  8572. #define TK_THEN 138
  8573. #define TK_ELSE 139
  8574. #define TK_INDEX 140
  8575. #define TK_ALTER 141
  8576. #define TK_ADD 142
  8577. #define TK_TO_TEXT 143
  8578. #define TK_TO_BLOB 144
  8579. #define TK_TO_NUMERIC 145
  8580. #define TK_TO_INT 146
  8581. #define TK_TO_REAL 147
  8582. #define TK_ISNOT 148
  8583. #define TK_END_OF_FILE 149
  8584. #define TK_ILLEGAL 150
  8585. #define TK_SPACE 151
  8586. #define TK_UNCLOSED_STRING 152
  8587. #define TK_FUNCTION 153
  8588. #define TK_COLUMN 154
  8589. #define TK_AGG_FUNCTION 155
  8590. #define TK_AGG_COLUMN 156
  8591. #define TK_UMINUS 157
  8592. #define TK_UPLUS 158
  8593. #define TK_REGISTER 159
  8594. /************** End of parse.h ***********************************************/
  8595. /************** Continuing where we left off in sqliteInt.h ******************/
  8596. #include <stdio.h>
  8597. #include <stdlib.h>
  8598. #include <string.h>
  8599. #include <assert.h>
  8600. #include <stddef.h>
  8601. /*
  8602. ** If compiling for a processor that lacks floating point support,
  8603. ** substitute integer for floating-point
  8604. */
  8605. #ifdef SQLITE_OMIT_FLOATING_POINT
  8606. # define double sqlite_int64
  8607. # define float sqlite_int64
  8608. # define LONGDOUBLE_TYPE sqlite_int64
  8609. # ifndef SQLITE_BIG_DBL
  8610. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  8611. # endif
  8612. # define SQLITE_OMIT_DATETIME_FUNCS 1
  8613. # define SQLITE_OMIT_TRACE 1
  8614. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  8615. # undef SQLITE_HAVE_ISNAN
  8616. #endif
  8617. #ifndef SQLITE_BIG_DBL
  8618. # define SQLITE_BIG_DBL (1e99)
  8619. #endif
  8620. /*
  8621. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  8622. ** afterward. Having this macro allows us to cause the C compiler
  8623. ** to omit code used by TEMP tables without messy #ifndef statements.
  8624. */
  8625. #ifdef SQLITE_OMIT_TEMPDB
  8626. #define OMIT_TEMPDB 1
  8627. #else
  8628. #define OMIT_TEMPDB 0
  8629. #endif
  8630. /*
  8631. ** The "file format" number is an integer that is incremented whenever
  8632. ** the VDBE-level file format changes. The following macros define the
  8633. ** the default file format for new databases and the maximum file format
  8634. ** that the library can read.
  8635. */
  8636. #define SQLITE_MAX_FILE_FORMAT 4
  8637. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  8638. # define SQLITE_DEFAULT_FILE_FORMAT 4
  8639. #endif
  8640. /*
  8641. ** Determine whether triggers are recursive by default. This can be
  8642. ** changed at run-time using a pragma.
  8643. */
  8644. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  8645. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  8646. #endif
  8647. /*
  8648. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  8649. ** on the command-line
  8650. */
  8651. #ifndef SQLITE_TEMP_STORE
  8652. # define SQLITE_TEMP_STORE 1
  8653. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  8654. #endif
  8655. /*
  8656. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  8657. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  8658. ** to zero.
  8659. */
  8660. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  8661. # undef SQLITE_MAX_WORKER_THREADS
  8662. # define SQLITE_MAX_WORKER_THREADS 0
  8663. #endif
  8664. #ifndef SQLITE_MAX_WORKER_THREADS
  8665. # define SQLITE_MAX_WORKER_THREADS 8
  8666. #endif
  8667. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  8668. # define SQLITE_DEFAULT_WORKER_THREADS 0
  8669. #endif
  8670. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  8671. # undef SQLITE_MAX_WORKER_THREADS
  8672. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  8673. #endif
  8674. /*
  8675. ** The default initial allocation for the pagecache when using separate
  8676. ** pagecaches for each database connection. A positive number is the
  8677. ** number of pages. A negative number N translations means that a buffer
  8678. ** of -1024*N bytes is allocated and used for as many pages as it will hold.
  8679. */
  8680. #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
  8681. # define SQLITE_DEFAULT_PCACHE_INITSZ 100
  8682. #endif
  8683. /*
  8684. ** GCC does not define the offsetof() macro so we'll have to do it
  8685. ** ourselves.
  8686. */
  8687. #ifndef offsetof
  8688. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  8689. #endif
  8690. /*
  8691. ** Macros to compute minimum and maximum of two numbers.
  8692. */
  8693. #define MIN(A,B) ((A)<(B)?(A):(B))
  8694. #define MAX(A,B) ((A)>(B)?(A):(B))
  8695. /*
  8696. ** Swap two objects of type TYPE.
  8697. */
  8698. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  8699. /*
  8700. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  8701. ** not, there are still machines out there that use EBCDIC.)
  8702. */
  8703. #if 'A' == '\301'
  8704. # define SQLITE_EBCDIC 1
  8705. #else
  8706. # define SQLITE_ASCII 1
  8707. #endif
  8708. /*
  8709. ** Integers of known sizes. These typedefs might change for architectures
  8710. ** where the sizes very. Preprocessor macros are available so that the
  8711. ** types can be conveniently redefined at compile-type. Like this:
  8712. **
  8713. ** cc '-DUINTPTR_TYPE=long long int' ...
  8714. */
  8715. #ifndef UINT32_TYPE
  8716. # ifdef HAVE_UINT32_T
  8717. # define UINT32_TYPE uint32_t
  8718. # else
  8719. # define UINT32_TYPE unsigned int
  8720. # endif
  8721. #endif
  8722. #ifndef UINT16_TYPE
  8723. # ifdef HAVE_UINT16_T
  8724. # define UINT16_TYPE uint16_t
  8725. # else
  8726. # define UINT16_TYPE unsigned short int
  8727. # endif
  8728. #endif
  8729. #ifndef INT16_TYPE
  8730. # ifdef HAVE_INT16_T
  8731. # define INT16_TYPE int16_t
  8732. # else
  8733. # define INT16_TYPE short int
  8734. # endif
  8735. #endif
  8736. #ifndef UINT8_TYPE
  8737. # ifdef HAVE_UINT8_T
  8738. # define UINT8_TYPE uint8_t
  8739. # else
  8740. # define UINT8_TYPE unsigned char
  8741. # endif
  8742. #endif
  8743. #ifndef INT8_TYPE
  8744. # ifdef HAVE_INT8_T
  8745. # define INT8_TYPE int8_t
  8746. # else
  8747. # define INT8_TYPE signed char
  8748. # endif
  8749. #endif
  8750. #ifndef LONGDOUBLE_TYPE
  8751. # define LONGDOUBLE_TYPE long double
  8752. #endif
  8753. typedef sqlite_int64 i64; /* 8-byte signed integer */
  8754. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  8755. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  8756. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  8757. typedef INT16_TYPE i16; /* 2-byte signed integer */
  8758. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  8759. typedef INT8_TYPE i8; /* 1-byte signed integer */
  8760. /*
  8761. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  8762. ** that can be stored in a u32 without loss of data. The value
  8763. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  8764. ** have to specify the value in the less intuitive manner shown:
  8765. */
  8766. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8767. /*
  8768. ** The datatype used to store estimates of the number of rows in a
  8769. ** table or index. This is an unsigned integer type. For 99.9% of
  8770. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8771. ** can be used at compile-time if desired.
  8772. */
  8773. #ifdef SQLITE_64BIT_STATS
  8774. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8775. #else
  8776. typedef u32 tRowcnt; /* 32-bit is the default */
  8777. #endif
  8778. /*
  8779. ** Estimated quantities used for query planning are stored as 16-bit
  8780. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8781. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8782. ** But the allowed values are "grainy". Not every value is representable.
  8783. ** For example, quantities 16 and 17 are both represented by a LogEst
  8784. ** of 40. However, since LogEst quantities are suppose to be estimates,
  8785. ** not exact values, this imprecision is not a problem.
  8786. **
  8787. ** "LogEst" is short for "Logarithmic Estimate".
  8788. **
  8789. ** Examples:
  8790. ** 1 -> 0 20 -> 43 10000 -> 132
  8791. ** 2 -> 10 25 -> 46 25000 -> 146
  8792. ** 3 -> 16 100 -> 66 1000000 -> 199
  8793. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8794. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8795. **
  8796. ** The LogEst can be negative to indicate fractional values.
  8797. ** Examples:
  8798. **
  8799. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8800. */
  8801. typedef INT16_TYPE LogEst;
  8802. /*
  8803. ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
  8804. */
  8805. #ifndef SQLITE_PTRSIZE
  8806. # if defined(__SIZEOF_POINTER__)
  8807. # define SQLITE_PTRSIZE __SIZEOF_POINTER__
  8808. # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  8809. defined(_M_ARM) || defined(__arm__) || defined(__x86)
  8810. # define SQLITE_PTRSIZE 4
  8811. # else
  8812. # define SQLITE_PTRSIZE 8
  8813. # endif
  8814. #endif
  8815. /*
  8816. ** Macros to determine whether the machine is big or little endian,
  8817. ** and whether or not that determination is run-time or compile-time.
  8818. **
  8819. ** For best performance, an attempt is made to guess at the byte-order
  8820. ** using C-preprocessor macros. If that is unsuccessful, or if
  8821. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  8822. ** at run-time.
  8823. */
  8824. #ifdef SQLITE_AMALGAMATION
  8825. SQLITE_PRIVATE const int sqlite3one = 1;
  8826. #else
  8827. SQLITE_PRIVATE const int sqlite3one;
  8828. #endif
  8829. #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  8830. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  8831. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  8832. defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
  8833. # define SQLITE_BYTEORDER 1234
  8834. # define SQLITE_BIGENDIAN 0
  8835. # define SQLITE_LITTLEENDIAN 1
  8836. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8837. #endif
  8838. #if (defined(sparc) || defined(__ppc__)) \
  8839. && !defined(SQLITE_RUNTIME_BYTEORDER)
  8840. # define SQLITE_BYTEORDER 4321
  8841. # define SQLITE_BIGENDIAN 1
  8842. # define SQLITE_LITTLEENDIAN 0
  8843. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  8844. #endif
  8845. #if !defined(SQLITE_BYTEORDER)
  8846. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  8847. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8848. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8849. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8850. #endif
  8851. /*
  8852. ** Constants for the largest and smallest possible 64-bit signed integers.
  8853. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8854. ** compilers.
  8855. */
  8856. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8857. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8858. /*
  8859. ** Round up a number to the next larger multiple of 8. This is used
  8860. ** to force 8-byte alignment on 64-bit architectures.
  8861. */
  8862. #define ROUND8(x) (((x)+7)&~7)
  8863. /*
  8864. ** Round down to the nearest multiple of 8
  8865. */
  8866. #define ROUNDDOWN8(x) ((x)&~7)
  8867. /*
  8868. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8869. ** macro is used only within assert() to verify that the code gets
  8870. ** all alignment restrictions correct.
  8871. **
  8872. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8873. ** underlying malloc() implementation might return us 4-byte aligned
  8874. ** pointers. In that case, only verify 4-byte alignment.
  8875. */
  8876. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8877. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8878. #else
  8879. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8880. #endif
  8881. /*
  8882. ** Disable MMAP on platforms where it is known to not work
  8883. */
  8884. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8885. # undef SQLITE_MAX_MMAP_SIZE
  8886. # define SQLITE_MAX_MMAP_SIZE 0
  8887. #endif
  8888. /*
  8889. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8890. */
  8891. #ifdef __APPLE__
  8892. # include <TargetConditionals.h>
  8893. # if TARGET_OS_IPHONE
  8894. # undef SQLITE_MAX_MMAP_SIZE
  8895. # define SQLITE_MAX_MMAP_SIZE 0
  8896. # endif
  8897. #endif
  8898. #ifndef SQLITE_MAX_MMAP_SIZE
  8899. # if defined(__linux__) \
  8900. || defined(_WIN32) \
  8901. || (defined(__APPLE__) && defined(__MACH__)) \
  8902. || defined(__sun) \
  8903. || defined(__FreeBSD__) \
  8904. || defined(__DragonFly__)
  8905. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8906. # else
  8907. # define SQLITE_MAX_MMAP_SIZE 0
  8908. # endif
  8909. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8910. #endif
  8911. /*
  8912. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8913. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8914. ** not exceed the maximum mmap size.
  8915. */
  8916. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8917. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8918. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8919. #endif
  8920. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8921. # undef SQLITE_DEFAULT_MMAP_SIZE
  8922. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8923. #endif
  8924. /*
  8925. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8926. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8927. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8928. */
  8929. #ifdef SQLITE_ENABLE_STAT4
  8930. # undef SQLITE_ENABLE_STAT3
  8931. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8932. #elif SQLITE_ENABLE_STAT3
  8933. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8934. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8935. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8936. #endif
  8937. /*
  8938. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  8939. ** the Select query generator tracing logic is turned on.
  8940. */
  8941. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  8942. # define SELECTTRACE_ENABLED 1
  8943. #else
  8944. # define SELECTTRACE_ENABLED 0
  8945. #endif
  8946. /*
  8947. ** An instance of the following structure is used to store the busy-handler
  8948. ** callback for a given sqlite handle.
  8949. **
  8950. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8951. ** callback for the database handle. Each pager opened via the sqlite
  8952. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8953. ** callback is currently invoked only from within pager.c.
  8954. */
  8955. typedef struct BusyHandler BusyHandler;
  8956. struct BusyHandler {
  8957. int (*xFunc)(void *,int); /* The busy callback */
  8958. void *pArg; /* First arg to busy callback */
  8959. int nBusy; /* Incremented with each busy call */
  8960. };
  8961. /*
  8962. ** Name of the master database table. The master database table
  8963. ** is a special table that holds the names and attributes of all
  8964. ** user tables and indices.
  8965. */
  8966. #define MASTER_NAME "sqlite_master"
  8967. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8968. /*
  8969. ** The root-page of the master database table.
  8970. */
  8971. #define MASTER_ROOT 1
  8972. /*
  8973. ** The name of the schema table.
  8974. */
  8975. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8976. /*
  8977. ** A convenience macro that returns the number of elements in
  8978. ** an array.
  8979. */
  8980. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8981. /*
  8982. ** Determine if the argument is a power of two
  8983. */
  8984. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8985. /*
  8986. ** The following value as a destructor means to use sqlite3DbFree().
  8987. ** The sqlite3DbFree() routine requires two parameters instead of the
  8988. ** one parameter that destructors normally want. So we have to introduce
  8989. ** this magic value that the code knows to handle differently. Any
  8990. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8991. ** and SQLITE_TRANSIENT.
  8992. */
  8993. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8994. /*
  8995. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8996. ** not support Writable Static Data (WSD) such as global and static variables.
  8997. ** All variables must either be on the stack or dynamically allocated from
  8998. ** the heap. When WSD is unsupported, the variable declarations scattered
  8999. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  9000. ** macro is used for this purpose. And instead of referencing the variable
  9001. ** directly, we use its constant as a key to lookup the run-time allocated
  9002. ** buffer that holds real variable. The constant is also the initializer
  9003. ** for the run-time allocated buffer.
  9004. **
  9005. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  9006. ** macros become no-ops and have zero performance impact.
  9007. */
  9008. #ifdef SQLITE_OMIT_WSD
  9009. #define SQLITE_WSD const
  9010. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  9011. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  9012. SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
  9013. SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
  9014. #else
  9015. #define SQLITE_WSD
  9016. #define GLOBAL(t,v) v
  9017. #define sqlite3GlobalConfig sqlite3Config
  9018. #endif
  9019. /*
  9020. ** The following macros are used to suppress compiler warnings and to
  9021. ** make it clear to human readers when a function parameter is deliberately
  9022. ** left unused within the body of a function. This usually happens when
  9023. ** a function is called via a function pointer. For example the
  9024. ** implementation of an SQL aggregate step callback may not use the
  9025. ** parameter indicating the number of arguments passed to the aggregate,
  9026. ** if it knows that this is enforced elsewhere.
  9027. **
  9028. ** When a function parameter is not used at all within the body of a function,
  9029. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  9030. ** However, these macros may also be used to suppress warnings related to
  9031. ** parameters that may or may not be used depending on compilation options.
  9032. ** For example those parameters only used in assert() statements. In these
  9033. ** cases the parameters are named as per the usual conventions.
  9034. */
  9035. #define UNUSED_PARAMETER(x) (void)(x)
  9036. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  9037. /*
  9038. ** Forward references to structures
  9039. */
  9040. typedef struct AggInfo AggInfo;
  9041. typedef struct AuthContext AuthContext;
  9042. typedef struct AutoincInfo AutoincInfo;
  9043. typedef struct Bitvec Bitvec;
  9044. typedef struct CollSeq CollSeq;
  9045. typedef struct Column Column;
  9046. typedef struct Db Db;
  9047. typedef struct Schema Schema;
  9048. typedef struct Expr Expr;
  9049. typedef struct ExprList ExprList;
  9050. typedef struct ExprSpan ExprSpan;
  9051. typedef struct FKey FKey;
  9052. typedef struct FuncDestructor FuncDestructor;
  9053. typedef struct FuncDef FuncDef;
  9054. typedef struct FuncDefHash FuncDefHash;
  9055. typedef struct IdList IdList;
  9056. typedef struct Index Index;
  9057. typedef struct IndexSample IndexSample;
  9058. typedef struct KeyClass KeyClass;
  9059. typedef struct KeyInfo KeyInfo;
  9060. typedef struct Lookaside Lookaside;
  9061. typedef struct LookasideSlot LookasideSlot;
  9062. typedef struct Module Module;
  9063. typedef struct NameContext NameContext;
  9064. typedef struct Parse Parse;
  9065. typedef struct PrintfArguments PrintfArguments;
  9066. typedef struct RowSet RowSet;
  9067. typedef struct Savepoint Savepoint;
  9068. typedef struct Select Select;
  9069. typedef struct SQLiteThread SQLiteThread;
  9070. typedef struct SelectDest SelectDest;
  9071. typedef struct SrcList SrcList;
  9072. typedef struct StrAccum StrAccum;
  9073. typedef struct Table Table;
  9074. typedef struct TableLock TableLock;
  9075. typedef struct Token Token;
  9076. typedef struct TreeView TreeView;
  9077. typedef struct Trigger Trigger;
  9078. typedef struct TriggerPrg TriggerPrg;
  9079. typedef struct TriggerStep TriggerStep;
  9080. typedef struct UnpackedRecord UnpackedRecord;
  9081. typedef struct VTable VTable;
  9082. typedef struct VtabCtx VtabCtx;
  9083. typedef struct Walker Walker;
  9084. typedef struct WhereInfo WhereInfo;
  9085. typedef struct With With;
  9086. /*
  9087. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  9088. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  9089. ** pointer types (i.e. FuncDef) defined above.
  9090. */
  9091. /************** Include btree.h in the middle of sqliteInt.h *****************/
  9092. /************** Begin file btree.h *******************************************/
  9093. /*
  9094. ** 2001 September 15
  9095. **
  9096. ** The author disclaims copyright to this source code. In place of
  9097. ** a legal notice, here is a blessing:
  9098. **
  9099. ** May you do good and not evil.
  9100. ** May you find forgiveness for yourself and forgive others.
  9101. ** May you share freely, never taking more than you give.
  9102. **
  9103. *************************************************************************
  9104. ** This header file defines the interface that the sqlite B-Tree file
  9105. ** subsystem. See comments in the source code for a detailed description
  9106. ** of what each interface routine does.
  9107. */
  9108. #ifndef _BTREE_H_
  9109. #define _BTREE_H_
  9110. /* TODO: This definition is just included so other modules compile. It
  9111. ** needs to be revisited.
  9112. */
  9113. #define SQLITE_N_BTREE_META 16
  9114. /*
  9115. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  9116. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  9117. */
  9118. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  9119. #define SQLITE_DEFAULT_AUTOVACUUM 0
  9120. #endif
  9121. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  9122. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  9123. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  9124. /*
  9125. ** Forward declarations of structure
  9126. */
  9127. typedef struct Btree Btree;
  9128. typedef struct BtCursor BtCursor;
  9129. typedef struct BtShared BtShared;
  9130. SQLITE_PRIVATE int sqlite3BtreeOpen(
  9131. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  9132. const char *zFilename, /* Name of database file to open */
  9133. sqlite3 *db, /* Associated database connection */
  9134. Btree **ppBtree, /* Return open Btree* here */
  9135. int flags, /* Flags */
  9136. int vfsFlags /* Flags passed through to VFS open */
  9137. );
  9138. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  9139. ** following values.
  9140. **
  9141. ** NOTE: These values must match the corresponding PAGER_ values in
  9142. ** pager.h.
  9143. */
  9144. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  9145. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  9146. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  9147. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  9148. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  9149. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  9150. #if SQLITE_MAX_MMAP_SIZE>0
  9151. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  9152. #endif
  9153. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  9154. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  9155. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  9156. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  9157. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  9158. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  9159. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  9160. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
  9161. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  9162. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  9163. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  9164. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  9165. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  9166. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  9167. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  9168. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  9169. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  9170. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  9171. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  9172. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  9173. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  9174. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  9175. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  9176. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  9177. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  9178. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  9179. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  9180. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  9181. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  9182. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  9183. ** of the flags shown below.
  9184. **
  9185. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  9186. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  9187. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  9188. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  9189. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  9190. ** indices.)
  9191. */
  9192. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  9193. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  9194. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  9195. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  9196. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  9197. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  9198. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  9199. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  9200. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  9201. /*
  9202. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  9203. ** should be one of the following values. The integer values are assigned
  9204. ** to constants so that the offset of the corresponding field in an
  9205. ** SQLite database header may be found using the following formula:
  9206. **
  9207. ** offset = 36 + (idx * 4)
  9208. **
  9209. ** For example, the free-page-count field is located at byte offset 36 of
  9210. ** the database file header. The incr-vacuum-flag field is located at
  9211. ** byte offset 64 (== 36+4*7).
  9212. **
  9213. ** The BTREE_DATA_VERSION value is not really a value stored in the header.
  9214. ** It is a read-only number computed by the pager. But we merge it with
  9215. ** the header value access routines since its access pattern is the same.
  9216. ** Call it a "virtual meta value".
  9217. */
  9218. #define BTREE_FREE_PAGE_COUNT 0
  9219. #define BTREE_SCHEMA_VERSION 1
  9220. #define BTREE_FILE_FORMAT 2
  9221. #define BTREE_DEFAULT_CACHE_SIZE 3
  9222. #define BTREE_LARGEST_ROOT_PAGE 4
  9223. #define BTREE_TEXT_ENCODING 5
  9224. #define BTREE_USER_VERSION 6
  9225. #define BTREE_INCR_VACUUM 7
  9226. #define BTREE_APPLICATION_ID 8
  9227. #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
  9228. /*
  9229. ** Values that may be OR'd together to form the second argument of an
  9230. ** sqlite3BtreeCursorHints() call.
  9231. **
  9232. ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
  9233. ** to be filled with content that is already in sorted order.
  9234. **
  9235. ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
  9236. ** OP_SeekLE opcodes for a range search, but where the range of entries
  9237. ** selected will all have the same key. In other words, the cursor will
  9238. ** be used only for equality key searches.
  9239. **
  9240. */
  9241. #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
  9242. #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
  9243. SQLITE_PRIVATE int sqlite3BtreeCursor(
  9244. Btree*, /* BTree containing table to open */
  9245. int iTable, /* Index of root page */
  9246. int wrFlag, /* 1 for writing. 0 for read-only */
  9247. struct KeyInfo*, /* First argument to compare function */
  9248. BtCursor *pCursor /* Space to write cursor structure */
  9249. );
  9250. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  9251. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  9252. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  9253. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  9254. BtCursor*,
  9255. UnpackedRecord *pUnKey,
  9256. i64 intKey,
  9257. int bias,
  9258. int *pRes
  9259. );
  9260. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  9261. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  9262. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  9263. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  9264. const void *pData, int nData,
  9265. int nZero, int bias, int seekResult);
  9266. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  9267. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  9268. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  9269. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  9270. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  9271. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  9272. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  9273. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  9274. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  9275. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  9276. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  9277. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  9278. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  9279. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  9280. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  9281. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  9282. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  9283. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  9284. #ifdef SQLITE_DEBUG
  9285. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
  9286. #endif
  9287. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  9288. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
  9289. #ifndef NDEBUG
  9290. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  9291. #endif
  9292. #ifndef SQLITE_OMIT_BTREECOUNT
  9293. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  9294. #endif
  9295. #ifdef SQLITE_TEST
  9296. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  9297. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  9298. #endif
  9299. #ifndef SQLITE_OMIT_WAL
  9300. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  9301. #endif
  9302. /*
  9303. ** If we are not using shared cache, then there is no need to
  9304. ** use mutexes to access the BtShared structures. So make the
  9305. ** Enter and Leave procedures no-ops.
  9306. */
  9307. #ifndef SQLITE_OMIT_SHARED_CACHE
  9308. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  9309. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  9310. #else
  9311. # define sqlite3BtreeEnter(X)
  9312. # define sqlite3BtreeEnterAll(X)
  9313. #endif
  9314. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  9315. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  9316. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  9317. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  9318. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  9319. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  9320. #ifndef NDEBUG
  9321. /* These routines are used inside assert() statements only. */
  9322. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  9323. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  9324. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  9325. #endif
  9326. #else
  9327. # define sqlite3BtreeSharable(X) 0
  9328. # define sqlite3BtreeLeave(X)
  9329. # define sqlite3BtreeEnterCursor(X)
  9330. # define sqlite3BtreeLeaveCursor(X)
  9331. # define sqlite3BtreeLeaveAll(X)
  9332. # define sqlite3BtreeHoldsMutex(X) 1
  9333. # define sqlite3BtreeHoldsAllMutexes(X) 1
  9334. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  9335. #endif
  9336. #endif /* _BTREE_H_ */
  9337. /************** End of btree.h ***********************************************/
  9338. /************** Continuing where we left off in sqliteInt.h ******************/
  9339. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  9340. /************** Begin file vdbe.h ********************************************/
  9341. /*
  9342. ** 2001 September 15
  9343. **
  9344. ** The author disclaims copyright to this source code. In place of
  9345. ** a legal notice, here is a blessing:
  9346. **
  9347. ** May you do good and not evil.
  9348. ** May you find forgiveness for yourself and forgive others.
  9349. ** May you share freely, never taking more than you give.
  9350. **
  9351. *************************************************************************
  9352. ** Header file for the Virtual DataBase Engine (VDBE)
  9353. **
  9354. ** This header defines the interface to the virtual database engine
  9355. ** or VDBE. The VDBE implements an abstract machine that runs a
  9356. ** simple program to access and modify the underlying database.
  9357. */
  9358. #ifndef _SQLITE_VDBE_H_
  9359. #define _SQLITE_VDBE_H_
  9360. /* #include <stdio.h> */
  9361. /*
  9362. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  9363. ** in the source file sqliteVdbe.c are allowed to see the insides
  9364. ** of this structure.
  9365. */
  9366. typedef struct Vdbe Vdbe;
  9367. /*
  9368. ** The names of the following types declared in vdbeInt.h are required
  9369. ** for the VdbeOp definition.
  9370. */
  9371. typedef struct Mem Mem;
  9372. typedef struct SubProgram SubProgram;
  9373. /*
  9374. ** A single instruction of the virtual machine has an opcode
  9375. ** and as many as three operands. The instruction is recorded
  9376. ** as an instance of the following structure:
  9377. */
  9378. struct VdbeOp {
  9379. u8 opcode; /* What operation to perform */
  9380. signed char p4type; /* One of the P4_xxx constants for p4 */
  9381. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  9382. u8 p5; /* Fifth parameter is an unsigned character */
  9383. int p1; /* First operand */
  9384. int p2; /* Second parameter (often the jump destination) */
  9385. int p3; /* The third parameter */
  9386. union p4union { /* fourth parameter */
  9387. int i; /* Integer value if p4type==P4_INT32 */
  9388. void *p; /* Generic pointer */
  9389. char *z; /* Pointer to data for string (char array) types */
  9390. i64 *pI64; /* Used when p4type is P4_INT64 */
  9391. double *pReal; /* Used when p4type is P4_REAL */
  9392. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  9393. sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
  9394. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  9395. Mem *pMem; /* Used when p4type is P4_MEM */
  9396. VTable *pVtab; /* Used when p4type is P4_VTAB */
  9397. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  9398. int *ai; /* Used when p4type is P4_INTARRAY */
  9399. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  9400. int (*xAdvance)(BtCursor *, int *);
  9401. } p4;
  9402. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9403. char *zComment; /* Comment to improve readability */
  9404. #endif
  9405. #ifdef VDBE_PROFILE
  9406. u32 cnt; /* Number of times this instruction was executed */
  9407. u64 cycles; /* Total time spent executing this instruction */
  9408. #endif
  9409. #ifdef SQLITE_VDBE_COVERAGE
  9410. int iSrcLine; /* Source-code line that generated this opcode */
  9411. #endif
  9412. };
  9413. typedef struct VdbeOp VdbeOp;
  9414. /*
  9415. ** A sub-routine used to implement a trigger program.
  9416. */
  9417. struct SubProgram {
  9418. VdbeOp *aOp; /* Array of opcodes for sub-program */
  9419. int nOp; /* Elements in aOp[] */
  9420. int nMem; /* Number of memory cells required */
  9421. int nCsr; /* Number of cursors required */
  9422. int nOnce; /* Number of OP_Once instructions */
  9423. void *token; /* id that may be used to recursive triggers */
  9424. SubProgram *pNext; /* Next sub-program already visited */
  9425. };
  9426. /*
  9427. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  9428. ** it takes up less space.
  9429. */
  9430. struct VdbeOpList {
  9431. u8 opcode; /* What operation to perform */
  9432. signed char p1; /* First operand */
  9433. signed char p2; /* Second parameter (often the jump destination) */
  9434. signed char p3; /* Third parameter */
  9435. };
  9436. typedef struct VdbeOpList VdbeOpList;
  9437. /*
  9438. ** Allowed values of VdbeOp.p4type
  9439. */
  9440. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  9441. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  9442. #define P4_STATIC (-2) /* Pointer to a static string */
  9443. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  9444. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  9445. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  9446. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  9447. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  9448. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  9449. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  9450. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  9451. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  9452. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  9453. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  9454. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  9455. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  9456. #define P4_FUNCCTX (-20) /* P4 is a pointer to an sqlite3_context object */
  9457. /* Error message codes for OP_Halt */
  9458. #define P5_ConstraintNotNull 1
  9459. #define P5_ConstraintUnique 2
  9460. #define P5_ConstraintCheck 3
  9461. #define P5_ConstraintFK 4
  9462. /*
  9463. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  9464. ** number of columns of data returned by the statement.
  9465. */
  9466. #define COLNAME_NAME 0
  9467. #define COLNAME_DECLTYPE 1
  9468. #define COLNAME_DATABASE 2
  9469. #define COLNAME_TABLE 3
  9470. #define COLNAME_COLUMN 4
  9471. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  9472. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  9473. #else
  9474. # ifdef SQLITE_OMIT_DECLTYPE
  9475. # define COLNAME_N 1 /* Store only the name */
  9476. # else
  9477. # define COLNAME_N 2 /* Store the name and decltype */
  9478. # endif
  9479. #endif
  9480. /*
  9481. ** The following macro converts a relative address in the p2 field
  9482. ** of a VdbeOp structure into a negative number so that
  9483. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  9484. ** the macro again restores the address.
  9485. */
  9486. #define ADDR(X) (-1-(X))
  9487. /*
  9488. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  9489. ** header file that defines a number for each opcode used by the VDBE.
  9490. */
  9491. /************** Include opcodes.h in the middle of vdbe.h ********************/
  9492. /************** Begin file opcodes.h *****************************************/
  9493. /* Automatically generated. Do not edit */
  9494. /* See the mkopcodeh.awk script for details */
  9495. #define OP_Savepoint 1
  9496. #define OP_AutoCommit 2
  9497. #define OP_Transaction 3
  9498. #define OP_SorterNext 4
  9499. #define OP_PrevIfOpen 5
  9500. #define OP_NextIfOpen 6
  9501. #define OP_Prev 7
  9502. #define OP_Next 8
  9503. #define OP_Checkpoint 9
  9504. #define OP_JournalMode 10
  9505. #define OP_Vacuum 11
  9506. #define OP_VFilter 12 /* synopsis: iplan=r[P3] zplan='P4' */
  9507. #define OP_VUpdate 13 /* synopsis: data=r[P3@P2] */
  9508. #define OP_Goto 14
  9509. #define OP_Gosub 15
  9510. #define OP_Return 16
  9511. #define OP_InitCoroutine 17
  9512. #define OP_EndCoroutine 18
  9513. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  9514. #define OP_Yield 20
  9515. #define OP_HaltIfNull 21 /* synopsis: if r[P3]=null halt */
  9516. #define OP_Halt 22
  9517. #define OP_Integer 23 /* synopsis: r[P2]=P1 */
  9518. #define OP_Int64 24 /* synopsis: r[P2]=P4 */
  9519. #define OP_String 25 /* synopsis: r[P2]='P4' (len=P1) */
  9520. #define OP_Null 26 /* synopsis: r[P2..P3]=NULL */
  9521. #define OP_SoftNull 27 /* synopsis: r[P1]=NULL */
  9522. #define OP_Blob 28 /* synopsis: r[P2]=P4 (len=P1) */
  9523. #define OP_Variable 29 /* synopsis: r[P2]=parameter(P1,P4) */
  9524. #define OP_Move 30 /* synopsis: r[P2@P3]=r[P1@P3] */
  9525. #define OP_Copy 31 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  9526. #define OP_SCopy 32 /* synopsis: r[P2]=r[P1] */
  9527. #define OP_ResultRow 33 /* synopsis: output=r[P1@P2] */
  9528. #define OP_CollSeq 34
  9529. #define OP_Function0 35 /* synopsis: r[P3]=func(r[P2@P5]) */
  9530. #define OP_Function 36 /* synopsis: r[P3]=func(r[P2@P5]) */
  9531. #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
  9532. #define OP_MustBeInt 38
  9533. #define OP_RealAffinity 39
  9534. #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
  9535. #define OP_Permutation 41
  9536. #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  9537. #define OP_Jump 43
  9538. #define OP_Once 44
  9539. #define OP_If 45
  9540. #define OP_IfNot 46
  9541. #define OP_Column 47 /* synopsis: r[P3]=PX */
  9542. #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
  9543. #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  9544. #define OP_Count 50 /* synopsis: r[P2]=count() */
  9545. #define OP_ReadCookie 51
  9546. #define OP_SetCookie 52
  9547. #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
  9548. #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
  9549. #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
  9550. #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
  9551. #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
  9552. #define OP_SorterOpen 58
  9553. #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  9554. #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
  9555. #define OP_Close 61
  9556. #define OP_ColumnsUsed 62
  9557. #define OP_SeekLT 63 /* synopsis: key=r[P3@P4] */
  9558. #define OP_SeekLE 64 /* synopsis: key=r[P3@P4] */
  9559. #define OP_SeekGE 65 /* synopsis: key=r[P3@P4] */
  9560. #define OP_SeekGT 66 /* synopsis: key=r[P3@P4] */
  9561. #define OP_Seek 67 /* synopsis: intkey=r[P2] */
  9562. #define OP_NoConflict 68 /* synopsis: key=r[P3@P4] */
  9563. #define OP_NotFound 69 /* synopsis: key=r[P3@P4] */
  9564. #define OP_Found 70 /* synopsis: key=r[P3@P4] */
  9565. #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  9566. #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  9567. #define OP_NotExists 73 /* synopsis: intkey=r[P3] */
  9568. #define OP_Sequence 74 /* synopsis: r[P2]=cursor[P1].ctr++ */
  9569. #define OP_NewRowid 75 /* synopsis: r[P2]=rowid */
  9570. #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  9571. #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  9572. #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  9573. #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  9574. #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  9575. #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  9576. #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  9577. #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  9578. #define OP_Insert 84 /* synopsis: intkey=r[P3] data=r[P2] */
  9579. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  9580. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  9581. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  9582. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  9583. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  9584. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  9585. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  9586. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  9587. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  9588. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  9589. #define OP_InsertInt 95 /* synopsis: intkey=P3 data=r[P2] */
  9590. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  9591. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  9592. #define OP_Delete 98
  9593. #define OP_ResetCount 99
  9594. #define OP_SorterCompare 100 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  9595. #define OP_SorterData 101 /* synopsis: r[P2]=data */
  9596. #define OP_RowKey 102 /* synopsis: r[P2]=key */
  9597. #define OP_RowData 103 /* synopsis: r[P2]=data */
  9598. #define OP_Rowid 104 /* synopsis: r[P2]=rowid */
  9599. #define OP_NullRow 105
  9600. #define OP_Last 106
  9601. #define OP_SorterSort 107
  9602. #define OP_Sort 108
  9603. #define OP_Rewind 109
  9604. #define OP_SorterInsert 110
  9605. #define OP_IdxInsert 111 /* synopsis: key=r[P2] */
  9606. #define OP_IdxDelete 112 /* synopsis: key=r[P2@P3] */
  9607. #define OP_IdxRowid 113 /* synopsis: r[P2]=rowid */
  9608. #define OP_IdxLE 114 /* synopsis: key=r[P3@P4] */
  9609. #define OP_IdxGT 115 /* synopsis: key=r[P3@P4] */
  9610. #define OP_IdxLT 116 /* synopsis: key=r[P3@P4] */
  9611. #define OP_IdxGE 117 /* synopsis: key=r[P3@P4] */
  9612. #define OP_Destroy 118
  9613. #define OP_Clear 119
  9614. #define OP_ResetSorter 120
  9615. #define OP_CreateIndex 121 /* synopsis: r[P2]=root iDb=P1 */
  9616. #define OP_CreateTable 122 /* synopsis: r[P2]=root iDb=P1 */
  9617. #define OP_ParseSchema 123
  9618. #define OP_LoadAnalysis 124
  9619. #define OP_DropTable 125
  9620. #define OP_DropIndex 126
  9621. #define OP_DropTrigger 127
  9622. #define OP_IntegrityCk 128
  9623. #define OP_RowSetAdd 129 /* synopsis: rowset(P1)=r[P2] */
  9624. #define OP_RowSetRead 130 /* synopsis: r[P3]=rowset(P1) */
  9625. #define OP_RowSetTest 131 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  9626. #define OP_Program 132
  9627. #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  9628. #define OP_Param 134
  9629. #define OP_FkCounter 135 /* synopsis: fkctr[P1]+=P2 */
  9630. #define OP_FkIfZero 136 /* synopsis: if fkctr[P1]==0 goto P2 */
  9631. #define OP_MemMax 137 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  9632. #define OP_IfPos 138 /* synopsis: if r[P1]>0 goto P2 */
  9633. #define OP_IfNeg 139 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2 */
  9634. #define OP_IfNotZero 140 /* synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2 */
  9635. #define OP_DecrJumpZero 141 /* synopsis: if (--r[P1])==0 goto P2 */
  9636. #define OP_JumpZeroIncr 142 /* synopsis: if (r[P1]++)==0 ) goto P2 */
  9637. #define OP_AggStep0 143 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  9638. #define OP_AggStep 144 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  9639. #define OP_AggFinal 145 /* synopsis: accum=r[P1] N=P2 */
  9640. #define OP_IncrVacuum 146
  9641. #define OP_Expire 147
  9642. #define OP_TableLock 148 /* synopsis: iDb=P1 root=P2 write=P3 */
  9643. #define OP_VBegin 149
  9644. #define OP_VCreate 150
  9645. #define OP_VDestroy 151
  9646. #define OP_VOpen 152
  9647. #define OP_VColumn 153 /* synopsis: r[P3]=vcolumn(P2) */
  9648. #define OP_VNext 154
  9649. #define OP_VRename 155
  9650. #define OP_Pagecount 156
  9651. #define OP_MaxPgcnt 157
  9652. #define OP_Init 158 /* synopsis: Start at P2 */
  9653. #define OP_Noop 159
  9654. #define OP_Explain 160
  9655. /* Properties such as "out2" or "jump" that are specified in
  9656. ** comments following the "case" for each opcode in the vdbe.c
  9657. ** are encoded into bitvectors as follows:
  9658. */
  9659. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  9660. #define OPFLG_IN1 0x0002 /* in1: P1 is an input */
  9661. #define OPFLG_IN2 0x0004 /* in2: P2 is an input */
  9662. #define OPFLG_IN3 0x0008 /* in3: P3 is an input */
  9663. #define OPFLG_OUT2 0x0010 /* out2: P2 is an output */
  9664. #define OPFLG_OUT3 0x0020 /* out3: P3 is an output */
  9665. #define OPFLG_INITIALIZER {\
  9666. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01,\
  9667. /* 8 */ 0x01, 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01,\
  9668. /* 16 */ 0x02, 0x01, 0x02, 0x12, 0x03, 0x08, 0x00, 0x10,\
  9669. /* 24 */ 0x10, 0x10, 0x10, 0x00, 0x10, 0x10, 0x00, 0x00,\
  9670. /* 32 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x02,\
  9671. /* 40 */ 0x02, 0x00, 0x00, 0x01, 0x01, 0x03, 0x03, 0x00,\
  9672. /* 48 */ 0x00, 0x00, 0x10, 0x10, 0x08, 0x00, 0x00, 0x00,\
  9673. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09,\
  9674. /* 64 */ 0x09, 0x09, 0x09, 0x04, 0x09, 0x09, 0x09, 0x26,\
  9675. /* 72 */ 0x26, 0x09, 0x10, 0x10, 0x03, 0x03, 0x0b, 0x0b,\
  9676. /* 80 */ 0x0b, 0x0b, 0x0b, 0x0b, 0x00, 0x26, 0x26, 0x26,\
  9677. /* 88 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x26, 0x00,\
  9678. /* 96 */ 0x12, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  9679. /* 104 */ 0x10, 0x00, 0x01, 0x01, 0x01, 0x01, 0x04, 0x04,\
  9680. /* 112 */ 0x00, 0x10, 0x01, 0x01, 0x01, 0x01, 0x10, 0x00,\
  9681. /* 120 */ 0x00, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,\
  9682. /* 128 */ 0x00, 0x06, 0x23, 0x0b, 0x01, 0x10, 0x10, 0x00,\
  9683. /* 136 */ 0x01, 0x04, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00,\
  9684. /* 144 */ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
  9685. /* 152 */ 0x00, 0x00, 0x01, 0x00, 0x10, 0x10, 0x01, 0x00,\
  9686. /* 160 */ 0x00,}
  9687. /************** End of opcodes.h *********************************************/
  9688. /************** Continuing where we left off in vdbe.h ***********************/
  9689. /*
  9690. ** Prototypes for the VDBE interface. See comments on the implementation
  9691. ** for a description of what each of these routines does.
  9692. */
  9693. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  9694. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  9695. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  9696. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  9697. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  9698. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  9699. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
  9700. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  9701. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  9702. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  9703. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  9704. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  9705. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  9706. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  9707. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  9708. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  9709. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  9710. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  9711. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  9712. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  9713. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  9714. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  9715. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  9716. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  9717. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  9718. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  9719. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  9720. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  9721. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  9722. #ifdef SQLITE_DEBUG
  9723. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  9724. #endif
  9725. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  9726. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  9727. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  9728. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  9729. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  9730. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  9731. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  9732. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  9733. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  9734. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  9735. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  9736. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  9737. #ifndef SQLITE_OMIT_TRACE
  9738. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  9739. #endif
  9740. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  9741. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  9742. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  9743. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
  9744. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  9745. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  9746. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  9747. #ifndef SQLITE_OMIT_TRIGGER
  9748. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  9749. #endif
  9750. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  9751. ** each VDBE opcode.
  9752. **
  9753. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  9754. ** comments in VDBE programs that show key decision points in the code
  9755. ** generator.
  9756. */
  9757. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9758. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  9759. # define VdbeComment(X) sqlite3VdbeComment X
  9760. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  9761. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  9762. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  9763. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  9764. # else
  9765. # define VdbeModuleComment(X)
  9766. # endif
  9767. #else
  9768. # define VdbeComment(X)
  9769. # define VdbeNoopComment(X)
  9770. # define VdbeModuleComment(X)
  9771. #endif
  9772. /*
  9773. ** The VdbeCoverage macros are used to set a coverage testing point
  9774. ** for VDBE branch instructions. The coverage testing points are line
  9775. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  9776. ** only works with an amalagmation build. That's ok since a VDBE branch
  9777. ** coverage build designed for testing the test suite only. No application
  9778. ** should ever ship with VDBE branch coverage measuring turned on.
  9779. **
  9780. ** VdbeCoverage(v) // Mark the previously coded instruction
  9781. ** // as a branch
  9782. **
  9783. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  9784. **
  9785. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  9786. **
  9787. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  9788. **
  9789. ** Every VDBE branch operation must be tagged with one of the macros above.
  9790. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  9791. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  9792. ** routine in vdbe.c, alerting the developer to the missed tag.
  9793. */
  9794. #ifdef SQLITE_VDBE_COVERAGE
  9795. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  9796. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  9797. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  9798. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  9799. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  9800. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  9801. #else
  9802. # define VdbeCoverage(v)
  9803. # define VdbeCoverageIf(v,x)
  9804. # define VdbeCoverageAlwaysTaken(v)
  9805. # define VdbeCoverageNeverTaken(v)
  9806. # define VDBE_OFFSET_LINENO(x) 0
  9807. #endif
  9808. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  9809. SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
  9810. #else
  9811. # define sqlite3VdbeScanStatus(a,b,c,d,e)
  9812. #endif
  9813. #endif
  9814. /************** End of vdbe.h ************************************************/
  9815. /************** Continuing where we left off in sqliteInt.h ******************/
  9816. /************** Include pager.h in the middle of sqliteInt.h *****************/
  9817. /************** Begin file pager.h *******************************************/
  9818. /*
  9819. ** 2001 September 15
  9820. **
  9821. ** The author disclaims copyright to this source code. In place of
  9822. ** a legal notice, here is a blessing:
  9823. **
  9824. ** May you do good and not evil.
  9825. ** May you find forgiveness for yourself and forgive others.
  9826. ** May you share freely, never taking more than you give.
  9827. **
  9828. *************************************************************************
  9829. ** This header file defines the interface that the sqlite page cache
  9830. ** subsystem. The page cache subsystem reads and writes a file a page
  9831. ** at a time and provides a journal for rollback.
  9832. */
  9833. #ifndef _PAGER_H_
  9834. #define _PAGER_H_
  9835. /*
  9836. ** Default maximum size for persistent journal files. A negative
  9837. ** value means no limit. This value may be overridden using the
  9838. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  9839. */
  9840. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  9841. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  9842. #endif
  9843. /*
  9844. ** The type used to represent a page number. The first page in a file
  9845. ** is called page 1. 0 is used to represent "not a page".
  9846. */
  9847. typedef u32 Pgno;
  9848. /*
  9849. ** Each open file is managed by a separate instance of the "Pager" structure.
  9850. */
  9851. typedef struct Pager Pager;
  9852. /*
  9853. ** Handle type for pages.
  9854. */
  9855. typedef struct PgHdr DbPage;
  9856. /*
  9857. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  9858. ** reserved for working around a windows/posix incompatibility). It is
  9859. ** used in the journal to signify that the remainder of the journal file
  9860. ** is devoted to storing a master journal name - there are no more pages to
  9861. ** roll back. See comments for function writeMasterJournal() in pager.c
  9862. ** for details.
  9863. */
  9864. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  9865. /*
  9866. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  9867. **
  9868. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  9869. */
  9870. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  9871. #define PAGER_MEMORY 0x0002 /* In-memory database */
  9872. /*
  9873. ** Valid values for the second argument to sqlite3PagerLockingMode().
  9874. */
  9875. #define PAGER_LOCKINGMODE_QUERY -1
  9876. #define PAGER_LOCKINGMODE_NORMAL 0
  9877. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  9878. /*
  9879. ** Numeric constants that encode the journalmode.
  9880. */
  9881. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  9882. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  9883. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  9884. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  9885. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  9886. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  9887. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  9888. /*
  9889. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  9890. */
  9891. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  9892. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  9893. /*
  9894. ** Flags for sqlite3PagerSetFlags()
  9895. */
  9896. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  9897. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  9898. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  9899. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  9900. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  9901. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  9902. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9903. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9904. /*
  9905. ** The remainder of this file contains the declarations of the functions
  9906. ** that make up the Pager sub-system API. See source code comments for
  9907. ** a detailed description of each routine.
  9908. */
  9909. /* Open and close a Pager connection. */
  9910. SQLITE_PRIVATE int sqlite3PagerOpen(
  9911. sqlite3_vfs*,
  9912. Pager **ppPager,
  9913. const char*,
  9914. int,
  9915. int,
  9916. int,
  9917. void(*)(DbPage*)
  9918. );
  9919. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9920. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9921. /* Functions used to configure a Pager object. */
  9922. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9923. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9924. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9925. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9926. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9927. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9928. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9929. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9930. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9931. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9932. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9933. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9934. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9935. /* Functions used to obtain and release page references. */
  9936. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9937. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9938. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9939. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9940. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9941. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  9942. /* Operations on page references. */
  9943. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9944. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9945. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9946. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9947. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9948. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9949. /* Functions used to manage pager transactions and savepoints. */
  9950. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9951. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9952. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9953. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9954. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  9955. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9956. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9957. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9958. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9959. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9960. #ifndef SQLITE_OMIT_WAL
  9961. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9962. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9963. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9964. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9965. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9966. #endif
  9967. #ifdef SQLITE_ENABLE_ZIPVFS
  9968. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9969. #endif
  9970. /* Functions used to query pager state and configuration. */
  9971. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9972. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
  9973. #ifdef SQLITE_DEBUG
  9974. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9975. #endif
  9976. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9977. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9978. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9979. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9980. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9981. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9982. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9983. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9984. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9985. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9986. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9987. /* Functions used to truncate the database file. */
  9988. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9989. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
  9990. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9991. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9992. #endif
  9993. /* Functions to support testing and debugging. */
  9994. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9995. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9996. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9997. #endif
  9998. #ifdef SQLITE_TEST
  9999. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  10000. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  10001. void disable_simulated_io_errors(void);
  10002. void enable_simulated_io_errors(void);
  10003. #else
  10004. # define disable_simulated_io_errors()
  10005. # define enable_simulated_io_errors()
  10006. #endif
  10007. #endif /* _PAGER_H_ */
  10008. /************** End of pager.h ***********************************************/
  10009. /************** Continuing where we left off in sqliteInt.h ******************/
  10010. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  10011. /************** Begin file pcache.h ******************************************/
  10012. /*
  10013. ** 2008 August 05
  10014. **
  10015. ** The author disclaims copyright to this source code. In place of
  10016. ** a legal notice, here is a blessing:
  10017. **
  10018. ** May you do good and not evil.
  10019. ** May you find forgiveness for yourself and forgive others.
  10020. ** May you share freely, never taking more than you give.
  10021. **
  10022. *************************************************************************
  10023. ** This header file defines the interface that the sqlite page cache
  10024. ** subsystem.
  10025. */
  10026. #ifndef _PCACHE_H_
  10027. typedef struct PgHdr PgHdr;
  10028. typedef struct PCache PCache;
  10029. /*
  10030. ** Every page in the cache is controlled by an instance of the following
  10031. ** structure.
  10032. */
  10033. struct PgHdr {
  10034. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  10035. void *pData; /* Page data */
  10036. void *pExtra; /* Extra content */
  10037. PgHdr *pDirty; /* Transient list of dirty pages */
  10038. Pager *pPager; /* The pager this page is part of */
  10039. Pgno pgno; /* Page number for this page */
  10040. #ifdef SQLITE_CHECK_PAGES
  10041. u32 pageHash; /* Hash of page content */
  10042. #endif
  10043. u16 flags; /* PGHDR flags defined below */
  10044. /**********************************************************************
  10045. ** Elements above are public. All that follows is private to pcache.c
  10046. ** and should not be accessed by other modules.
  10047. */
  10048. i16 nRef; /* Number of users of this page */
  10049. PCache *pCache; /* Cache that owns this page */
  10050. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  10051. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  10052. };
  10053. /* Bit values for PgHdr.flags */
  10054. #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
  10055. #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
  10056. #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
  10057. #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
  10058. ** writing this page to the database */
  10059. #define PGHDR_NEED_READ 0x010 /* Content is unread */
  10060. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  10061. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  10062. /* Initialize and shutdown the page cache subsystem */
  10063. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  10064. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  10065. /* Page cache buffer management:
  10066. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  10067. */
  10068. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  10069. /* Create a new pager cache.
  10070. ** Under memory stress, invoke xStress to try to make pages clean.
  10071. ** Only clean and unpinned pages can be reclaimed.
  10072. */
  10073. SQLITE_PRIVATE int sqlite3PcacheOpen(
  10074. int szPage, /* Size of every page */
  10075. int szExtra, /* Extra space associated with each page */
  10076. int bPurgeable, /* True if pages are on backing store */
  10077. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  10078. void *pStress, /* Argument to xStress */
  10079. PCache *pToInit /* Preallocated space for the PCache */
  10080. );
  10081. /* Modify the page-size after the cache has been created. */
  10082. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  10083. /* Return the size in bytes of a PCache object. Used to preallocate
  10084. ** storage space.
  10085. */
  10086. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  10087. /* One release per successful fetch. Page is pinned until released.
  10088. ** Reference counted.
  10089. */
  10090. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  10091. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  10092. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  10093. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  10094. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  10095. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  10096. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  10097. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  10098. /* Change a page number. Used by incr-vacuum. */
  10099. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  10100. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  10101. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  10102. /* Get a list of all dirty pages in the cache, sorted by page number */
  10103. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  10104. /* Reset and close the cache object */
  10105. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  10106. /* Clear flags from pages of the page cache */
  10107. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  10108. /* Discard the contents of the cache */
  10109. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  10110. /* Return the total number of outstanding page references */
  10111. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  10112. /* Increment the reference count of an existing page */
  10113. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  10114. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  10115. /* Return the total number of pages stored in the cache */
  10116. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  10117. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  10118. /* Iterate through all dirty pages currently stored in the cache. This
  10119. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  10120. ** library is built.
  10121. */
  10122. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  10123. #endif
  10124. /* Set and get the suggested cache-size for the specified pager-cache.
  10125. **
  10126. ** If no global maximum is configured, then the system attempts to limit
  10127. ** the total number of pages cached by purgeable pager-caches to the sum
  10128. ** of the suggested cache-sizes.
  10129. */
  10130. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  10131. #ifdef SQLITE_TEST
  10132. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  10133. #endif
  10134. /* Free up as much memory as possible from the page cache */
  10135. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  10136. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  10137. /* Try to return memory used by the pcache module to the main memory heap */
  10138. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  10139. #endif
  10140. #ifdef SQLITE_TEST
  10141. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  10142. #endif
  10143. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  10144. /* Return the header size */
  10145. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
  10146. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
  10147. #endif /* _PCACHE_H_ */
  10148. /************** End of pcache.h **********************************************/
  10149. /************** Continuing where we left off in sqliteInt.h ******************/
  10150. /************** Include os.h in the middle of sqliteInt.h ********************/
  10151. /************** Begin file os.h **********************************************/
  10152. /*
  10153. ** 2001 September 16
  10154. **
  10155. ** The author disclaims copyright to this source code. In place of
  10156. ** a legal notice, here is a blessing:
  10157. **
  10158. ** May you do good and not evil.
  10159. ** May you find forgiveness for yourself and forgive others.
  10160. ** May you share freely, never taking more than you give.
  10161. **
  10162. ******************************************************************************
  10163. **
  10164. ** This header file (together with is companion C source-code file
  10165. ** "os.c") attempt to abstract the underlying operating system so that
  10166. ** the SQLite library will work on both POSIX and windows systems.
  10167. **
  10168. ** This header file is #include-ed by sqliteInt.h and thus ends up
  10169. ** being included by every source file.
  10170. */
  10171. #ifndef _SQLITE_OS_H_
  10172. #define _SQLITE_OS_H_
  10173. /*
  10174. ** Attempt to automatically detect the operating system and setup the
  10175. ** necessary pre-processor macros for it.
  10176. */
  10177. /************** Include os_setup.h in the middle of os.h *********************/
  10178. /************** Begin file os_setup.h ****************************************/
  10179. /*
  10180. ** 2013 November 25
  10181. **
  10182. ** The author disclaims copyright to this source code. In place of
  10183. ** a legal notice, here is a blessing:
  10184. **
  10185. ** May you do good and not evil.
  10186. ** May you find forgiveness for yourself and forgive others.
  10187. ** May you share freely, never taking more than you give.
  10188. **
  10189. ******************************************************************************
  10190. **
  10191. ** This file contains pre-processor directives related to operating system
  10192. ** detection and/or setup.
  10193. */
  10194. #ifndef _OS_SETUP_H_
  10195. #define _OS_SETUP_H_
  10196. /*
  10197. ** Figure out if we are dealing with Unix, Windows, or some other operating
  10198. ** system.
  10199. **
  10200. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  10201. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  10202. ** the three will be 1. The other two will be 0.
  10203. */
  10204. #if defined(SQLITE_OS_OTHER)
  10205. # if SQLITE_OS_OTHER==1
  10206. # undef SQLITE_OS_UNIX
  10207. # define SQLITE_OS_UNIX 0
  10208. # undef SQLITE_OS_WIN
  10209. # define SQLITE_OS_WIN 0
  10210. # else
  10211. # undef SQLITE_OS_OTHER
  10212. # endif
  10213. #endif
  10214. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  10215. # define SQLITE_OS_OTHER 0
  10216. # ifndef SQLITE_OS_WIN
  10217. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  10218. defined(__MINGW32__) || defined(__BORLANDC__)
  10219. # define SQLITE_OS_WIN 1
  10220. # define SQLITE_OS_UNIX 0
  10221. # else
  10222. # define SQLITE_OS_WIN 0
  10223. # define SQLITE_OS_UNIX 1
  10224. # endif
  10225. # else
  10226. # define SQLITE_OS_UNIX 0
  10227. # endif
  10228. #else
  10229. # ifndef SQLITE_OS_WIN
  10230. # define SQLITE_OS_WIN 0
  10231. # endif
  10232. #endif
  10233. #endif /* _OS_SETUP_H_ */
  10234. /************** End of os_setup.h ********************************************/
  10235. /************** Continuing where we left off in os.h *************************/
  10236. /* If the SET_FULLSYNC macro is not defined above, then make it
  10237. ** a no-op
  10238. */
  10239. #ifndef SET_FULLSYNC
  10240. # define SET_FULLSYNC(x,y)
  10241. #endif
  10242. /*
  10243. ** The default size of a disk sector
  10244. */
  10245. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  10246. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  10247. #endif
  10248. /*
  10249. ** Temporary files are named starting with this prefix followed by 16 random
  10250. ** alphanumeric characters, and no file extension. They are stored in the
  10251. ** OS's standard temporary file directory, and are deleted prior to exit.
  10252. ** If sqlite is being embedded in another program, you may wish to change the
  10253. ** prefix to reflect your program's name, so that if your program exits
  10254. ** prematurely, old temporary files can be easily identified. This can be done
  10255. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  10256. **
  10257. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  10258. ** Mcafee started using SQLite in their anti-virus product and it
  10259. ** started putting files with the "sqlite" name in the c:/temp folder.
  10260. ** This annoyed many windows users. Those users would then do a
  10261. ** Google search for "sqlite", find the telephone numbers of the
  10262. ** developers and call to wake them up at night and complain.
  10263. ** For this reason, the default name prefix is changed to be "sqlite"
  10264. ** spelled backwards. So the temp files are still identified, but
  10265. ** anybody smart enough to figure out the code is also likely smart
  10266. ** enough to know that calling the developer will not help get rid
  10267. ** of the file.
  10268. */
  10269. #ifndef SQLITE_TEMP_FILE_PREFIX
  10270. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  10271. #endif
  10272. /*
  10273. ** The following values may be passed as the second argument to
  10274. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  10275. **
  10276. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  10277. ** RESERVED: A single process may hold a RESERVED lock on a file at
  10278. ** any time. Other processes may hold and obtain new SHARED locks.
  10279. ** PENDING: A single process may hold a PENDING lock on a file at
  10280. ** any one time. Existing SHARED locks may persist, but no new
  10281. ** SHARED locks may be obtained by other processes.
  10282. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  10283. **
  10284. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  10285. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  10286. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  10287. ** sqlite3OsLock().
  10288. */
  10289. #define NO_LOCK 0
  10290. #define SHARED_LOCK 1
  10291. #define RESERVED_LOCK 2
  10292. #define PENDING_LOCK 3
  10293. #define EXCLUSIVE_LOCK 4
  10294. /*
  10295. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  10296. **
  10297. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  10298. ** those functions are not available. So we use only LockFile() and
  10299. ** UnlockFile().
  10300. **
  10301. ** LockFile() prevents not just writing but also reading by other processes.
  10302. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  10303. ** byte out of a specific range of bytes. The lock byte is obtained at
  10304. ** random so two separate readers can probably access the file at the
  10305. ** same time, unless they are unlucky and choose the same lock byte.
  10306. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  10307. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  10308. ** a single byte of the file that is designated as the reserved lock byte.
  10309. ** A PENDING_LOCK is obtained by locking a designated byte different from
  10310. ** the RESERVED_LOCK byte.
  10311. **
  10312. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  10313. ** which means we can use reader/writer locks. When reader/writer locks
  10314. ** are used, the lock is placed on the same range of bytes that is used
  10315. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  10316. ** will support two or more Win95 readers or two or more WinNT readers.
  10317. ** But a single Win95 reader will lock out all WinNT readers and a single
  10318. ** WinNT reader will lock out all other Win95 readers.
  10319. **
  10320. ** The following #defines specify the range of bytes used for locking.
  10321. ** SHARED_SIZE is the number of bytes available in the pool from which
  10322. ** a random byte is selected for a shared lock. The pool of bytes for
  10323. ** shared locks begins at SHARED_FIRST.
  10324. **
  10325. ** The same locking strategy and
  10326. ** byte ranges are used for Unix. This leaves open the possibility of having
  10327. ** clients on win95, winNT, and unix all talking to the same shared file
  10328. ** and all locking correctly. To do so would require that samba (or whatever
  10329. ** tool is being used for file sharing) implements locks correctly between
  10330. ** windows and unix. I'm guessing that isn't likely to happen, but by
  10331. ** using the same locking range we are at least open to the possibility.
  10332. **
  10333. ** Locking in windows is manditory. For this reason, we cannot store
  10334. ** actual data in the bytes used for locking. The pager never allocates
  10335. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  10336. ** that all locks will fit on a single page even at the minimum page size.
  10337. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  10338. ** is set high so that we don't have to allocate an unused page except
  10339. ** for very large databases. But one should test the page skipping logic
  10340. ** by setting PENDING_BYTE low and running the entire regression suite.
  10341. **
  10342. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  10343. ** file format. Depending on how it is changed, you might not notice
  10344. ** the incompatibility right away, even running a full regression test.
  10345. ** The default location of PENDING_BYTE is the first byte past the
  10346. ** 1GB boundary.
  10347. **
  10348. */
  10349. #ifdef SQLITE_OMIT_WSD
  10350. # define PENDING_BYTE (0x40000000)
  10351. #else
  10352. # define PENDING_BYTE sqlite3PendingByte
  10353. #endif
  10354. #define RESERVED_BYTE (PENDING_BYTE+1)
  10355. #define SHARED_FIRST (PENDING_BYTE+2)
  10356. #define SHARED_SIZE 510
  10357. /*
  10358. ** Wrapper around OS specific sqlite3_os_init() function.
  10359. */
  10360. SQLITE_PRIVATE int sqlite3OsInit(void);
  10361. /*
  10362. ** Functions for accessing sqlite3_file methods
  10363. */
  10364. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  10365. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  10366. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  10367. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  10368. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  10369. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  10370. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  10371. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  10372. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  10373. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  10374. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  10375. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  10376. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  10377. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  10378. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  10379. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  10380. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  10381. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  10382. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  10383. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  10384. /*
  10385. ** Functions for accessing sqlite3_vfs methods
  10386. */
  10387. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  10388. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  10389. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  10390. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  10391. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  10392. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  10393. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  10394. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  10395. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  10396. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  10397. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  10398. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  10399. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  10400. /*
  10401. ** Convenience functions for opening and closing files using
  10402. ** sqlite3_malloc() to obtain space for the file-handle structure.
  10403. */
  10404. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  10405. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  10406. #endif /* _SQLITE_OS_H_ */
  10407. /************** End of os.h **************************************************/
  10408. /************** Continuing where we left off in sqliteInt.h ******************/
  10409. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  10410. /************** Begin file mutex.h *******************************************/
  10411. /*
  10412. ** 2007 August 28
  10413. **
  10414. ** The author disclaims copyright to this source code. In place of
  10415. ** a legal notice, here is a blessing:
  10416. **
  10417. ** May you do good and not evil.
  10418. ** May you find forgiveness for yourself and forgive others.
  10419. ** May you share freely, never taking more than you give.
  10420. **
  10421. *************************************************************************
  10422. **
  10423. ** This file contains the common header for all mutex implementations.
  10424. ** The sqliteInt.h header #includes this file so that it is available
  10425. ** to all source files. We break it out in an effort to keep the code
  10426. ** better organized.
  10427. **
  10428. ** NOTE: source files should *not* #include this header file directly.
  10429. ** Source files should #include the sqliteInt.h file and let that file
  10430. ** include this one indirectly.
  10431. */
  10432. /*
  10433. ** Figure out what version of the code to use. The choices are
  10434. **
  10435. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  10436. ** mutexes implementation cannot be overridden
  10437. ** at start-time.
  10438. **
  10439. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  10440. ** mutual exclusion is provided. But this
  10441. ** implementation can be overridden at
  10442. ** start-time.
  10443. **
  10444. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  10445. **
  10446. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  10447. */
  10448. #if !SQLITE_THREADSAFE
  10449. # define SQLITE_MUTEX_OMIT
  10450. #endif
  10451. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  10452. # if SQLITE_OS_UNIX
  10453. # define SQLITE_MUTEX_PTHREADS
  10454. # elif SQLITE_OS_WIN
  10455. # define SQLITE_MUTEX_W32
  10456. # else
  10457. # define SQLITE_MUTEX_NOOP
  10458. # endif
  10459. #endif
  10460. #ifdef SQLITE_MUTEX_OMIT
  10461. /*
  10462. ** If this is a no-op implementation, implement everything as macros.
  10463. */
  10464. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  10465. #define sqlite3_mutex_free(X)
  10466. #define sqlite3_mutex_enter(X)
  10467. #define sqlite3_mutex_try(X) SQLITE_OK
  10468. #define sqlite3_mutex_leave(X)
  10469. #define sqlite3_mutex_held(X) ((void)(X),1)
  10470. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  10471. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  10472. #define sqlite3MutexInit() SQLITE_OK
  10473. #define sqlite3MutexEnd()
  10474. #define MUTEX_LOGIC(X)
  10475. #else
  10476. #define MUTEX_LOGIC(X) X
  10477. #endif /* defined(SQLITE_MUTEX_OMIT) */
  10478. /************** End of mutex.h ***********************************************/
  10479. /************** Continuing where we left off in sqliteInt.h ******************/
  10480. /*
  10481. ** Each database file to be accessed by the system is an instance
  10482. ** of the following structure. There are normally two of these structures
  10483. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  10484. ** aDb[1] is the database file used to hold temporary tables. Additional
  10485. ** databases may be attached.
  10486. */
  10487. struct Db {
  10488. char *zName; /* Name of this database */
  10489. Btree *pBt; /* The B*Tree structure for this database file */
  10490. u8 safety_level; /* How aggressive at syncing data to disk */
  10491. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  10492. };
  10493. /*
  10494. ** An instance of the following structure stores a database schema.
  10495. **
  10496. ** Most Schema objects are associated with a Btree. The exception is
  10497. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  10498. ** In shared cache mode, a single Schema object can be shared by multiple
  10499. ** Btrees that refer to the same underlying BtShared object.
  10500. **
  10501. ** Schema objects are automatically deallocated when the last Btree that
  10502. ** references them is destroyed. The TEMP Schema is manually freed by
  10503. ** sqlite3_close().
  10504. *
  10505. ** A thread must be holding a mutex on the corresponding Btree in order
  10506. ** to access Schema content. This implies that the thread must also be
  10507. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  10508. ** For a TEMP Schema, only the connection mutex is required.
  10509. */
  10510. struct Schema {
  10511. int schema_cookie; /* Database schema version number for this file */
  10512. int iGeneration; /* Generation counter. Incremented with each change */
  10513. Hash tblHash; /* All tables indexed by name */
  10514. Hash idxHash; /* All (named) indices indexed by name */
  10515. Hash trigHash; /* All triggers indexed by name */
  10516. Hash fkeyHash; /* All foreign keys by referenced table name */
  10517. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  10518. u8 file_format; /* Schema format version for this file */
  10519. u8 enc; /* Text encoding used by this database */
  10520. u16 schemaFlags; /* Flags associated with this schema */
  10521. int cache_size; /* Number of pages to use in the cache */
  10522. };
  10523. /*
  10524. ** These macros can be used to test, set, or clear bits in the
  10525. ** Db.pSchema->flags field.
  10526. */
  10527. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  10528. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  10529. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  10530. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  10531. /*
  10532. ** Allowed values for the DB.pSchema->flags field.
  10533. **
  10534. ** The DB_SchemaLoaded flag is set after the database schema has been
  10535. ** read into internal hash tables.
  10536. **
  10537. ** DB_UnresetViews means that one or more views have column names that
  10538. ** have been filled out. If the schema changes, these column names might
  10539. ** changes and so the view will need to be reset.
  10540. */
  10541. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  10542. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  10543. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  10544. /*
  10545. ** The number of different kinds of things that can be limited
  10546. ** using the sqlite3_limit() interface.
  10547. */
  10548. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  10549. /*
  10550. ** Lookaside malloc is a set of fixed-size buffers that can be used
  10551. ** to satisfy small transient memory allocation requests for objects
  10552. ** associated with a particular database connection. The use of
  10553. ** lookaside malloc provides a significant performance enhancement
  10554. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  10555. ** SQL statements.
  10556. **
  10557. ** The Lookaside structure holds configuration information about the
  10558. ** lookaside malloc subsystem. Each available memory allocation in
  10559. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  10560. ** objects.
  10561. **
  10562. ** Lookaside allocations are only allowed for objects that are associated
  10563. ** with a particular database connection. Hence, schema information cannot
  10564. ** be stored in lookaside because in shared cache mode the schema information
  10565. ** is shared by multiple database connections. Therefore, while parsing
  10566. ** schema information, the Lookaside.bEnabled flag is cleared so that
  10567. ** lookaside allocations are not used to construct the schema objects.
  10568. */
  10569. struct Lookaside {
  10570. u16 sz; /* Size of each buffer in bytes */
  10571. u8 bEnabled; /* False to disable new lookaside allocations */
  10572. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  10573. int nOut; /* Number of buffers currently checked out */
  10574. int mxOut; /* Highwater mark for nOut */
  10575. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  10576. LookasideSlot *pFree; /* List of available buffers */
  10577. void *pStart; /* First byte of available memory space */
  10578. void *pEnd; /* First byte past end of available space */
  10579. };
  10580. struct LookasideSlot {
  10581. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  10582. };
  10583. /*
  10584. ** A hash table for function definitions.
  10585. **
  10586. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  10587. ** Collisions are on the FuncDef.pHash chain.
  10588. */
  10589. struct FuncDefHash {
  10590. FuncDef *a[23]; /* Hash table for functions */
  10591. };
  10592. #ifdef SQLITE_USER_AUTHENTICATION
  10593. /*
  10594. ** Information held in the "sqlite3" database connection object and used
  10595. ** to manage user authentication.
  10596. */
  10597. typedef struct sqlite3_userauth sqlite3_userauth;
  10598. struct sqlite3_userauth {
  10599. u8 authLevel; /* Current authentication level */
  10600. int nAuthPW; /* Size of the zAuthPW in bytes */
  10601. char *zAuthPW; /* Password used to authenticate */
  10602. char *zAuthUser; /* User name used to authenticate */
  10603. };
  10604. /* Allowed values for sqlite3_userauth.authLevel */
  10605. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  10606. #define UAUTH_Fail 1 /* User authentication failed */
  10607. #define UAUTH_User 2 /* Authenticated as a normal user */
  10608. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  10609. /* Functions used only by user authorization logic */
  10610. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  10611. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  10612. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  10613. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  10614. #endif /* SQLITE_USER_AUTHENTICATION */
  10615. /*
  10616. ** typedef for the authorization callback function.
  10617. */
  10618. #ifdef SQLITE_USER_AUTHENTICATION
  10619. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10620. const char*, const char*);
  10621. #else
  10622. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10623. const char*);
  10624. #endif
  10625. /*
  10626. ** Each database connection is an instance of the following structure.
  10627. */
  10628. struct sqlite3 {
  10629. sqlite3_vfs *pVfs; /* OS Interface */
  10630. struct Vdbe *pVdbe; /* List of active virtual machines */
  10631. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  10632. sqlite3_mutex *mutex; /* Connection mutex */
  10633. Db *aDb; /* All backends */
  10634. int nDb; /* Number of backends currently in use */
  10635. int flags; /* Miscellaneous flags. See below */
  10636. i64 lastRowid; /* ROWID of most recent insert (see above) */
  10637. i64 szMmap; /* Default mmap_size setting */
  10638. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  10639. int errCode; /* Most recent error code (SQLITE_*) */
  10640. int errMask; /* & result codes with this before returning */
  10641. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  10642. u8 enc; /* Text encoding */
  10643. u8 autoCommit; /* The auto-commit flag. */
  10644. u8 temp_store; /* 1: file 2: memory 0: default */
  10645. u8 mallocFailed; /* True if we have seen a malloc failure */
  10646. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  10647. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  10648. u8 suppressErr; /* Do not issue error messages if true */
  10649. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  10650. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  10651. int nextPagesize; /* Pagesize after VACUUM if >0 */
  10652. u32 magic; /* Magic number for detect library misuse */
  10653. int nChange; /* Value returned by sqlite3_changes() */
  10654. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  10655. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  10656. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  10657. struct sqlite3InitInfo { /* Information used during initialization */
  10658. int newTnum; /* Rootpage of table being initialized */
  10659. u8 iDb; /* Which db file is being initialized */
  10660. u8 busy; /* TRUE if currently initializing */
  10661. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  10662. u8 imposterTable; /* Building an imposter table */
  10663. } init;
  10664. int nVdbeActive; /* Number of VDBEs currently running */
  10665. int nVdbeRead; /* Number of active VDBEs that read or write */
  10666. int nVdbeWrite; /* Number of active VDBEs that read and write */
  10667. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  10668. int nVDestroy; /* Number of active OP_VDestroy operations */
  10669. int nExtension; /* Number of loaded extensions */
  10670. void **aExtension; /* Array of shared library handles */
  10671. void (*xTrace)(void*,const char*); /* Trace function */
  10672. void *pTraceArg; /* Argument to the trace function */
  10673. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  10674. void *pProfileArg; /* Argument to profile function */
  10675. void *pCommitArg; /* Argument to xCommitCallback() */
  10676. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  10677. void *pRollbackArg; /* Argument to xRollbackCallback() */
  10678. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  10679. void *pUpdateArg;
  10680. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  10681. #ifndef SQLITE_OMIT_WAL
  10682. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  10683. void *pWalArg;
  10684. #endif
  10685. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  10686. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  10687. void *pCollNeededArg;
  10688. sqlite3_value *pErr; /* Most recent error message */
  10689. union {
  10690. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  10691. double notUsed1; /* Spacer */
  10692. } u1;
  10693. Lookaside lookaside; /* Lookaside malloc configuration */
  10694. #ifndef SQLITE_OMIT_AUTHORIZATION
  10695. sqlite3_xauth xAuth; /* Access authorization function */
  10696. void *pAuthArg; /* 1st argument to the access auth function */
  10697. #endif
  10698. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  10699. int (*xProgress)(void *); /* The progress callback */
  10700. void *pProgressArg; /* Argument to the progress callback */
  10701. unsigned nProgressOps; /* Number of opcodes for progress callback */
  10702. #endif
  10703. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10704. int nVTrans; /* Allocated size of aVTrans */
  10705. Hash aModule; /* populated by sqlite3_create_module() */
  10706. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  10707. VTable **aVTrans; /* Virtual tables with open transactions */
  10708. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  10709. #endif
  10710. FuncDefHash aFunc; /* Hash table of connection functions */
  10711. Hash aCollSeq; /* All collating sequences */
  10712. BusyHandler busyHandler; /* Busy callback */
  10713. Db aDbStatic[2]; /* Static space for the 2 default backends */
  10714. Savepoint *pSavepoint; /* List of active savepoints */
  10715. int busyTimeout; /* Busy handler timeout, in msec */
  10716. int nSavepoint; /* Number of non-transaction savepoints */
  10717. int nStatement; /* Number of nested statement-transactions */
  10718. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  10719. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  10720. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  10721. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  10722. /* The following variables are all protected by the STATIC_MASTER
  10723. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  10724. **
  10725. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  10726. ** unlock so that it can proceed.
  10727. **
  10728. ** When X.pBlockingConnection==Y, that means that something that X tried
  10729. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  10730. ** held by Y.
  10731. */
  10732. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  10733. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  10734. void *pUnlockArg; /* Argument to xUnlockNotify */
  10735. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  10736. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  10737. #endif
  10738. #ifdef SQLITE_USER_AUTHENTICATION
  10739. sqlite3_userauth auth; /* User authentication information */
  10740. #endif
  10741. };
  10742. /*
  10743. ** A macro to discover the encoding of a database.
  10744. */
  10745. #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
  10746. #define ENC(db) ((db)->enc)
  10747. /*
  10748. ** Possible values for the sqlite3.flags.
  10749. */
  10750. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  10751. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  10752. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  10753. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  10754. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  10755. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  10756. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  10757. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  10758. /* DELETE, or UPDATE and return */
  10759. /* the count using a callback. */
  10760. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  10761. /* result set is empty */
  10762. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  10763. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  10764. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  10765. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  10766. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  10767. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  10768. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  10769. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  10770. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  10771. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  10772. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  10773. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  10774. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  10775. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  10776. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  10777. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  10778. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  10779. #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
  10780. #define SQLITE_Vacuum 0x08000000 /* Currently in a VACUUM */
  10781. #define SQLITE_CellSizeCk 0x10000000 /* Check btree cell sizes on load */
  10782. /*
  10783. ** Bits of the sqlite3.dbOptFlags field that are used by the
  10784. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  10785. ** selectively disable various optimizations.
  10786. */
  10787. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  10788. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  10789. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  10790. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  10791. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  10792. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  10793. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  10794. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  10795. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  10796. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  10797. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  10798. #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
  10799. #define SQLITE_AllOpts 0xffff /* All optimizations */
  10800. /*
  10801. ** Macros for testing whether or not optimizations are enabled or disabled.
  10802. */
  10803. #ifndef SQLITE_OMIT_BUILTIN_TEST
  10804. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  10805. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  10806. #else
  10807. #define OptimizationDisabled(db, mask) 0
  10808. #define OptimizationEnabled(db, mask) 1
  10809. #endif
  10810. /*
  10811. ** Return true if it OK to factor constant expressions into the initialization
  10812. ** code. The argument is a Parse object for the code generator.
  10813. */
  10814. #define ConstFactorOk(P) ((P)->okConstFactor)
  10815. /*
  10816. ** Possible values for the sqlite.magic field.
  10817. ** The numbers are obtained at random and have no special meaning, other
  10818. ** than being distinct from one another.
  10819. */
  10820. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  10821. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  10822. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  10823. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  10824. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  10825. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  10826. /*
  10827. ** Each SQL function is defined by an instance of the following
  10828. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  10829. ** hash table. When multiple functions have the same name, the hash table
  10830. ** points to a linked list of these structures.
  10831. */
  10832. struct FuncDef {
  10833. i16 nArg; /* Number of arguments. -1 means unlimited */
  10834. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  10835. void *pUserData; /* User data parameter */
  10836. FuncDef *pNext; /* Next function with same name */
  10837. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  10838. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  10839. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  10840. char *zName; /* SQL name of the function. */
  10841. FuncDef *pHash; /* Next with a different name but the same hash */
  10842. FuncDestructor *pDestructor; /* Reference counted destructor function */
  10843. };
  10844. /*
  10845. ** This structure encapsulates a user-function destructor callback (as
  10846. ** configured using create_function_v2()) and a reference counter. When
  10847. ** create_function_v2() is called to create a function with a destructor,
  10848. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  10849. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  10850. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  10851. ** member of each of the new FuncDef objects is set to point to the allocated
  10852. ** FuncDestructor.
  10853. **
  10854. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  10855. ** count on this object is decremented. When it reaches 0, the destructor
  10856. ** is invoked and the FuncDestructor structure freed.
  10857. */
  10858. struct FuncDestructor {
  10859. int nRef;
  10860. void (*xDestroy)(void *);
  10861. void *pUserData;
  10862. };
  10863. /*
  10864. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  10865. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  10866. ** are assert() statements in the code to verify this.
  10867. */
  10868. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  10869. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  10870. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  10871. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  10872. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  10873. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  10874. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  10875. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  10876. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  10877. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  10878. #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
  10879. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  10880. /*
  10881. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  10882. ** used to create the initializers for the FuncDef structures.
  10883. **
  10884. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  10885. ** Used to create a scalar function definition of a function zName
  10886. ** implemented by C function xFunc that accepts nArg arguments. The
  10887. ** value passed as iArg is cast to a (void*) and made available
  10888. ** as the user-data (sqlite3_user_data()) for the function. If
  10889. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  10890. **
  10891. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  10892. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  10893. **
  10894. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  10895. ** Used to create an aggregate function definition implemented by
  10896. ** the C functions xStep and xFinal. The first four parameters
  10897. ** are interpreted in the same way as the first 4 parameters to
  10898. ** FUNCTION().
  10899. **
  10900. ** LIKEFUNC(zName, nArg, pArg, flags)
  10901. ** Used to create a scalar function definition of a function zName
  10902. ** that accepts nArg arguments and is implemented by a call to C
  10903. ** function likeFunc. Argument pArg is cast to a (void *) and made
  10904. ** available as the function user-data (sqlite3_user_data()). The
  10905. ** FuncDef.flags variable is set to the value passed as the flags
  10906. ** parameter.
  10907. */
  10908. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10909. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10910. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10911. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10912. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10913. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10914. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  10915. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  10916. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10917. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  10918. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10919. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  10920. #define LIKEFUNC(zName, nArg, arg, flags) \
  10921. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  10922. (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  10923. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  10924. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  10925. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10926. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  10927. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  10928. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10929. /*
  10930. ** All current savepoints are stored in a linked list starting at
  10931. ** sqlite3.pSavepoint. The first element in the list is the most recently
  10932. ** opened savepoint. Savepoints are added to the list by the vdbe
  10933. ** OP_Savepoint instruction.
  10934. */
  10935. struct Savepoint {
  10936. char *zName; /* Savepoint name (nul-terminated) */
  10937. i64 nDeferredCons; /* Number of deferred fk violations */
  10938. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  10939. Savepoint *pNext; /* Parent savepoint (if any) */
  10940. };
  10941. /*
  10942. ** The following are used as the second parameter to sqlite3Savepoint(),
  10943. ** and as the P1 argument to the OP_Savepoint instruction.
  10944. */
  10945. #define SAVEPOINT_BEGIN 0
  10946. #define SAVEPOINT_RELEASE 1
  10947. #define SAVEPOINT_ROLLBACK 2
  10948. /*
  10949. ** Each SQLite module (virtual table definition) is defined by an
  10950. ** instance of the following structure, stored in the sqlite3.aModule
  10951. ** hash table.
  10952. */
  10953. struct Module {
  10954. const sqlite3_module *pModule; /* Callback pointers */
  10955. const char *zName; /* Name passed to create_module() */
  10956. void *pAux; /* pAux passed to create_module() */
  10957. void (*xDestroy)(void *); /* Module destructor function */
  10958. };
  10959. /*
  10960. ** information about each column of an SQL table is held in an instance
  10961. ** of this structure.
  10962. */
  10963. struct Column {
  10964. char *zName; /* Name of this column */
  10965. Expr *pDflt; /* Default value of this column */
  10966. char *zDflt; /* Original text of the default value */
  10967. char *zType; /* Data type for this column */
  10968. char *zColl; /* Collating sequence. If NULL, use the default */
  10969. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10970. char affinity; /* One of the SQLITE_AFF_... values */
  10971. u8 szEst; /* Estimated size of this column. INT==1 */
  10972. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10973. };
  10974. /* Allowed values for Column.colFlags:
  10975. */
  10976. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10977. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10978. /*
  10979. ** A "Collating Sequence" is defined by an instance of the following
  10980. ** structure. Conceptually, a collating sequence consists of a name and
  10981. ** a comparison routine that defines the order of that sequence.
  10982. **
  10983. ** If CollSeq.xCmp is NULL, it means that the
  10984. ** collating sequence is undefined. Indices built on an undefined
  10985. ** collating sequence may not be read or written.
  10986. */
  10987. struct CollSeq {
  10988. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10989. u8 enc; /* Text encoding handled by xCmp() */
  10990. void *pUser; /* First argument to xCmp() */
  10991. int (*xCmp)(void*,int, const void*, int, const void*);
  10992. void (*xDel)(void*); /* Destructor for pUser */
  10993. };
  10994. /*
  10995. ** A sort order can be either ASC or DESC.
  10996. */
  10997. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10998. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10999. /*
  11000. ** Column affinity types.
  11001. **
  11002. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  11003. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  11004. ** the speed a little by numbering the values consecutively.
  11005. **
  11006. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  11007. ** when multiple affinity types are concatenated into a string and
  11008. ** used as the P4 operand, they will be more readable.
  11009. **
  11010. ** Note also that the numeric types are grouped together so that testing
  11011. ** for a numeric type is a single comparison. And the BLOB type is first.
  11012. */
  11013. #define SQLITE_AFF_BLOB 'A'
  11014. #define SQLITE_AFF_TEXT 'B'
  11015. #define SQLITE_AFF_NUMERIC 'C'
  11016. #define SQLITE_AFF_INTEGER 'D'
  11017. #define SQLITE_AFF_REAL 'E'
  11018. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  11019. /*
  11020. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  11021. ** affinity value.
  11022. */
  11023. #define SQLITE_AFF_MASK 0x47
  11024. /*
  11025. ** Additional bit values that can be ORed with an affinity without
  11026. ** changing the affinity.
  11027. **
  11028. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  11029. ** It causes an assert() to fire if either operand to a comparison
  11030. ** operator is NULL. It is added to certain comparison operators to
  11031. ** prove that the operands are always NOT NULL.
  11032. */
  11033. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  11034. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  11035. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  11036. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  11037. /*
  11038. ** An object of this type is created for each virtual table present in
  11039. ** the database schema.
  11040. **
  11041. ** If the database schema is shared, then there is one instance of this
  11042. ** structure for each database connection (sqlite3*) that uses the shared
  11043. ** schema. This is because each database connection requires its own unique
  11044. ** instance of the sqlite3_vtab* handle used to access the virtual table
  11045. ** implementation. sqlite3_vtab* handles can not be shared between
  11046. ** database connections, even when the rest of the in-memory database
  11047. ** schema is shared, as the implementation often stores the database
  11048. ** connection handle passed to it via the xConnect() or xCreate() method
  11049. ** during initialization internally. This database connection handle may
  11050. ** then be used by the virtual table implementation to access real tables
  11051. ** within the database. So that they appear as part of the callers
  11052. ** transaction, these accesses need to be made via the same database
  11053. ** connection as that used to execute SQL operations on the virtual table.
  11054. **
  11055. ** All VTable objects that correspond to a single table in a shared
  11056. ** database schema are initially stored in a linked-list pointed to by
  11057. ** the Table.pVTable member variable of the corresponding Table object.
  11058. ** When an sqlite3_prepare() operation is required to access the virtual
  11059. ** table, it searches the list for the VTable that corresponds to the
  11060. ** database connection doing the preparing so as to use the correct
  11061. ** sqlite3_vtab* handle in the compiled query.
  11062. **
  11063. ** When an in-memory Table object is deleted (for example when the
  11064. ** schema is being reloaded for some reason), the VTable objects are not
  11065. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  11066. ** immediately. Instead, they are moved from the Table.pVTable list to
  11067. ** another linked list headed by the sqlite3.pDisconnect member of the
  11068. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  11069. ** next time a statement is prepared using said sqlite3*. This is done
  11070. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  11071. ** Refer to comments above function sqlite3VtabUnlockList() for an
  11072. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  11073. ** list without holding the corresponding sqlite3.mutex mutex.
  11074. **
  11075. ** The memory for objects of this type is always allocated by
  11076. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  11077. ** the first argument.
  11078. */
  11079. struct VTable {
  11080. sqlite3 *db; /* Database connection associated with this table */
  11081. Module *pMod; /* Pointer to module implementation */
  11082. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  11083. int nRef; /* Number of pointers to this structure */
  11084. u8 bConstraint; /* True if constraints are supported */
  11085. int iSavepoint; /* Depth of the SAVEPOINT stack */
  11086. VTable *pNext; /* Next in linked list (see above) */
  11087. };
  11088. /*
  11089. ** The schema for each SQL table and view is represented in memory
  11090. ** by an instance of the following structure.
  11091. */
  11092. struct Table {
  11093. char *zName; /* Name of the table or view */
  11094. Column *aCol; /* Information about each column */
  11095. Index *pIndex; /* List of SQL indexes on this table. */
  11096. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  11097. FKey *pFKey; /* Linked list of all foreign keys in this table */
  11098. char *zColAff; /* String defining the affinity of each column */
  11099. #ifndef SQLITE_OMIT_CHECK
  11100. ExprList *pCheck; /* All CHECK constraints */
  11101. #endif
  11102. int tnum; /* Root BTree page for this table */
  11103. i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
  11104. i16 nCol; /* Number of columns in this table */
  11105. u16 nRef; /* Number of pointers to this Table */
  11106. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  11107. LogEst szTabRow; /* Estimated size of each table row in bytes */
  11108. #ifdef SQLITE_ENABLE_COSTMULT
  11109. LogEst costMult; /* Cost multiplier for using this table */
  11110. #endif
  11111. u8 tabFlags; /* Mask of TF_* values */
  11112. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  11113. #ifndef SQLITE_OMIT_ALTERTABLE
  11114. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  11115. #endif
  11116. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11117. int nModuleArg; /* Number of arguments to the module */
  11118. char **azModuleArg; /* Text of all module args. [0] is module name */
  11119. VTable *pVTable; /* List of VTable objects. */
  11120. #endif
  11121. Trigger *pTrigger; /* List of triggers stored in pSchema */
  11122. Schema *pSchema; /* Schema that contains this table */
  11123. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  11124. };
  11125. /*
  11126. ** Allowed values for Table.tabFlags.
  11127. **
  11128. ** TF_OOOHidden applies to virtual tables that have hidden columns that are
  11129. ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
  11130. ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
  11131. ** the TF_OOOHidden attribute would apply in this case. Such tables require
  11132. ** special handling during INSERT processing.
  11133. */
  11134. #define TF_Readonly 0x01 /* Read-only system table */
  11135. #define TF_Ephemeral 0x02 /* An ephemeral table */
  11136. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  11137. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  11138. #define TF_Virtual 0x10 /* Is a virtual table */
  11139. #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
  11140. #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
  11141. #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
  11142. /*
  11143. ** Test to see whether or not a table is a virtual table. This is
  11144. ** done as a macro so that it will be optimized out when virtual
  11145. ** table support is omitted from the build.
  11146. */
  11147. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11148. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  11149. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  11150. #else
  11151. # define IsVirtual(X) 0
  11152. # define IsHiddenColumn(X) 0
  11153. #endif
  11154. /* Does the table have a rowid */
  11155. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  11156. #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
  11157. /*
  11158. ** Each foreign key constraint is an instance of the following structure.
  11159. **
  11160. ** A foreign key is associated with two tables. The "from" table is
  11161. ** the table that contains the REFERENCES clause that creates the foreign
  11162. ** key. The "to" table is the table that is named in the REFERENCES clause.
  11163. ** Consider this example:
  11164. **
  11165. ** CREATE TABLE ex1(
  11166. ** a INTEGER PRIMARY KEY,
  11167. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  11168. ** );
  11169. **
  11170. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  11171. ** Equivalent names:
  11172. **
  11173. ** from-table == child-table
  11174. ** to-table == parent-table
  11175. **
  11176. ** Each REFERENCES clause generates an instance of the following structure
  11177. ** which is attached to the from-table. The to-table need not exist when
  11178. ** the from-table is created. The existence of the to-table is not checked.
  11179. **
  11180. ** The list of all parents for child Table X is held at X.pFKey.
  11181. **
  11182. ** A list of all children for a table named Z (which might not even exist)
  11183. ** is held in Schema.fkeyHash with a hash key of Z.
  11184. */
  11185. struct FKey {
  11186. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  11187. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  11188. char *zTo; /* Name of table that the key points to (aka: Parent) */
  11189. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  11190. FKey *pPrevTo; /* Previous with the same zTo */
  11191. int nCol; /* Number of columns in this key */
  11192. /* EV: R-30323-21917 */
  11193. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  11194. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  11195. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  11196. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  11197. int iFrom; /* Index of column in pFrom */
  11198. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  11199. } aCol[1]; /* One entry for each of nCol columns */
  11200. };
  11201. /*
  11202. ** SQLite supports many different ways to resolve a constraint
  11203. ** error. ROLLBACK processing means that a constraint violation
  11204. ** causes the operation in process to fail and for the current transaction
  11205. ** to be rolled back. ABORT processing means the operation in process
  11206. ** fails and any prior changes from that one operation are backed out,
  11207. ** but the transaction is not rolled back. FAIL processing means that
  11208. ** the operation in progress stops and returns an error code. But prior
  11209. ** changes due to the same operation are not backed out and no rollback
  11210. ** occurs. IGNORE means that the particular row that caused the constraint
  11211. ** error is not inserted or updated. Processing continues and no error
  11212. ** is returned. REPLACE means that preexisting database rows that caused
  11213. ** a UNIQUE constraint violation are removed so that the new insert or
  11214. ** update can proceed. Processing continues and no error is reported.
  11215. **
  11216. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  11217. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  11218. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  11219. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  11220. ** referenced table row is propagated into the row that holds the
  11221. ** foreign key.
  11222. **
  11223. ** The following symbolic values are used to record which type
  11224. ** of action to take.
  11225. */
  11226. #define OE_None 0 /* There is no constraint to check */
  11227. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  11228. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  11229. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  11230. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  11231. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  11232. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  11233. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  11234. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  11235. #define OE_Cascade 9 /* Cascade the changes */
  11236. #define OE_Default 10 /* Do whatever the default action is */
  11237. /*
  11238. ** An instance of the following structure is passed as the first
  11239. ** argument to sqlite3VdbeKeyCompare and is used to control the
  11240. ** comparison of the two index keys.
  11241. **
  11242. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  11243. ** are nField slots for the columns of an index then one extra slot
  11244. ** for the rowid at the end.
  11245. */
  11246. struct KeyInfo {
  11247. u32 nRef; /* Number of references to this KeyInfo object */
  11248. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  11249. u16 nField; /* Number of key columns in the index */
  11250. u16 nXField; /* Number of columns beyond the key columns */
  11251. sqlite3 *db; /* The database connection */
  11252. u8 *aSortOrder; /* Sort order for each column. */
  11253. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  11254. };
  11255. /*
  11256. ** An instance of the following structure holds information about a
  11257. ** single index record that has already been parsed out into individual
  11258. ** values.
  11259. **
  11260. ** A record is an object that contains one or more fields of data.
  11261. ** Records are used to store the content of a table row and to store
  11262. ** the key of an index. A blob encoding of a record is created by
  11263. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  11264. ** OP_Column opcode.
  11265. **
  11266. ** This structure holds a record that has already been disassembled
  11267. ** into its constituent fields.
  11268. **
  11269. ** The r1 and r2 member variables are only used by the optimized comparison
  11270. ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
  11271. */
  11272. struct UnpackedRecord {
  11273. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  11274. u16 nField; /* Number of entries in apMem[] */
  11275. i8 default_rc; /* Comparison result if keys are equal */
  11276. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  11277. Mem *aMem; /* Values */
  11278. int r1; /* Value to return if (lhs > rhs) */
  11279. int r2; /* Value to return if (rhs < lhs) */
  11280. };
  11281. /*
  11282. ** Each SQL index is represented in memory by an
  11283. ** instance of the following structure.
  11284. **
  11285. ** The columns of the table that are to be indexed are described
  11286. ** by the aiColumn[] field of this structure. For example, suppose
  11287. ** we have the following table and index:
  11288. **
  11289. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  11290. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  11291. **
  11292. ** In the Table structure describing Ex1, nCol==3 because there are
  11293. ** three columns in the table. In the Index structure describing
  11294. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  11295. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  11296. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  11297. ** The second column to be indexed (c1) has an index of 0 in
  11298. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  11299. **
  11300. ** The Index.onError field determines whether or not the indexed columns
  11301. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  11302. ** it means this is not a unique index. Otherwise it is a unique index
  11303. ** and the value of Index.onError indicate the which conflict resolution
  11304. ** algorithm to employ whenever an attempt is made to insert a non-unique
  11305. ** element.
  11306. **
  11307. ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
  11308. ** generate VDBE code (as opposed to parsing one read from an sqlite_master
  11309. ** table as part of parsing an existing database schema), transient instances
  11310. ** of this structure may be created. In this case the Index.tnum variable is
  11311. ** used to store the address of a VDBE instruction, not a database page
  11312. ** number (it cannot - the database page is not allocated until the VDBE
  11313. ** program is executed). See convertToWithoutRowidTable() for details.
  11314. */
  11315. struct Index {
  11316. char *zName; /* Name of this index */
  11317. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  11318. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  11319. Table *pTable; /* The SQL table being indexed */
  11320. char *zColAff; /* String defining the affinity of each column */
  11321. Index *pNext; /* The next index associated with the same table */
  11322. Schema *pSchema; /* Schema containing this index */
  11323. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  11324. char **azColl; /* Array of collation sequence names for index */
  11325. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  11326. int tnum; /* DB Page containing root of this index */
  11327. LogEst szIdxRow; /* Estimated average row size in bytes */
  11328. u16 nKeyCol; /* Number of columns forming the key */
  11329. u16 nColumn; /* Number of columns stored in the index */
  11330. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  11331. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  11332. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  11333. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  11334. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  11335. unsigned isCovering:1; /* True if this is a covering index */
  11336. unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
  11337. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  11338. int nSample; /* Number of elements in aSample[] */
  11339. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  11340. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  11341. IndexSample *aSample; /* Samples of the left-most key */
  11342. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
  11343. tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
  11344. #endif
  11345. };
  11346. /*
  11347. ** Allowed values for Index.idxType
  11348. */
  11349. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  11350. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  11351. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  11352. /* Return true if index X is a PRIMARY KEY index */
  11353. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  11354. /* Return true if index X is a UNIQUE index */
  11355. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  11356. /*
  11357. ** Each sample stored in the sqlite_stat3 table is represented in memory
  11358. ** using a structure of this type. See documentation at the top of the
  11359. ** analyze.c source file for additional information.
  11360. */
  11361. struct IndexSample {
  11362. void *p; /* Pointer to sampled record */
  11363. int n; /* Size of record in bytes */
  11364. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  11365. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  11366. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  11367. };
  11368. /*
  11369. ** Each token coming out of the lexer is an instance of
  11370. ** this structure. Tokens are also used as part of an expression.
  11371. **
  11372. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  11373. ** may contain random values. Do not make any assumptions about Token.dyn
  11374. ** and Token.n when Token.z==0.
  11375. */
  11376. struct Token {
  11377. const char *z; /* Text of the token. Not NULL-terminated! */
  11378. unsigned int n; /* Number of characters in this token */
  11379. };
  11380. /*
  11381. ** An instance of this structure contains information needed to generate
  11382. ** code for a SELECT that contains aggregate functions.
  11383. **
  11384. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  11385. ** pointer to this structure. The Expr.iColumn field is the index in
  11386. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  11387. ** code for that node.
  11388. **
  11389. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  11390. ** original Select structure that describes the SELECT statement. These
  11391. ** fields do not need to be freed when deallocating the AggInfo structure.
  11392. */
  11393. struct AggInfo {
  11394. u8 directMode; /* Direct rendering mode means take data directly
  11395. ** from source tables rather than from accumulators */
  11396. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  11397. ** than the source table */
  11398. int sortingIdx; /* Cursor number of the sorting index */
  11399. int sortingIdxPTab; /* Cursor number of pseudo-table */
  11400. int nSortingColumn; /* Number of columns in the sorting index */
  11401. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  11402. ExprList *pGroupBy; /* The group by clause */
  11403. struct AggInfo_col { /* For each column used in source tables */
  11404. Table *pTab; /* Source table */
  11405. int iTable; /* Cursor number of the source table */
  11406. int iColumn; /* Column number within the source table */
  11407. int iSorterColumn; /* Column number in the sorting index */
  11408. int iMem; /* Memory location that acts as accumulator */
  11409. Expr *pExpr; /* The original expression */
  11410. } *aCol;
  11411. int nColumn; /* Number of used entries in aCol[] */
  11412. int nAccumulator; /* Number of columns that show through to the output.
  11413. ** Additional columns are used only as parameters to
  11414. ** aggregate functions */
  11415. struct AggInfo_func { /* For each aggregate function */
  11416. Expr *pExpr; /* Expression encoding the function */
  11417. FuncDef *pFunc; /* The aggregate function implementation */
  11418. int iMem; /* Memory location that acts as accumulator */
  11419. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  11420. } *aFunc;
  11421. int nFunc; /* Number of entries in aFunc[] */
  11422. };
  11423. /*
  11424. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  11425. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  11426. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  11427. ** it uses less memory in the Expr object, which is a big memory user
  11428. ** in systems with lots of prepared statements. And few applications
  11429. ** need more than about 10 or 20 variables. But some extreme users want
  11430. ** to have prepared statements with over 32767 variables, and for them
  11431. ** the option is available (at compile-time).
  11432. */
  11433. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  11434. typedef i16 ynVar;
  11435. #else
  11436. typedef int ynVar;
  11437. #endif
  11438. /*
  11439. ** Each node of an expression in the parse tree is an instance
  11440. ** of this structure.
  11441. **
  11442. ** Expr.op is the opcode. The integer parser token codes are reused
  11443. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  11444. ** code representing the ">=" operator. This same integer code is reused
  11445. ** to represent the greater-than-or-equal-to operator in the expression
  11446. ** tree.
  11447. **
  11448. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  11449. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  11450. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  11451. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  11452. ** then Expr.token contains the name of the function.
  11453. **
  11454. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  11455. ** binary operator. Either or both may be NULL.
  11456. **
  11457. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  11458. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  11459. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  11460. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  11461. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  11462. ** valid.
  11463. **
  11464. ** An expression of the form ID or ID.ID refers to a column in a table.
  11465. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  11466. ** the integer cursor number of a VDBE cursor pointing to that table and
  11467. ** Expr.iColumn is the column number for the specific column. If the
  11468. ** expression is used as a result in an aggregate SELECT, then the
  11469. ** value is also stored in the Expr.iAgg column in the aggregate so that
  11470. ** it can be accessed after all aggregates are computed.
  11471. **
  11472. ** If the expression is an unbound variable marker (a question mark
  11473. ** character '?' in the original SQL) then the Expr.iTable holds the index
  11474. ** number for that variable.
  11475. **
  11476. ** If the expression is a subquery then Expr.iColumn holds an integer
  11477. ** register number containing the result of the subquery. If the
  11478. ** subquery gives a constant result, then iTable is -1. If the subquery
  11479. ** gives a different answer at different times during statement processing
  11480. ** then iTable is the address of a subroutine that computes the subquery.
  11481. **
  11482. ** If the Expr is of type OP_Column, and the table it is selecting from
  11483. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  11484. ** corresponding table definition.
  11485. **
  11486. ** ALLOCATION NOTES:
  11487. **
  11488. ** Expr objects can use a lot of memory space in database schema. To
  11489. ** help reduce memory requirements, sometimes an Expr object will be
  11490. ** truncated. And to reduce the number of memory allocations, sometimes
  11491. ** two or more Expr objects will be stored in a single memory allocation,
  11492. ** together with Expr.zToken strings.
  11493. **
  11494. ** If the EP_Reduced and EP_TokenOnly flags are set when
  11495. ** an Expr object is truncated. When EP_Reduced is set, then all
  11496. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  11497. ** are contained within the same memory allocation. Note, however, that
  11498. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  11499. ** allocated, regardless of whether or not EP_Reduced is set.
  11500. */
  11501. struct Expr {
  11502. u8 op; /* Operation performed by this node */
  11503. char affinity; /* The affinity of the column or 0 if not a column */
  11504. u32 flags; /* Various flags. EP_* See below */
  11505. union {
  11506. char *zToken; /* Token value. Zero terminated and dequoted */
  11507. int iValue; /* Non-negative integer value if EP_IntValue */
  11508. } u;
  11509. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  11510. ** space is allocated for the fields below this point. An attempt to
  11511. ** access them will result in a segfault or malfunction.
  11512. *********************************************************************/
  11513. Expr *pLeft; /* Left subnode */
  11514. Expr *pRight; /* Right subnode */
  11515. union {
  11516. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  11517. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  11518. } x;
  11519. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  11520. ** space is allocated for the fields below this point. An attempt to
  11521. ** access them will result in a segfault or malfunction.
  11522. *********************************************************************/
  11523. #if SQLITE_MAX_EXPR_DEPTH>0
  11524. int nHeight; /* Height of the tree headed by this node */
  11525. #endif
  11526. int iTable; /* TK_COLUMN: cursor number of table holding column
  11527. ** TK_REGISTER: register number
  11528. ** TK_TRIGGER: 1 -> new, 0 -> old
  11529. ** EP_Unlikely: 134217728 times likelihood */
  11530. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  11531. ** TK_VARIABLE: variable number (always >= 1). */
  11532. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  11533. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  11534. u8 op2; /* TK_REGISTER: original value of Expr.op
  11535. ** TK_COLUMN: the value of p5 for OP_Column
  11536. ** TK_AGG_FUNCTION: nesting depth */
  11537. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  11538. Table *pTab; /* Table for TK_COLUMN expressions. */
  11539. };
  11540. /*
  11541. ** The following are the meanings of bits in the Expr.flags field.
  11542. */
  11543. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  11544. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  11545. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  11546. #define EP_Error 0x000008 /* Expression contains one or more errors */
  11547. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  11548. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  11549. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  11550. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  11551. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  11552. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  11553. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  11554. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  11555. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  11556. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  11557. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  11558. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  11559. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  11560. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  11561. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  11562. #define EP_ConstFunc 0x080000 /* Node is a SQLITE_FUNC_CONSTANT function */
  11563. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  11564. #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
  11565. /*
  11566. ** Combinations of two or more EP_* flags
  11567. */
  11568. #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
  11569. /*
  11570. ** These macros can be used to test, set, or clear bits in the
  11571. ** Expr.flags field.
  11572. */
  11573. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  11574. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  11575. #define ExprSetProperty(E,P) (E)->flags|=(P)
  11576. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  11577. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  11578. ** and Accreditation only. It works like ExprSetProperty() during VVA
  11579. ** processes but is a no-op for delivery.
  11580. */
  11581. #ifdef SQLITE_DEBUG
  11582. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  11583. #else
  11584. # define ExprSetVVAProperty(E,P)
  11585. #endif
  11586. /*
  11587. ** Macros to determine the number of bytes required by a normal Expr
  11588. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  11589. ** and an Expr struct with the EP_TokenOnly flag set.
  11590. */
  11591. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  11592. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  11593. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  11594. /*
  11595. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  11596. ** above sqlite3ExprDup() for details.
  11597. */
  11598. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  11599. /*
  11600. ** A list of expressions. Each expression may optionally have a
  11601. ** name. An expr/name combination can be used in several ways, such
  11602. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  11603. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  11604. ** also be used as the argument to a function, in which case the a.zName
  11605. ** field is not used.
  11606. **
  11607. ** By default the Expr.zSpan field holds a human-readable description of
  11608. ** the expression that is used in the generation of error messages and
  11609. ** column labels. In this case, Expr.zSpan is typically the text of a
  11610. ** column expression as it exists in a SELECT statement. However, if
  11611. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  11612. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  11613. ** form is used for name resolution with nested FROM clauses.
  11614. */
  11615. struct ExprList {
  11616. int nExpr; /* Number of expressions on the list */
  11617. struct ExprList_item { /* For each expression in the list */
  11618. Expr *pExpr; /* The list of expressions */
  11619. char *zName; /* Token associated with this expression */
  11620. char *zSpan; /* Original text of the expression */
  11621. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  11622. unsigned done :1; /* A flag to indicate when processing is finished */
  11623. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  11624. unsigned reusable :1; /* Constant expression is reusable */
  11625. union {
  11626. struct {
  11627. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  11628. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  11629. } x;
  11630. int iConstExprReg; /* Register in which Expr value is cached */
  11631. } u;
  11632. } *a; /* Alloc a power of two greater or equal to nExpr */
  11633. };
  11634. /*
  11635. ** An instance of this structure is used by the parser to record both
  11636. ** the parse tree for an expression and the span of input text for an
  11637. ** expression.
  11638. */
  11639. struct ExprSpan {
  11640. Expr *pExpr; /* The expression parse tree */
  11641. const char *zStart; /* First character of input text */
  11642. const char *zEnd; /* One character past the end of input text */
  11643. };
  11644. /*
  11645. ** An instance of this structure can hold a simple list of identifiers,
  11646. ** such as the list "a,b,c" in the following statements:
  11647. **
  11648. ** INSERT INTO t(a,b,c) VALUES ...;
  11649. ** CREATE INDEX idx ON t(a,b,c);
  11650. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  11651. **
  11652. ** The IdList.a.idx field is used when the IdList represents the list of
  11653. ** column names after a table name in an INSERT statement. In the statement
  11654. **
  11655. ** INSERT INTO t(a,b,c) ...
  11656. **
  11657. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  11658. */
  11659. struct IdList {
  11660. struct IdList_item {
  11661. char *zName; /* Name of the identifier */
  11662. int idx; /* Index in some Table.aCol[] of a column named zName */
  11663. } *a;
  11664. int nId; /* Number of identifiers on the list */
  11665. };
  11666. /*
  11667. ** The bitmask datatype defined below is used for various optimizations.
  11668. **
  11669. ** Changing this from a 64-bit to a 32-bit type limits the number of
  11670. ** tables in a join to 32 instead of 64. But it also reduces the size
  11671. ** of the library by 738 bytes on ix86.
  11672. */
  11673. typedef u64 Bitmask;
  11674. /*
  11675. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  11676. */
  11677. #define BMS ((int)(sizeof(Bitmask)*8))
  11678. /*
  11679. ** A bit in a Bitmask
  11680. */
  11681. #define MASKBIT(n) (((Bitmask)1)<<(n))
  11682. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  11683. /*
  11684. ** The following structure describes the FROM clause of a SELECT statement.
  11685. ** Each table or subquery in the FROM clause is a separate element of
  11686. ** the SrcList.a[] array.
  11687. **
  11688. ** With the addition of multiple database support, the following structure
  11689. ** can also be used to describe a particular table such as the table that
  11690. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  11691. ** such a table must be a simple name: ID. But in SQLite, the table can
  11692. ** now be identified by a database name, a dot, then the table name: ID.ID.
  11693. **
  11694. ** The jointype starts out showing the join type between the current table
  11695. ** and the next table on the list. The parser builds the list this way.
  11696. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  11697. ** jointype expresses the join between the table and the previous table.
  11698. **
  11699. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  11700. ** contains more than 63 columns and the 64-th or later column is used.
  11701. */
  11702. struct SrcList {
  11703. int nSrc; /* Number of tables or subqueries in the FROM clause */
  11704. u32 nAlloc; /* Number of entries allocated in a[] below */
  11705. struct SrcList_item {
  11706. Schema *pSchema; /* Schema to which this item is fixed */
  11707. char *zDatabase; /* Name of database holding this table */
  11708. char *zName; /* Name of the table */
  11709. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  11710. Table *pTab; /* An SQL table corresponding to zName */
  11711. Select *pSelect; /* A SELECT statement used in place of a table name */
  11712. int addrFillSub; /* Address of subroutine to manifest a subquery */
  11713. int regReturn; /* Register holding return address of addrFillSub */
  11714. int regResult; /* Registers holding results of a co-routine */
  11715. u8 jointype; /* Type of join between this able and the previous */
  11716. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  11717. unsigned isCorrelated :1; /* True if sub-query is correlated */
  11718. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  11719. unsigned isRecursive :1; /* True for recursive reference in WITH */
  11720. #ifndef SQLITE_OMIT_EXPLAIN
  11721. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  11722. #endif
  11723. int iCursor; /* The VDBE cursor number used to access this table */
  11724. Expr *pOn; /* The ON clause of a join */
  11725. IdList *pUsing; /* The USING clause of a join */
  11726. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  11727. char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
  11728. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  11729. } a[1]; /* One entry for each identifier on the list */
  11730. };
  11731. /*
  11732. ** Permitted values of the SrcList.a.jointype field
  11733. */
  11734. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  11735. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  11736. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  11737. #define JT_LEFT 0x0008 /* Left outer join */
  11738. #define JT_RIGHT 0x0010 /* Right outer join */
  11739. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  11740. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  11741. /*
  11742. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  11743. ** and the WhereInfo.wctrlFlags member.
  11744. */
  11745. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  11746. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  11747. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  11748. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  11749. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  11750. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  11751. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  11752. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  11753. #define WHERE_NO_AUTOINDEX 0x0080 /* Disallow automatic indexes */
  11754. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  11755. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  11756. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  11757. #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
  11758. #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
  11759. /* Allowed return values from sqlite3WhereIsDistinct()
  11760. */
  11761. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  11762. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  11763. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  11764. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  11765. /*
  11766. ** A NameContext defines a context in which to resolve table and column
  11767. ** names. The context consists of a list of tables (the pSrcList) field and
  11768. ** a list of named expression (pEList). The named expression list may
  11769. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  11770. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  11771. ** pEList corresponds to the result set of a SELECT and is NULL for
  11772. ** other statements.
  11773. **
  11774. ** NameContexts can be nested. When resolving names, the inner-most
  11775. ** context is searched first. If no match is found, the next outer
  11776. ** context is checked. If there is still no match, the next context
  11777. ** is checked. This process continues until either a match is found
  11778. ** or all contexts are check. When a match is found, the nRef member of
  11779. ** the context containing the match is incremented.
  11780. **
  11781. ** Each subquery gets a new NameContext. The pNext field points to the
  11782. ** NameContext in the parent query. Thus the process of scanning the
  11783. ** NameContext list corresponds to searching through successively outer
  11784. ** subqueries looking for a match.
  11785. */
  11786. struct NameContext {
  11787. Parse *pParse; /* The parser */
  11788. SrcList *pSrcList; /* One or more tables used to resolve names */
  11789. ExprList *pEList; /* Optional list of result-set columns */
  11790. AggInfo *pAggInfo; /* Information about aggregates at this level */
  11791. NameContext *pNext; /* Next outer name context. NULL for outermost */
  11792. int nRef; /* Number of names resolved by this context */
  11793. int nErr; /* Number of errors encountered while resolving names */
  11794. u16 ncFlags; /* Zero or more NC_* flags defined below */
  11795. };
  11796. /*
  11797. ** Allowed values for the NameContext, ncFlags field.
  11798. **
  11799. ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
  11800. ** SQLITE_FUNC_MINMAX.
  11801. **
  11802. */
  11803. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  11804. #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
  11805. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  11806. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  11807. #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
  11808. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  11809. /*
  11810. ** An instance of the following structure contains all information
  11811. ** needed to generate code for a single SELECT statement.
  11812. **
  11813. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  11814. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  11815. ** limit and nOffset to the value of the offset (or 0 if there is not
  11816. ** offset). But later on, nLimit and nOffset become the memory locations
  11817. ** in the VDBE that record the limit and offset counters.
  11818. **
  11819. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  11820. ** These addresses must be stored so that we can go back and fill in
  11821. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  11822. ** the number of columns in P2 can be computed at the same time
  11823. ** as the OP_OpenEphm instruction is coded because not
  11824. ** enough information about the compound query is known at that point.
  11825. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  11826. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  11827. ** sequences for the ORDER BY clause.
  11828. */
  11829. struct Select {
  11830. ExprList *pEList; /* The fields of the result */
  11831. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  11832. u16 selFlags; /* Various SF_* values */
  11833. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  11834. #if SELECTTRACE_ENABLED
  11835. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  11836. #endif
  11837. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  11838. u64 nSelectRow; /* Estimated number of result rows */
  11839. SrcList *pSrc; /* The FROM clause */
  11840. Expr *pWhere; /* The WHERE clause */
  11841. ExprList *pGroupBy; /* The GROUP BY clause */
  11842. Expr *pHaving; /* The HAVING clause */
  11843. ExprList *pOrderBy; /* The ORDER BY clause */
  11844. Select *pPrior; /* Prior select in a compound select statement */
  11845. Select *pNext; /* Next select to the left in a compound */
  11846. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  11847. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  11848. With *pWith; /* WITH clause attached to this select. Or NULL. */
  11849. };
  11850. /*
  11851. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  11852. ** "Select Flag".
  11853. */
  11854. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  11855. #define SF_All 0x0002 /* Includes the ALL keyword */
  11856. #define SF_Resolved 0x0004 /* Identifiers have been resolved */
  11857. #define SF_Aggregate 0x0008 /* Contains aggregate functions */
  11858. #define SF_UsesEphemeral 0x0010 /* Uses the OpenEphemeral opcode */
  11859. #define SF_Expanded 0x0020 /* sqlite3SelectExpand() called on this */
  11860. #define SF_HasTypeInfo 0x0040 /* FROM subqueries have Table metadata */
  11861. #define SF_Compound 0x0080 /* Part of a compound query */
  11862. #define SF_Values 0x0100 /* Synthesized from VALUES clause */
  11863. #define SF_MultiValue 0x0200 /* Single VALUES term with multiple rows */
  11864. #define SF_NestedFrom 0x0400 /* Part of a parenthesized FROM clause */
  11865. #define SF_MaybeConvert 0x0800 /* Need convertCompoundSelectToSubquery() */
  11866. #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
  11867. #define SF_Recursive 0x2000 /* The recursive part of a recursive CTE */
  11868. #define SF_Converted 0x4000 /* By convertCompoundSelectToSubquery() */
  11869. /*
  11870. ** The results of a SELECT can be distributed in several ways, as defined
  11871. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  11872. ** Type".
  11873. **
  11874. ** SRT_Union Store results as a key in a temporary index
  11875. ** identified by pDest->iSDParm.
  11876. **
  11877. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  11878. **
  11879. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  11880. ** set is not empty.
  11881. **
  11882. ** SRT_Discard Throw the results away. This is used by SELECT
  11883. ** statements within triggers whose only purpose is
  11884. ** the side-effects of functions.
  11885. **
  11886. ** All of the above are free to ignore their ORDER BY clause. Those that
  11887. ** follow must honor the ORDER BY clause.
  11888. **
  11889. ** SRT_Output Generate a row of output (using the OP_ResultRow
  11890. ** opcode) for each row in the result set.
  11891. **
  11892. ** SRT_Mem Only valid if the result is a single column.
  11893. ** Store the first column of the first result row
  11894. ** in register pDest->iSDParm then abandon the rest
  11895. ** of the query. This destination implies "LIMIT 1".
  11896. **
  11897. ** SRT_Set The result must be a single column. Store each
  11898. ** row of result as the key in table pDest->iSDParm.
  11899. ** Apply the affinity pDest->affSdst before storing
  11900. ** results. Used to implement "IN (SELECT ...)".
  11901. **
  11902. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  11903. ** the result there. The cursor is left open after
  11904. ** returning. This is like SRT_Table except that
  11905. ** this destination uses OP_OpenEphemeral to create
  11906. ** the table first.
  11907. **
  11908. ** SRT_Coroutine Generate a co-routine that returns a new row of
  11909. ** results each time it is invoked. The entry point
  11910. ** of the co-routine is stored in register pDest->iSDParm
  11911. ** and the result row is stored in pDest->nDest registers
  11912. ** starting with pDest->iSdst.
  11913. **
  11914. ** SRT_Table Store results in temporary table pDest->iSDParm.
  11915. ** SRT_Fifo This is like SRT_EphemTab except that the table
  11916. ** is assumed to already be open. SRT_Fifo has
  11917. ** the additional property of being able to ignore
  11918. ** the ORDER BY clause.
  11919. **
  11920. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  11921. ** But also use temporary table pDest->iSDParm+1 as
  11922. ** a record of all prior results and ignore any duplicate
  11923. ** rows. Name means: "Distinct Fifo".
  11924. **
  11925. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  11926. ** an index). Append a sequence number so that all entries
  11927. ** are distinct.
  11928. **
  11929. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  11930. ** the same record has never been stored before. The
  11931. ** index at pDest->iSDParm+1 hold all prior stores.
  11932. */
  11933. #define SRT_Union 1 /* Store result as keys in an index */
  11934. #define SRT_Except 2 /* Remove result from a UNION index */
  11935. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  11936. #define SRT_Discard 4 /* Do not save the results anywhere */
  11937. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  11938. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  11939. #define SRT_Queue 7 /* Store result in an queue */
  11940. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  11941. /* The ORDER BY clause is ignored for all of the above */
  11942. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  11943. #define SRT_Output 9 /* Output each row of result */
  11944. #define SRT_Mem 10 /* Store result in a memory cell */
  11945. #define SRT_Set 11 /* Store results as keys in an index */
  11946. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  11947. #define SRT_Coroutine 13 /* Generate a single row of result */
  11948. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  11949. /*
  11950. ** An instance of this object describes where to put of the results of
  11951. ** a SELECT statement.
  11952. */
  11953. struct SelectDest {
  11954. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  11955. char affSdst; /* Affinity used when eDest==SRT_Set */
  11956. int iSDParm; /* A parameter used by the eDest disposal method */
  11957. int iSdst; /* Base register where results are written */
  11958. int nSdst; /* Number of registers allocated */
  11959. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  11960. };
  11961. /*
  11962. ** During code generation of statements that do inserts into AUTOINCREMENT
  11963. ** tables, the following information is attached to the Table.u.autoInc.p
  11964. ** pointer of each autoincrement table to record some side information that
  11965. ** the code generator needs. We have to keep per-table autoincrement
  11966. ** information in case inserts are down within triggers. Triggers do not
  11967. ** normally coordinate their activities, but we do need to coordinate the
  11968. ** loading and saving of autoincrement information.
  11969. */
  11970. struct AutoincInfo {
  11971. AutoincInfo *pNext; /* Next info block in a list of them all */
  11972. Table *pTab; /* Table this info block refers to */
  11973. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  11974. int regCtr; /* Memory register holding the rowid counter */
  11975. };
  11976. /*
  11977. ** Size of the column cache
  11978. */
  11979. #ifndef SQLITE_N_COLCACHE
  11980. # define SQLITE_N_COLCACHE 10
  11981. #endif
  11982. /*
  11983. ** At least one instance of the following structure is created for each
  11984. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  11985. ** statement. All such objects are stored in the linked list headed at
  11986. ** Parse.pTriggerPrg and deleted once statement compilation has been
  11987. ** completed.
  11988. **
  11989. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  11990. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  11991. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  11992. ** The Parse.pTriggerPrg list never contains two entries with the same
  11993. ** values for both pTrigger and orconf.
  11994. **
  11995. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  11996. ** accessed (or set to 0 for triggers fired as a result of INSERT
  11997. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  11998. ** a mask of new.* columns used by the program.
  11999. */
  12000. struct TriggerPrg {
  12001. Trigger *pTrigger; /* Trigger this program was coded from */
  12002. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  12003. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  12004. int orconf; /* Default ON CONFLICT policy */
  12005. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  12006. };
  12007. /*
  12008. ** The yDbMask datatype for the bitmask of all attached databases.
  12009. */
  12010. #if SQLITE_MAX_ATTACHED>30
  12011. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  12012. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  12013. # define DbMaskZero(M) memset((M),0,sizeof(M))
  12014. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  12015. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  12016. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  12017. #else
  12018. typedef unsigned int yDbMask;
  12019. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  12020. # define DbMaskZero(M) (M)=0
  12021. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  12022. # define DbMaskAllZero(M) (M)==0
  12023. # define DbMaskNonZero(M) (M)!=0
  12024. #endif
  12025. /*
  12026. ** An SQL parser context. A copy of this structure is passed through
  12027. ** the parser and down into all the parser action routine in order to
  12028. ** carry around information that is global to the entire parse.
  12029. **
  12030. ** The structure is divided into two parts. When the parser and code
  12031. ** generate call themselves recursively, the first part of the structure
  12032. ** is constant but the second part is reset at the beginning and end of
  12033. ** each recursion.
  12034. **
  12035. ** The nTableLock and aTableLock variables are only used if the shared-cache
  12036. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  12037. ** used to store the set of table-locks required by the statement being
  12038. ** compiled. Function sqlite3TableLock() is used to add entries to the
  12039. ** list.
  12040. */
  12041. struct Parse {
  12042. sqlite3 *db; /* The main database structure */
  12043. char *zErrMsg; /* An error message */
  12044. Vdbe *pVdbe; /* An engine for executing database bytecode */
  12045. int rc; /* Return code from execution */
  12046. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  12047. u8 checkSchema; /* Causes schema cookie check after an error */
  12048. u8 nested; /* Number of nested calls to the parser/code generator */
  12049. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  12050. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  12051. u8 mayAbort; /* True if statement may throw an ABORT exception */
  12052. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  12053. u8 okConstFactor; /* OK to factor out constants */
  12054. int aTempReg[8]; /* Holding area for temporary registers */
  12055. int nRangeReg; /* Size of the temporary register block */
  12056. int iRangeReg; /* First register in temporary register block */
  12057. int nErr; /* Number of errors seen */
  12058. int nTab; /* Number of previously allocated VDBE cursors */
  12059. int nMem; /* Number of memory cells used so far */
  12060. int nSet; /* Number of sets used so far */
  12061. int nOnce; /* Number of OP_Once instructions so far */
  12062. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  12063. int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
  12064. int ckBase; /* Base register of data during check constraints */
  12065. int iPartIdxTab; /* Table corresponding to a partial index */
  12066. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  12067. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  12068. int nLabel; /* Number of labels used */
  12069. int *aLabel; /* Space to hold the labels */
  12070. struct yColCache {
  12071. int iTable; /* Table cursor number */
  12072. i16 iColumn; /* Table column number */
  12073. u8 tempReg; /* iReg is a temp register that needs to be freed */
  12074. int iLevel; /* Nesting level */
  12075. int iReg; /* Reg with value of this column. 0 means none. */
  12076. int lru; /* Least recently used entry has the smallest value */
  12077. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  12078. ExprList *pConstExpr;/* Constant expressions */
  12079. Token constraintName;/* Name of the constraint currently being parsed */
  12080. yDbMask writeMask; /* Start a write transaction on these databases */
  12081. yDbMask cookieMask; /* Bitmask of schema verified databases */
  12082. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  12083. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  12084. int regRoot; /* Register holding root page number for new objects */
  12085. int nMaxArg; /* Max args passed to user function by sub-program */
  12086. #if SELECTTRACE_ENABLED
  12087. int nSelect; /* Number of SELECT statements seen */
  12088. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  12089. #endif
  12090. #ifndef SQLITE_OMIT_SHARED_CACHE
  12091. int nTableLock; /* Number of locks in aTableLock */
  12092. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  12093. #endif
  12094. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  12095. /* Information used while coding trigger programs. */
  12096. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  12097. Table *pTriggerTab; /* Table triggers are being coded for */
  12098. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  12099. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  12100. u32 oldmask; /* Mask of old.* columns referenced */
  12101. u32 newmask; /* Mask of new.* columns referenced */
  12102. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  12103. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  12104. u8 disableTriggers; /* True to disable triggers */
  12105. /************************************************************************
  12106. ** Above is constant between recursions. Below is reset before and after
  12107. ** each recursion. The boundary between these two regions is determined
  12108. ** using offsetof(Parse,nVar) so the nVar field must be the first field
  12109. ** in the recursive region.
  12110. ************************************************************************/
  12111. int nVar; /* Number of '?' variables seen in the SQL so far */
  12112. int nzVar; /* Number of available slots in azVar[] */
  12113. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  12114. u8 bFreeWith; /* True if pWith should be freed with parser */
  12115. u8 explain; /* True if the EXPLAIN flag is found on the query */
  12116. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12117. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  12118. int nVtabLock; /* Number of virtual tables to lock */
  12119. #endif
  12120. int nAlias; /* Number of aliased result set columns */
  12121. int nHeight; /* Expression tree height of current sub-select */
  12122. #ifndef SQLITE_OMIT_EXPLAIN
  12123. int iSelectId; /* ID of current select for EXPLAIN output */
  12124. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  12125. #endif
  12126. char **azVar; /* Pointers to names of parameters */
  12127. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  12128. const char *zTail; /* All SQL text past the last semicolon parsed */
  12129. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  12130. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  12131. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  12132. Token sNameToken; /* Token with unqualified schema object name */
  12133. Token sLastToken; /* The last token parsed */
  12134. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12135. Token sArg; /* Complete text of a module argument */
  12136. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  12137. #endif
  12138. Table *pZombieTab; /* List of Table objects to delete after code gen */
  12139. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  12140. With *pWith; /* Current WITH clause, or NULL */
  12141. };
  12142. /*
  12143. ** Return true if currently inside an sqlite3_declare_vtab() call.
  12144. */
  12145. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12146. #define IN_DECLARE_VTAB 0
  12147. #else
  12148. #define IN_DECLARE_VTAB (pParse->declareVtab)
  12149. #endif
  12150. /*
  12151. ** An instance of the following structure can be declared on a stack and used
  12152. ** to save the Parse.zAuthContext value so that it can be restored later.
  12153. */
  12154. struct AuthContext {
  12155. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  12156. Parse *pParse; /* The Parse structure */
  12157. };
  12158. /*
  12159. ** Bitfield flags for P5 value in various opcodes.
  12160. */
  12161. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  12162. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  12163. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  12164. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  12165. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  12166. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  12167. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  12168. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  12169. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  12170. #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
  12171. #define OPFLAG_P2ISREG 0x04 /* P2 to OP_Open** is a register number */
  12172. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  12173. /*
  12174. * Each trigger present in the database schema is stored as an instance of
  12175. * struct Trigger.
  12176. *
  12177. * Pointers to instances of struct Trigger are stored in two ways.
  12178. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  12179. * database). This allows Trigger structures to be retrieved by name.
  12180. * 2. All triggers associated with a single table form a linked list, using the
  12181. * pNext member of struct Trigger. A pointer to the first element of the
  12182. * linked list is stored as the "pTrigger" member of the associated
  12183. * struct Table.
  12184. *
  12185. * The "step_list" member points to the first element of a linked list
  12186. * containing the SQL statements specified as the trigger program.
  12187. */
  12188. struct Trigger {
  12189. char *zName; /* The name of the trigger */
  12190. char *table; /* The table or view to which the trigger applies */
  12191. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  12192. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  12193. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  12194. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  12195. the <column-list> is stored here */
  12196. Schema *pSchema; /* Schema containing the trigger */
  12197. Schema *pTabSchema; /* Schema containing the table */
  12198. TriggerStep *step_list; /* Link list of trigger program steps */
  12199. Trigger *pNext; /* Next trigger associated with the table */
  12200. };
  12201. /*
  12202. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  12203. ** determine which.
  12204. **
  12205. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  12206. ** In that cases, the constants below can be ORed together.
  12207. */
  12208. #define TRIGGER_BEFORE 1
  12209. #define TRIGGER_AFTER 2
  12210. /*
  12211. * An instance of struct TriggerStep is used to store a single SQL statement
  12212. * that is a part of a trigger-program.
  12213. *
  12214. * Instances of struct TriggerStep are stored in a singly linked list (linked
  12215. * using the "pNext" member) referenced by the "step_list" member of the
  12216. * associated struct Trigger instance. The first element of the linked list is
  12217. * the first step of the trigger-program.
  12218. *
  12219. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  12220. * "SELECT" statement. The meanings of the other members is determined by the
  12221. * value of "op" as follows:
  12222. *
  12223. * (op == TK_INSERT)
  12224. * orconf -> stores the ON CONFLICT algorithm
  12225. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  12226. * this stores a pointer to the SELECT statement. Otherwise NULL.
  12227. * zTarget -> Dequoted name of the table to insert into.
  12228. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  12229. * this stores values to be inserted. Otherwise NULL.
  12230. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  12231. * statement, then this stores the column-names to be
  12232. * inserted into.
  12233. *
  12234. * (op == TK_DELETE)
  12235. * zTarget -> Dequoted name of the table to delete from.
  12236. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  12237. * Otherwise NULL.
  12238. *
  12239. * (op == TK_UPDATE)
  12240. * zTarget -> Dequoted name of the table to update.
  12241. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  12242. * Otherwise NULL.
  12243. * pExprList -> A list of the columns to update and the expressions to update
  12244. * them to. See sqlite3Update() documentation of "pChanges"
  12245. * argument.
  12246. *
  12247. */
  12248. struct TriggerStep {
  12249. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  12250. u8 orconf; /* OE_Rollback etc. */
  12251. Trigger *pTrig; /* The trigger that this step is a part of */
  12252. Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
  12253. char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
  12254. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  12255. ExprList *pExprList; /* SET clause for UPDATE. */
  12256. IdList *pIdList; /* Column names for INSERT */
  12257. TriggerStep *pNext; /* Next in the link-list */
  12258. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  12259. };
  12260. /*
  12261. ** The following structure contains information used by the sqliteFix...
  12262. ** routines as they walk the parse tree to make database references
  12263. ** explicit.
  12264. */
  12265. typedef struct DbFixer DbFixer;
  12266. struct DbFixer {
  12267. Parse *pParse; /* The parsing context. Error messages written here */
  12268. Schema *pSchema; /* Fix items to this schema */
  12269. int bVarOnly; /* Check for variable references only */
  12270. const char *zDb; /* Make sure all objects are contained in this database */
  12271. const char *zType; /* Type of the container - used for error messages */
  12272. const Token *pName; /* Name of the container - used for error messages */
  12273. };
  12274. /*
  12275. ** An objected used to accumulate the text of a string where we
  12276. ** do not necessarily know how big the string will be in the end.
  12277. */
  12278. struct StrAccum {
  12279. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  12280. char *zBase; /* A base allocation. Not from malloc. */
  12281. char *zText; /* The string collected so far */
  12282. int nChar; /* Length of the string so far */
  12283. int nAlloc; /* Amount of space allocated in zText */
  12284. int mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
  12285. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  12286. };
  12287. #define STRACCUM_NOMEM 1
  12288. #define STRACCUM_TOOBIG 2
  12289. /*
  12290. ** A pointer to this structure is used to communicate information
  12291. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  12292. */
  12293. typedef struct {
  12294. sqlite3 *db; /* The database being initialized */
  12295. char **pzErrMsg; /* Error message stored here */
  12296. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  12297. int rc; /* Result code stored here */
  12298. } InitData;
  12299. /*
  12300. ** Structure containing global configuration data for the SQLite library.
  12301. **
  12302. ** This structure also contains some state information.
  12303. */
  12304. struct Sqlite3Config {
  12305. int bMemstat; /* True to enable memory status */
  12306. int bCoreMutex; /* True to enable core mutexing */
  12307. int bFullMutex; /* True to enable full mutexing */
  12308. int bOpenUri; /* True to interpret filenames as URIs */
  12309. int bUseCis; /* Use covering indices for full-scans */
  12310. int mxStrlen; /* Maximum string length */
  12311. int neverCorrupt; /* Database is always well-formed */
  12312. int szLookaside; /* Default lookaside buffer size */
  12313. int nLookaside; /* Default lookaside buffer count */
  12314. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  12315. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  12316. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  12317. void *pHeap; /* Heap storage space */
  12318. int nHeap; /* Size of pHeap[] */
  12319. int mnReq, mxReq; /* Min and max heap requests sizes */
  12320. sqlite3_int64 szMmap; /* mmap() space per open file */
  12321. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  12322. void *pScratch; /* Scratch memory */
  12323. int szScratch; /* Size of each scratch buffer */
  12324. int nScratch; /* Number of scratch buffers */
  12325. void *pPage; /* Page cache memory */
  12326. int szPage; /* Size of each page in pPage[] */
  12327. int nPage; /* Number of pages in pPage[] */
  12328. int mxParserStack; /* maximum depth of the parser stack */
  12329. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  12330. u32 szPma; /* Maximum Sorter PMA size */
  12331. /* The above might be initialized to non-zero. The following need to always
  12332. ** initially be zero, however. */
  12333. int isInit; /* True after initialization has finished */
  12334. int inProgress; /* True while initialization in progress */
  12335. int isMutexInit; /* True after mutexes are initialized */
  12336. int isMallocInit; /* True after malloc is initialized */
  12337. int isPCacheInit; /* True after malloc is initialized */
  12338. int nRefInitMutex; /* Number of users of pInitMutex */
  12339. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  12340. void (*xLog)(void*,int,const char*); /* Function for logging */
  12341. void *pLogArg; /* First argument to xLog() */
  12342. #ifdef SQLITE_ENABLE_SQLLOG
  12343. void(*xSqllog)(void*,sqlite3*,const char*, int);
  12344. void *pSqllogArg;
  12345. #endif
  12346. #ifdef SQLITE_VDBE_COVERAGE
  12347. /* The following callback (if not NULL) is invoked on every VDBE branch
  12348. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  12349. */
  12350. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  12351. void *pVdbeBranchArg; /* 1st argument */
  12352. #endif
  12353. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12354. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  12355. #endif
  12356. int bLocaltimeFault; /* True to fail localtime() calls */
  12357. };
  12358. /*
  12359. ** This macro is used inside of assert() statements to indicate that
  12360. ** the assert is only valid on a well-formed database. Instead of:
  12361. **
  12362. ** assert( X );
  12363. **
  12364. ** One writes:
  12365. **
  12366. ** assert( X || CORRUPT_DB );
  12367. **
  12368. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  12369. ** that the database is definitely corrupt, only that it might be corrupt.
  12370. ** For most test cases, CORRUPT_DB is set to false using a special
  12371. ** sqlite3_test_control(). This enables assert() statements to prove
  12372. ** things that are always true for well-formed databases.
  12373. */
  12374. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  12375. /*
  12376. ** Context pointer passed down through the tree-walk.
  12377. */
  12378. struct Walker {
  12379. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  12380. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  12381. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  12382. Parse *pParse; /* Parser context. */
  12383. int walkerDepth; /* Number of subqueries */
  12384. u8 eCode; /* A small processing code */
  12385. union { /* Extra data for callback */
  12386. NameContext *pNC; /* Naming context */
  12387. int n; /* A counter */
  12388. int iCur; /* A cursor number */
  12389. SrcList *pSrcList; /* FROM clause */
  12390. struct SrcCount *pSrcCount; /* Counting column references */
  12391. } u;
  12392. };
  12393. /* Forward declarations */
  12394. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  12395. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  12396. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  12397. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  12398. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  12399. /*
  12400. ** Return code from the parse-tree walking primitives and their
  12401. ** callbacks.
  12402. */
  12403. #define WRC_Continue 0 /* Continue down into children */
  12404. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  12405. #define WRC_Abort 2 /* Abandon the tree walk */
  12406. /*
  12407. ** An instance of this structure represents a set of one or more CTEs
  12408. ** (common table expressions) created by a single WITH clause.
  12409. */
  12410. struct With {
  12411. int nCte; /* Number of CTEs in the WITH clause */
  12412. With *pOuter; /* Containing WITH clause, or NULL */
  12413. struct Cte { /* For each CTE in the WITH clause.... */
  12414. char *zName; /* Name of this CTE */
  12415. ExprList *pCols; /* List of explicit column names, or NULL */
  12416. Select *pSelect; /* The definition of this CTE */
  12417. const char *zErr; /* Error message for circular references */
  12418. } a[1];
  12419. };
  12420. #ifdef SQLITE_DEBUG
  12421. /*
  12422. ** An instance of the TreeView object is used for printing the content of
  12423. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  12424. */
  12425. struct TreeView {
  12426. int iLevel; /* Which level of the tree we are on */
  12427. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  12428. };
  12429. #endif /* SQLITE_DEBUG */
  12430. /*
  12431. ** Assuming zIn points to the first byte of a UTF-8 character,
  12432. ** advance zIn to point to the first byte of the next UTF-8 character.
  12433. */
  12434. #define SQLITE_SKIP_UTF8(zIn) { \
  12435. if( (*(zIn++))>=0xc0 ){ \
  12436. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  12437. } \
  12438. }
  12439. /*
  12440. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  12441. ** the same name but without the _BKPT suffix. These macros invoke
  12442. ** routines that report the line-number on which the error originated
  12443. ** using sqlite3_log(). The routines also provide a convenient place
  12444. ** to set a debugger breakpoint.
  12445. */
  12446. SQLITE_PRIVATE int sqlite3CorruptError(int);
  12447. SQLITE_PRIVATE int sqlite3MisuseError(int);
  12448. SQLITE_PRIVATE int sqlite3CantopenError(int);
  12449. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  12450. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  12451. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  12452. /*
  12453. ** FTS4 is really an extension for FTS3. It is enabled using the
  12454. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  12455. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  12456. */
  12457. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  12458. # define SQLITE_ENABLE_FTS3 1
  12459. #endif
  12460. /*
  12461. ** The ctype.h header is needed for non-ASCII systems. It is also
  12462. ** needed by FTS3 when FTS3 is included in the amalgamation.
  12463. */
  12464. #if !defined(SQLITE_ASCII) || \
  12465. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  12466. # include <ctype.h>
  12467. #endif
  12468. /*
  12469. ** The following macros mimic the standard library functions toupper(),
  12470. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  12471. ** sqlite versions only work for ASCII characters, regardless of locale.
  12472. */
  12473. #ifdef SQLITE_ASCII
  12474. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  12475. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  12476. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  12477. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  12478. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  12479. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  12480. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  12481. #else
  12482. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  12483. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  12484. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  12485. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  12486. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  12487. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  12488. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  12489. #endif
  12490. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12491. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  12492. #endif
  12493. /*
  12494. ** Internal function prototypes
  12495. */
  12496. #define sqlite3StrICmp sqlite3_stricmp
  12497. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  12498. #define sqlite3StrNICmp sqlite3_strnicmp
  12499. SQLITE_PRIVATE int sqlite3MallocInit(void);
  12500. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  12501. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  12502. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  12503. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  12504. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  12505. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  12506. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  12507. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  12508. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  12509. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  12510. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  12511. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  12512. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  12513. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  12514. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  12515. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  12516. SQLITE_PRIVATE void sqlite3PageFree(void*);
  12517. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  12518. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12519. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  12520. #endif
  12521. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  12522. /*
  12523. ** On systems with ample stack space and that support alloca(), make
  12524. ** use of alloca() to obtain space for large automatic objects. By default,
  12525. ** obtain space from malloc().
  12526. **
  12527. ** The alloca() routine never returns NULL. This will cause code paths
  12528. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  12529. */
  12530. #ifdef SQLITE_USE_ALLOCA
  12531. # define sqlite3StackAllocRaw(D,N) alloca(N)
  12532. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  12533. # define sqlite3StackFree(D,P)
  12534. #else
  12535. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  12536. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  12537. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  12538. #endif
  12539. #ifdef SQLITE_ENABLE_MEMSYS3
  12540. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  12541. #endif
  12542. #ifdef SQLITE_ENABLE_MEMSYS5
  12543. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  12544. #endif
  12545. #ifndef SQLITE_MUTEX_OMIT
  12546. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  12547. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  12548. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  12549. SQLITE_PRIVATE int sqlite3MutexInit(void);
  12550. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  12551. #endif
  12552. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
  12553. SQLITE_PRIVATE void sqlite3StatusUp(int, int);
  12554. SQLITE_PRIVATE void sqlite3StatusDown(int, int);
  12555. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  12556. /* Access to mutexes used by sqlite3_status() */
  12557. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
  12558. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
  12559. #ifndef SQLITE_OMIT_FLOATING_POINT
  12560. SQLITE_PRIVATE int sqlite3IsNaN(double);
  12561. #else
  12562. # define sqlite3IsNaN(X) 0
  12563. #endif
  12564. /*
  12565. ** An instance of the following structure holds information about SQL
  12566. ** functions arguments that are the parameters to the printf() function.
  12567. */
  12568. struct PrintfArguments {
  12569. int nArg; /* Total number of arguments */
  12570. int nUsed; /* Number of arguments used so far */
  12571. sqlite3_value **apArg; /* The argument values */
  12572. };
  12573. #define SQLITE_PRINTF_INTERNAL 0x01
  12574. #define SQLITE_PRINTF_SQLFUNC 0x02
  12575. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
  12576. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
  12577. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  12578. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  12579. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  12580. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  12581. #endif
  12582. #if defined(SQLITE_TEST)
  12583. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  12584. #endif
  12585. #if defined(SQLITE_DEBUG)
  12586. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  12587. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  12588. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  12589. #endif
  12590. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
  12591. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  12592. SQLITE_PRIVATE int sqlite3Dequote(char*);
  12593. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  12594. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  12595. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  12596. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  12597. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  12598. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  12599. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  12600. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  12601. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  12602. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  12603. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  12604. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  12605. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  12606. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  12607. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  12608. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  12609. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  12610. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  12611. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  12612. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  12613. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
  12614. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  12615. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  12616. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  12617. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  12618. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  12619. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  12620. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  12621. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  12622. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  12623. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  12624. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  12625. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  12626. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  12627. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  12628. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  12629. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  12630. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  12631. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  12632. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  12633. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  12634. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  12635. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  12636. sqlite3_vfs**,char**,char **);
  12637. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  12638. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  12639. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12640. # define sqlite3FaultSim(X) SQLITE_OK
  12641. #else
  12642. SQLITE_PRIVATE int sqlite3FaultSim(int);
  12643. #endif
  12644. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  12645. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  12646. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec*, u32);
  12647. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  12648. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  12649. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  12650. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  12651. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12652. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  12653. #endif
  12654. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  12655. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  12656. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  12657. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  12658. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  12659. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  12660. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  12661. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  12662. #else
  12663. # define sqlite3ViewGetColumnNames(A,B) 0
  12664. #endif
  12665. #if SQLITE_MAX_ATTACHED>30
  12666. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  12667. #endif
  12668. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  12669. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  12670. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  12671. #ifndef SQLITE_OMIT_AUTOINCREMENT
  12672. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  12673. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  12674. #else
  12675. # define sqlite3AutoincrementBegin(X)
  12676. # define sqlite3AutoincrementEnd(X)
  12677. #endif
  12678. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  12679. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  12680. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  12681. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  12682. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  12683. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  12684. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  12685. Token*, Select*, Expr*, IdList*);
  12686. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  12687. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  12688. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  12689. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  12690. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  12691. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  12692. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  12693. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  12694. Expr*, int, int);
  12695. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  12696. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  12697. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  12698. Expr*,ExprList*,u16,Expr*,Expr*);
  12699. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  12700. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  12701. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  12702. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  12703. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  12704. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  12705. #endif
  12706. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  12707. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  12708. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  12709. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  12710. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  12711. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  12712. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  12713. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  12714. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  12715. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  12716. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  12717. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  12718. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  12719. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  12720. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  12721. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  12722. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  12723. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  12724. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  12725. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  12726. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  12727. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  12728. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  12729. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  12730. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  12731. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  12732. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
  12733. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  12734. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  12735. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  12736. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  12737. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
  12738. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  12739. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  12740. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  12741. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  12742. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  12743. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  12744. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  12745. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  12746. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  12747. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  12748. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  12749. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  12750. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  12751. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  12752. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  12753. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  12754. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12755. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  12756. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  12757. #endif
  12758. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  12759. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  12760. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  12761. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  12762. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  12763. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  12764. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  12765. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  12766. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  12767. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  12768. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  12769. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  12770. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
  12771. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  12772. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  12773. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  12774. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  12775. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
  12776. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
  12777. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  12778. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  12779. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  12780. u8,u8,int,int*);
  12781. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  12782. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
  12783. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  12784. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  12785. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  12786. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  12787. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  12788. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  12789. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  12790. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  12791. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  12792. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  12793. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  12794. #if SELECTTRACE_ENABLED
  12795. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  12796. #else
  12797. # define sqlite3SelectSetName(A,B)
  12798. #endif
  12799. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  12800. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  12801. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  12802. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  12803. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  12804. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  12805. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  12806. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  12807. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  12808. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  12809. #endif
  12810. #ifndef SQLITE_OMIT_TRIGGER
  12811. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  12812. Expr*,int, int);
  12813. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  12814. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  12815. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  12816. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  12817. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  12818. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  12819. int, int, int);
  12820. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  12821. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  12822. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  12823. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  12824. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  12825. Select*,u8);
  12826. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  12827. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  12828. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  12829. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  12830. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  12831. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  12832. #else
  12833. # define sqlite3TriggersExist(B,C,D,E,F) 0
  12834. # define sqlite3DeleteTrigger(A,B)
  12835. # define sqlite3DropTriggerPtr(A,B)
  12836. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  12837. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  12838. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  12839. # define sqlite3TriggerList(X, Y) 0
  12840. # define sqlite3ParseToplevel(p) p
  12841. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  12842. #endif
  12843. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  12844. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  12845. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  12846. #ifndef SQLITE_OMIT_AUTHORIZATION
  12847. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  12848. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  12849. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  12850. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  12851. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  12852. #else
  12853. # define sqlite3AuthRead(a,b,c,d)
  12854. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  12855. # define sqlite3AuthContextPush(a,b,c)
  12856. # define sqlite3AuthContextPop(a) ((void)(a))
  12857. #endif
  12858. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  12859. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  12860. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  12861. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  12862. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  12863. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  12864. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  12865. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  12866. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  12867. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  12868. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  12869. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  12870. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  12871. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  12872. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  12873. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  12874. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12875. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  12876. #endif
  12877. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  12878. /*
  12879. ** Routines to read and write variable-length integers. These used to
  12880. ** be defined locally, but now we use the varint routines in the util.c
  12881. ** file.
  12882. */
  12883. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  12884. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  12885. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  12886. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  12887. /*
  12888. ** The common case is for a varint to be a single byte. They following
  12889. ** macros handle the common case without a procedure call, but then call
  12890. ** the procedure for larger varints.
  12891. */
  12892. #define getVarint32(A,B) \
  12893. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  12894. #define putVarint32(A,B) \
  12895. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  12896. sqlite3PutVarint((A),(B)))
  12897. #define getVarint sqlite3GetVarint
  12898. #define putVarint sqlite3PutVarint
  12899. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  12900. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  12901. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  12902. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  12903. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  12904. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  12905. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  12906. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  12907. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  12908. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  12909. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  12910. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  12911. #if defined(SQLITE_NEED_ERR_NAME)
  12912. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  12913. #endif
  12914. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  12915. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  12916. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  12917. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  12918. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  12919. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
  12920. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  12921. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  12922. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  12923. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  12924. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  12925. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  12926. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  12927. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  12928. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  12929. #ifdef SQLITE_ENABLE_8_3_NAMES
  12930. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  12931. #else
  12932. # define sqlite3FileSuffix3(X,Y)
  12933. #endif
  12934. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  12935. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  12936. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  12937. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  12938. void(*)(void*));
  12939. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  12940. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  12941. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  12942. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  12943. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  12944. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  12945. #ifndef SQLITE_AMALGAMATION
  12946. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  12947. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  12948. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  12949. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  12950. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  12951. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12952. #ifndef SQLITE_OMIT_WSD
  12953. SQLITE_PRIVATE int sqlite3PendingByte;
  12954. #endif
  12955. #endif
  12956. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  12957. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  12958. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  12959. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  12960. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  12961. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  12962. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  12963. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  12964. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  12965. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p);
  12966. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  12967. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  12968. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  12969. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  12970. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  12971. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  12972. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  12973. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  12974. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  12975. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  12976. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  12977. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  12978. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  12979. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  12980. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  12981. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  12982. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  12983. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  12984. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  12985. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  12986. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  12987. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  12988. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  12989. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  12990. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  12991. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  12992. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  12993. #ifdef SQLITE_DEBUG
  12994. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  12995. #endif
  12996. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  12997. void (*)(sqlite3_context*,int,sqlite3_value **),
  12998. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  12999. FuncDestructor *pDestructor
  13000. );
  13001. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  13002. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  13003. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
  13004. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  13005. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  13006. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  13007. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  13008. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  13009. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  13010. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  13011. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  13012. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  13013. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  13014. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  13015. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  13016. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  13017. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  13018. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  13019. #endif
  13020. /*
  13021. ** The interface to the LEMON-generated parser
  13022. */
  13023. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  13024. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  13025. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  13026. #ifdef YYTRACKMAXSTACKDEPTH
  13027. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  13028. #endif
  13029. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  13030. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  13031. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  13032. #else
  13033. # define sqlite3CloseExtensions(X)
  13034. #endif
  13035. #ifndef SQLITE_OMIT_SHARED_CACHE
  13036. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  13037. #else
  13038. #define sqlite3TableLock(v,w,x,y,z)
  13039. #endif
  13040. #ifdef SQLITE_TEST
  13041. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  13042. #endif
  13043. #ifdef SQLITE_OMIT_VIRTUALTABLE
  13044. # define sqlite3VtabClear(Y)
  13045. # define sqlite3VtabSync(X,Y) SQLITE_OK
  13046. # define sqlite3VtabRollback(X)
  13047. # define sqlite3VtabCommit(X)
  13048. # define sqlite3VtabInSync(db) 0
  13049. # define sqlite3VtabLock(X)
  13050. # define sqlite3VtabUnlock(X)
  13051. # define sqlite3VtabUnlockList(X)
  13052. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  13053. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  13054. #else
  13055. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  13056. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  13057. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  13058. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  13059. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  13060. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  13061. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  13062. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  13063. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  13064. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  13065. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  13066. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  13067. #endif
  13068. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  13069. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  13070. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  13071. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  13072. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  13073. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  13074. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  13075. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  13076. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  13077. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  13078. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  13079. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  13080. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  13081. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  13082. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  13083. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  13084. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  13085. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  13086. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  13087. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  13088. #ifndef SQLITE_OMIT_WAL
  13089. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  13090. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  13091. #endif
  13092. #ifndef SQLITE_OMIT_CTE
  13093. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  13094. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  13095. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  13096. #else
  13097. #define sqlite3WithPush(x,y,z)
  13098. #define sqlite3WithDelete(x,y)
  13099. #endif
  13100. /* Declarations for functions in fkey.c. All of these are replaced by
  13101. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  13102. ** key functionality is available. If OMIT_TRIGGER is defined but
  13103. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  13104. ** this case foreign keys are parsed, but no other functionality is
  13105. ** provided (enforcement of FK constraints requires the triggers sub-system).
  13106. */
  13107. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  13108. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  13109. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  13110. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  13111. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  13112. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  13113. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  13114. #else
  13115. #define sqlite3FkActions(a,b,c,d,e,f)
  13116. #define sqlite3FkCheck(a,b,c,d,e,f)
  13117. #define sqlite3FkDropTable(a,b,c)
  13118. #define sqlite3FkOldmask(a,b) 0
  13119. #define sqlite3FkRequired(a,b,c,d) 0
  13120. #endif
  13121. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13122. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  13123. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  13124. #else
  13125. #define sqlite3FkDelete(a,b)
  13126. #define sqlite3FkLocateIndex(a,b,c,d,e)
  13127. #endif
  13128. /*
  13129. ** Available fault injectors. Should be numbered beginning with 0.
  13130. */
  13131. #define SQLITE_FAULTINJECTOR_MALLOC 0
  13132. #define SQLITE_FAULTINJECTOR_COUNT 1
  13133. /*
  13134. ** The interface to the code in fault.c used for identifying "benign"
  13135. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  13136. ** is not defined.
  13137. */
  13138. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13139. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  13140. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  13141. #else
  13142. #define sqlite3BeginBenignMalloc()
  13143. #define sqlite3EndBenignMalloc()
  13144. #endif
  13145. /*
  13146. ** Allowed return values from sqlite3FindInIndex()
  13147. */
  13148. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  13149. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  13150. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  13151. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  13152. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  13153. /*
  13154. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  13155. */
  13156. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  13157. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  13158. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  13159. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
  13160. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  13161. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  13162. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  13163. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  13164. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  13165. #else
  13166. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  13167. #define sqlite3JournalExists(p) 1
  13168. #endif
  13169. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  13170. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  13171. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  13172. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
  13173. #if SQLITE_MAX_EXPR_DEPTH>0
  13174. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  13175. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  13176. #else
  13177. #define sqlite3SelectExprHeight(x) 0
  13178. #define sqlite3ExprCheckHeight(x,y)
  13179. #endif
  13180. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  13181. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  13182. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  13183. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  13184. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  13185. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  13186. #else
  13187. #define sqlite3ConnectionBlocked(x,y)
  13188. #define sqlite3ConnectionUnlocked(x)
  13189. #define sqlite3ConnectionClosed(x)
  13190. #endif
  13191. #ifdef SQLITE_DEBUG
  13192. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  13193. #endif
  13194. /*
  13195. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  13196. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  13197. ** print I/O tracing messages.
  13198. */
  13199. #ifdef SQLITE_ENABLE_IOTRACE
  13200. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  13201. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  13202. SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
  13203. #else
  13204. # define IOTRACE(A)
  13205. # define sqlite3VdbeIOTraceSql(X)
  13206. #endif
  13207. /*
  13208. ** These routines are available for the mem2.c debugging memory allocator
  13209. ** only. They are used to verify that different "types" of memory
  13210. ** allocations are properly tracked by the system.
  13211. **
  13212. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  13213. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  13214. ** a single bit set.
  13215. **
  13216. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  13217. ** argument match the type set by the previous sqlite3MemdebugSetType().
  13218. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  13219. **
  13220. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  13221. ** argument match the type set by the previous sqlite3MemdebugSetType().
  13222. **
  13223. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  13224. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  13225. ** it might have been allocated by lookaside, except the allocation was
  13226. ** too large or lookaside was already full. It is important to verify
  13227. ** that allocations that might have been satisfied by lookaside are not
  13228. ** passed back to non-lookaside free() routines. Asserts such as the
  13229. ** example above are placed on the non-lookaside free() routines to verify
  13230. ** this constraint.
  13231. **
  13232. ** All of this is no-op for a production build. It only comes into
  13233. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  13234. */
  13235. #ifdef SQLITE_MEMDEBUG
  13236. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  13237. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  13238. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  13239. #else
  13240. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  13241. # define sqlite3MemdebugHasType(X,Y) 1
  13242. # define sqlite3MemdebugNoType(X,Y) 1
  13243. #endif
  13244. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  13245. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  13246. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  13247. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  13248. /*
  13249. ** Threading interface
  13250. */
  13251. #if SQLITE_MAX_WORKER_THREADS>0
  13252. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  13253. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  13254. #endif
  13255. #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
  13256. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
  13257. #endif
  13258. #endif /* _SQLITEINT_H_ */
  13259. /************** End of sqliteInt.h *******************************************/
  13260. /************** Begin file global.c ******************************************/
  13261. /*
  13262. ** 2008 June 13
  13263. **
  13264. ** The author disclaims copyright to this source code. In place of
  13265. ** a legal notice, here is a blessing:
  13266. **
  13267. ** May you do good and not evil.
  13268. ** May you find forgiveness for yourself and forgive others.
  13269. ** May you share freely, never taking more than you give.
  13270. **
  13271. *************************************************************************
  13272. **
  13273. ** This file contains definitions of global variables and constants.
  13274. */
  13275. /* #include "sqliteInt.h" */
  13276. /* An array to map all upper-case characters into their corresponding
  13277. ** lower-case character.
  13278. **
  13279. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  13280. ** handle case conversions for the UTF character set since the tables
  13281. ** involved are nearly as big or bigger than SQLite itself.
  13282. */
  13283. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  13284. #ifdef SQLITE_ASCII
  13285. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  13286. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  13287. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  13288. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  13289. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  13290. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  13291. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  13292. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  13293. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  13294. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  13295. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  13296. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  13297. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  13298. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  13299. 252,253,254,255
  13300. #endif
  13301. #ifdef SQLITE_EBCDIC
  13302. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  13303. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  13304. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  13305. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  13306. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  13307. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  13308. 96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
  13309. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
  13310. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  13311. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
  13312. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  13313. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  13314. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  13315. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  13316. 224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
  13317. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
  13318. #endif
  13319. };
  13320. /*
  13321. ** The following 256 byte lookup table is used to support SQLites built-in
  13322. ** equivalents to the following standard library functions:
  13323. **
  13324. ** isspace() 0x01
  13325. ** isalpha() 0x02
  13326. ** isdigit() 0x04
  13327. ** isalnum() 0x06
  13328. ** isxdigit() 0x08
  13329. ** toupper() 0x20
  13330. ** SQLite identifier character 0x40
  13331. **
  13332. ** Bit 0x20 is set if the mapped character requires translation to upper
  13333. ** case. i.e. if the character is a lower-case ASCII character.
  13334. ** If x is a lower-case ASCII character, then its upper-case equivalent
  13335. ** is (x - 0x20). Therefore toupper() can be implemented as:
  13336. **
  13337. ** (x & ~(map[x]&0x20))
  13338. **
  13339. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  13340. ** array. tolower() is used more often than toupper() by SQLite.
  13341. **
  13342. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  13343. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  13344. ** non-ASCII UTF character. Hence the test for whether or not a character is
  13345. ** part of an identifier is 0x46.
  13346. **
  13347. ** SQLite's versions are identical to the standard versions assuming a
  13348. ** locale of "C". They are implemented as macros in sqliteInt.h.
  13349. */
  13350. #ifdef SQLITE_ASCII
  13351. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  13352. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  13353. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  13354. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  13355. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  13356. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  13357. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  13358. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  13359. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  13360. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  13361. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  13362. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  13363. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  13364. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  13365. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  13366. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  13367. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  13368. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  13369. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  13370. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  13371. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  13372. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  13373. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  13374. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  13375. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  13376. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  13377. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  13378. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  13379. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  13380. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  13381. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  13382. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  13383. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  13384. };
  13385. #endif
  13386. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  13387. ** compatibility for legacy applications, the URI filename capability is
  13388. ** disabled by default.
  13389. **
  13390. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  13391. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  13392. **
  13393. ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
  13394. ** disabled. The default value may be changed by compiling with the
  13395. ** SQLITE_USE_URI symbol defined.
  13396. */
  13397. #ifndef SQLITE_USE_URI
  13398. # define SQLITE_USE_URI 0
  13399. #endif
  13400. /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
  13401. ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
  13402. ** that compile-time option is omitted.
  13403. */
  13404. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  13405. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  13406. #endif
  13407. /* The minimum PMA size is set to this value multiplied by the database
  13408. ** page size in bytes.
  13409. */
  13410. #ifndef SQLITE_SORTER_PMASZ
  13411. # define SQLITE_SORTER_PMASZ 250
  13412. #endif
  13413. /*
  13414. ** The following singleton contains the global configuration for
  13415. ** the SQLite library.
  13416. */
  13417. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  13418. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  13419. 1, /* bCoreMutex */
  13420. SQLITE_THREADSAFE==1, /* bFullMutex */
  13421. SQLITE_USE_URI, /* bOpenUri */
  13422. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  13423. 0x7ffffffe, /* mxStrlen */
  13424. 0, /* neverCorrupt */
  13425. 128, /* szLookaside */
  13426. 500, /* nLookaside */
  13427. {0,0,0,0,0,0,0,0}, /* m */
  13428. {0,0,0,0,0,0,0,0,0}, /* mutex */
  13429. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  13430. (void*)0, /* pHeap */
  13431. 0, /* nHeap */
  13432. 0, 0, /* mnHeap, mxHeap */
  13433. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  13434. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  13435. (void*)0, /* pScratch */
  13436. 0, /* szScratch */
  13437. 0, /* nScratch */
  13438. (void*)0, /* pPage */
  13439. 0, /* szPage */
  13440. SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
  13441. 0, /* mxParserStack */
  13442. 0, /* sharedCacheEnabled */
  13443. SQLITE_SORTER_PMASZ, /* szPma */
  13444. /* All the rest should always be initialized to zero */
  13445. 0, /* isInit */
  13446. 0, /* inProgress */
  13447. 0, /* isMutexInit */
  13448. 0, /* isMallocInit */
  13449. 0, /* isPCacheInit */
  13450. 0, /* nRefInitMutex */
  13451. 0, /* pInitMutex */
  13452. 0, /* xLog */
  13453. 0, /* pLogArg */
  13454. #ifdef SQLITE_ENABLE_SQLLOG
  13455. 0, /* xSqllog */
  13456. 0, /* pSqllogArg */
  13457. #endif
  13458. #ifdef SQLITE_VDBE_COVERAGE
  13459. 0, /* xVdbeBranch */
  13460. 0, /* pVbeBranchArg */
  13461. #endif
  13462. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13463. 0, /* xTestCallback */
  13464. #endif
  13465. 0 /* bLocaltimeFault */
  13466. };
  13467. /*
  13468. ** Hash table for global functions - functions common to all
  13469. ** database connections. After initialization, this table is
  13470. ** read-only.
  13471. */
  13472. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  13473. /*
  13474. ** Constant tokens for values 0 and 1.
  13475. */
  13476. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  13477. { "0", 1 },
  13478. { "1", 1 }
  13479. };
  13480. /*
  13481. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  13482. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  13483. ** the database page that contains the pending byte. It never attempts
  13484. ** to read or write that page. The pending byte page is set assign
  13485. ** for use by the VFS layers as space for managing file locks.
  13486. **
  13487. ** During testing, it is often desirable to move the pending byte to
  13488. ** a different position in the file. This allows code that has to
  13489. ** deal with the pending byte to run on files that are much smaller
  13490. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  13491. ** move the pending byte.
  13492. **
  13493. ** IMPORTANT: Changing the pending byte to any value other than
  13494. ** 0x40000000 results in an incompatible database file format!
  13495. ** Changing the pending byte during operation will result in undefined
  13496. ** and incorrect behavior.
  13497. */
  13498. #ifndef SQLITE_OMIT_WSD
  13499. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  13500. #endif
  13501. /* #include "opcodes.h" */
  13502. /*
  13503. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  13504. ** created by mkopcodeh.awk during compilation. Data is obtained
  13505. ** from the comments following the "case OP_xxxx:" statements in
  13506. ** the vdbe.c file.
  13507. */
  13508. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  13509. /************** End of global.c **********************************************/
  13510. /************** Begin file ctime.c *******************************************/
  13511. /*
  13512. ** 2010 February 23
  13513. **
  13514. ** The author disclaims copyright to this source code. In place of
  13515. ** a legal notice, here is a blessing:
  13516. **
  13517. ** May you do good and not evil.
  13518. ** May you find forgiveness for yourself and forgive others.
  13519. ** May you share freely, never taking more than you give.
  13520. **
  13521. *************************************************************************
  13522. **
  13523. ** This file implements routines used to report what compile-time options
  13524. ** SQLite was built with.
  13525. */
  13526. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  13527. /* #include "sqliteInt.h" */
  13528. /*
  13529. ** An array of names of all compile-time options. This array should
  13530. ** be sorted A-Z.
  13531. **
  13532. ** This array looks large, but in a typical installation actually uses
  13533. ** only a handful of compile-time options, so most times this array is usually
  13534. ** rather short and uses little memory space.
  13535. */
  13536. static const char * const azCompileOpt[] = {
  13537. /* These macros are provided to "stringify" the value of the define
  13538. ** for those options in which the value is meaningful. */
  13539. #define CTIMEOPT_VAL_(opt) #opt
  13540. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  13541. #if SQLITE_32BIT_ROWID
  13542. "32BIT_ROWID",
  13543. #endif
  13544. #if SQLITE_4_BYTE_ALIGNED_MALLOC
  13545. "4_BYTE_ALIGNED_MALLOC",
  13546. #endif
  13547. #if SQLITE_CASE_SENSITIVE_LIKE
  13548. "CASE_SENSITIVE_LIKE",
  13549. #endif
  13550. #if SQLITE_CHECK_PAGES
  13551. "CHECK_PAGES",
  13552. #endif
  13553. #if SQLITE_COVERAGE_TEST
  13554. "COVERAGE_TEST",
  13555. #endif
  13556. #if SQLITE_DEBUG
  13557. "DEBUG",
  13558. #endif
  13559. #if SQLITE_DEFAULT_LOCKING_MODE
  13560. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  13561. #endif
  13562. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  13563. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  13564. #endif
  13565. #if SQLITE_DISABLE_DIRSYNC
  13566. "DISABLE_DIRSYNC",
  13567. #endif
  13568. #if SQLITE_DISABLE_LFS
  13569. "DISABLE_LFS",
  13570. #endif
  13571. #if SQLITE_ENABLE_API_ARMOR
  13572. "ENABLE_API_ARMOR",
  13573. #endif
  13574. #if SQLITE_ENABLE_ATOMIC_WRITE
  13575. "ENABLE_ATOMIC_WRITE",
  13576. #endif
  13577. #if SQLITE_ENABLE_CEROD
  13578. "ENABLE_CEROD",
  13579. #endif
  13580. #if SQLITE_ENABLE_COLUMN_METADATA
  13581. "ENABLE_COLUMN_METADATA",
  13582. #endif
  13583. #if SQLITE_ENABLE_DBSTAT_VTAB
  13584. "ENABLE_DBSTAT_VTAB",
  13585. #endif
  13586. #if SQLITE_ENABLE_EXPENSIVE_ASSERT
  13587. "ENABLE_EXPENSIVE_ASSERT",
  13588. #endif
  13589. #if SQLITE_ENABLE_FTS1
  13590. "ENABLE_FTS1",
  13591. #endif
  13592. #if SQLITE_ENABLE_FTS2
  13593. "ENABLE_FTS2",
  13594. #endif
  13595. #if SQLITE_ENABLE_FTS3
  13596. "ENABLE_FTS3",
  13597. #endif
  13598. #if SQLITE_ENABLE_FTS3_PARENTHESIS
  13599. "ENABLE_FTS3_PARENTHESIS",
  13600. #endif
  13601. #if SQLITE_ENABLE_FTS4
  13602. "ENABLE_FTS4",
  13603. #endif
  13604. #if SQLITE_ENABLE_ICU
  13605. "ENABLE_ICU",
  13606. #endif
  13607. #if SQLITE_ENABLE_IOTRACE
  13608. "ENABLE_IOTRACE",
  13609. #endif
  13610. #if SQLITE_ENABLE_LOAD_EXTENSION
  13611. "ENABLE_LOAD_EXTENSION",
  13612. #endif
  13613. #if SQLITE_ENABLE_LOCKING_STYLE
  13614. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  13615. #endif
  13616. #if SQLITE_ENABLE_MEMORY_MANAGEMENT
  13617. "ENABLE_MEMORY_MANAGEMENT",
  13618. #endif
  13619. #if SQLITE_ENABLE_MEMSYS3
  13620. "ENABLE_MEMSYS3",
  13621. #endif
  13622. #if SQLITE_ENABLE_MEMSYS5
  13623. "ENABLE_MEMSYS5",
  13624. #endif
  13625. #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  13626. "ENABLE_OVERSIZE_CELL_CHECK",
  13627. #endif
  13628. #if SQLITE_ENABLE_RTREE
  13629. "ENABLE_RTREE",
  13630. #endif
  13631. #if defined(SQLITE_ENABLE_STAT4)
  13632. "ENABLE_STAT4",
  13633. #elif defined(SQLITE_ENABLE_STAT3)
  13634. "ENABLE_STAT3",
  13635. #endif
  13636. #if SQLITE_ENABLE_UNLOCK_NOTIFY
  13637. "ENABLE_UNLOCK_NOTIFY",
  13638. #endif
  13639. #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  13640. "ENABLE_UPDATE_DELETE_LIMIT",
  13641. #endif
  13642. #if SQLITE_HAS_CODEC
  13643. "HAS_CODEC",
  13644. #endif
  13645. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  13646. "HAVE_ISNAN",
  13647. #endif
  13648. #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13649. "HOMEGROWN_RECURSIVE_MUTEX",
  13650. #endif
  13651. #if SQLITE_IGNORE_AFP_LOCK_ERRORS
  13652. "IGNORE_AFP_LOCK_ERRORS",
  13653. #endif
  13654. #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  13655. "IGNORE_FLOCK_LOCK_ERRORS",
  13656. #endif
  13657. #ifdef SQLITE_INT64_TYPE
  13658. "INT64_TYPE",
  13659. #endif
  13660. #if SQLITE_LOCK_TRACE
  13661. "LOCK_TRACE",
  13662. #endif
  13663. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  13664. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  13665. #endif
  13666. #ifdef SQLITE_MAX_SCHEMA_RETRY
  13667. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  13668. #endif
  13669. #if SQLITE_MEMDEBUG
  13670. "MEMDEBUG",
  13671. #endif
  13672. #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13673. "MIXED_ENDIAN_64BIT_FLOAT",
  13674. #endif
  13675. #if SQLITE_NO_SYNC
  13676. "NO_SYNC",
  13677. #endif
  13678. #if SQLITE_OMIT_ALTERTABLE
  13679. "OMIT_ALTERTABLE",
  13680. #endif
  13681. #if SQLITE_OMIT_ANALYZE
  13682. "OMIT_ANALYZE",
  13683. #endif
  13684. #if SQLITE_OMIT_ATTACH
  13685. "OMIT_ATTACH",
  13686. #endif
  13687. #if SQLITE_OMIT_AUTHORIZATION
  13688. "OMIT_AUTHORIZATION",
  13689. #endif
  13690. #if SQLITE_OMIT_AUTOINCREMENT
  13691. "OMIT_AUTOINCREMENT",
  13692. #endif
  13693. #if SQLITE_OMIT_AUTOINIT
  13694. "OMIT_AUTOINIT",
  13695. #endif
  13696. #if SQLITE_OMIT_AUTOMATIC_INDEX
  13697. "OMIT_AUTOMATIC_INDEX",
  13698. #endif
  13699. #if SQLITE_OMIT_AUTORESET
  13700. "OMIT_AUTORESET",
  13701. #endif
  13702. #if SQLITE_OMIT_AUTOVACUUM
  13703. "OMIT_AUTOVACUUM",
  13704. #endif
  13705. #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
  13706. "OMIT_BETWEEN_OPTIMIZATION",
  13707. #endif
  13708. #if SQLITE_OMIT_BLOB_LITERAL
  13709. "OMIT_BLOB_LITERAL",
  13710. #endif
  13711. #if SQLITE_OMIT_BTREECOUNT
  13712. "OMIT_BTREECOUNT",
  13713. #endif
  13714. #if SQLITE_OMIT_BUILTIN_TEST
  13715. "OMIT_BUILTIN_TEST",
  13716. #endif
  13717. #if SQLITE_OMIT_CAST
  13718. "OMIT_CAST",
  13719. #endif
  13720. #if SQLITE_OMIT_CHECK
  13721. "OMIT_CHECK",
  13722. #endif
  13723. #if SQLITE_OMIT_COMPLETE
  13724. "OMIT_COMPLETE",
  13725. #endif
  13726. #if SQLITE_OMIT_COMPOUND_SELECT
  13727. "OMIT_COMPOUND_SELECT",
  13728. #endif
  13729. #if SQLITE_OMIT_CTE
  13730. "OMIT_CTE",
  13731. #endif
  13732. #if SQLITE_OMIT_DATETIME_FUNCS
  13733. "OMIT_DATETIME_FUNCS",
  13734. #endif
  13735. #if SQLITE_OMIT_DECLTYPE
  13736. "OMIT_DECLTYPE",
  13737. #endif
  13738. #if SQLITE_OMIT_DEPRECATED
  13739. "OMIT_DEPRECATED",
  13740. #endif
  13741. #if SQLITE_OMIT_DISKIO
  13742. "OMIT_DISKIO",
  13743. #endif
  13744. #if SQLITE_OMIT_EXPLAIN
  13745. "OMIT_EXPLAIN",
  13746. #endif
  13747. #if SQLITE_OMIT_FLAG_PRAGMAS
  13748. "OMIT_FLAG_PRAGMAS",
  13749. #endif
  13750. #if SQLITE_OMIT_FLOATING_POINT
  13751. "OMIT_FLOATING_POINT",
  13752. #endif
  13753. #if SQLITE_OMIT_FOREIGN_KEY
  13754. "OMIT_FOREIGN_KEY",
  13755. #endif
  13756. #if SQLITE_OMIT_GET_TABLE
  13757. "OMIT_GET_TABLE",
  13758. #endif
  13759. #if SQLITE_OMIT_INCRBLOB
  13760. "OMIT_INCRBLOB",
  13761. #endif
  13762. #if SQLITE_OMIT_INTEGRITY_CHECK
  13763. "OMIT_INTEGRITY_CHECK",
  13764. #endif
  13765. #if SQLITE_OMIT_LIKE_OPTIMIZATION
  13766. "OMIT_LIKE_OPTIMIZATION",
  13767. #endif
  13768. #if SQLITE_OMIT_LOAD_EXTENSION
  13769. "OMIT_LOAD_EXTENSION",
  13770. #endif
  13771. #if SQLITE_OMIT_LOCALTIME
  13772. "OMIT_LOCALTIME",
  13773. #endif
  13774. #if SQLITE_OMIT_LOOKASIDE
  13775. "OMIT_LOOKASIDE",
  13776. #endif
  13777. #if SQLITE_OMIT_MEMORYDB
  13778. "OMIT_MEMORYDB",
  13779. #endif
  13780. #if SQLITE_OMIT_OR_OPTIMIZATION
  13781. "OMIT_OR_OPTIMIZATION",
  13782. #endif
  13783. #if SQLITE_OMIT_PAGER_PRAGMAS
  13784. "OMIT_PAGER_PRAGMAS",
  13785. #endif
  13786. #if SQLITE_OMIT_PRAGMA
  13787. "OMIT_PRAGMA",
  13788. #endif
  13789. #if SQLITE_OMIT_PROGRESS_CALLBACK
  13790. "OMIT_PROGRESS_CALLBACK",
  13791. #endif
  13792. #if SQLITE_OMIT_QUICKBALANCE
  13793. "OMIT_QUICKBALANCE",
  13794. #endif
  13795. #if SQLITE_OMIT_REINDEX
  13796. "OMIT_REINDEX",
  13797. #endif
  13798. #if SQLITE_OMIT_SCHEMA_PRAGMAS
  13799. "OMIT_SCHEMA_PRAGMAS",
  13800. #endif
  13801. #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  13802. "OMIT_SCHEMA_VERSION_PRAGMAS",
  13803. #endif
  13804. #if SQLITE_OMIT_SHARED_CACHE
  13805. "OMIT_SHARED_CACHE",
  13806. #endif
  13807. #if SQLITE_OMIT_SUBQUERY
  13808. "OMIT_SUBQUERY",
  13809. #endif
  13810. #if SQLITE_OMIT_TCL_VARIABLE
  13811. "OMIT_TCL_VARIABLE",
  13812. #endif
  13813. #if SQLITE_OMIT_TEMPDB
  13814. "OMIT_TEMPDB",
  13815. #endif
  13816. #if SQLITE_OMIT_TRACE
  13817. "OMIT_TRACE",
  13818. #endif
  13819. #if SQLITE_OMIT_TRIGGER
  13820. "OMIT_TRIGGER",
  13821. #endif
  13822. #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  13823. "OMIT_TRUNCATE_OPTIMIZATION",
  13824. #endif
  13825. #if SQLITE_OMIT_UTF16
  13826. "OMIT_UTF16",
  13827. #endif
  13828. #if SQLITE_OMIT_VACUUM
  13829. "OMIT_VACUUM",
  13830. #endif
  13831. #if SQLITE_OMIT_VIEW
  13832. "OMIT_VIEW",
  13833. #endif
  13834. #if SQLITE_OMIT_VIRTUALTABLE
  13835. "OMIT_VIRTUALTABLE",
  13836. #endif
  13837. #if SQLITE_OMIT_WAL
  13838. "OMIT_WAL",
  13839. #endif
  13840. #if SQLITE_OMIT_WSD
  13841. "OMIT_WSD",
  13842. #endif
  13843. #if SQLITE_OMIT_XFER_OPT
  13844. "OMIT_XFER_OPT",
  13845. #endif
  13846. #if SQLITE_PERFORMANCE_TRACE
  13847. "PERFORMANCE_TRACE",
  13848. #endif
  13849. #if SQLITE_PROXY_DEBUG
  13850. "PROXY_DEBUG",
  13851. #endif
  13852. #if SQLITE_RTREE_INT_ONLY
  13853. "RTREE_INT_ONLY",
  13854. #endif
  13855. #if SQLITE_SECURE_DELETE
  13856. "SECURE_DELETE",
  13857. #endif
  13858. #if SQLITE_SMALL_STACK
  13859. "SMALL_STACK",
  13860. #endif
  13861. #if SQLITE_SOUNDEX
  13862. "SOUNDEX",
  13863. #endif
  13864. #if SQLITE_SYSTEM_MALLOC
  13865. "SYSTEM_MALLOC",
  13866. #endif
  13867. #if SQLITE_TCL
  13868. "TCL",
  13869. #endif
  13870. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  13871. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  13872. #endif
  13873. #if SQLITE_TEST
  13874. "TEST",
  13875. #endif
  13876. #if defined(SQLITE_THREADSAFE)
  13877. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  13878. #endif
  13879. #if SQLITE_USE_ALLOCA
  13880. "USE_ALLOCA",
  13881. #endif
  13882. #if SQLITE_USER_AUTHENTICATION
  13883. "USER_AUTHENTICATION",
  13884. #endif
  13885. #if SQLITE_WIN32_MALLOC
  13886. "WIN32_MALLOC",
  13887. #endif
  13888. #if SQLITE_ZERO_MALLOC
  13889. "ZERO_MALLOC"
  13890. #endif
  13891. };
  13892. /*
  13893. ** Given the name of a compile-time option, return true if that option
  13894. ** was used and false if not.
  13895. **
  13896. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  13897. ** is not required for a match.
  13898. */
  13899. SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
  13900. int i, n;
  13901. #if SQLITE_ENABLE_API_ARMOR
  13902. if( zOptName==0 ){
  13903. (void)SQLITE_MISUSE_BKPT;
  13904. return 0;
  13905. }
  13906. #endif
  13907. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  13908. n = sqlite3Strlen30(zOptName);
  13909. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  13910. ** linear search is adequate. No need for a binary search. */
  13911. for(i=0; i<ArraySize(azCompileOpt); i++){
  13912. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  13913. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  13914. ){
  13915. return 1;
  13916. }
  13917. }
  13918. return 0;
  13919. }
  13920. /*
  13921. ** Return the N-th compile-time option string. If N is out of range,
  13922. ** return a NULL pointer.
  13923. */
  13924. SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
  13925. if( N>=0 && N<ArraySize(azCompileOpt) ){
  13926. return azCompileOpt[N];
  13927. }
  13928. return 0;
  13929. }
  13930. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  13931. /************** End of ctime.c ***********************************************/
  13932. /************** Begin file status.c ******************************************/
  13933. /*
  13934. ** 2008 June 18
  13935. **
  13936. ** The author disclaims copyright to this source code. In place of
  13937. ** a legal notice, here is a blessing:
  13938. **
  13939. ** May you do good and not evil.
  13940. ** May you find forgiveness for yourself and forgive others.
  13941. ** May you share freely, never taking more than you give.
  13942. **
  13943. *************************************************************************
  13944. **
  13945. ** This module implements the sqlite3_status() interface and related
  13946. ** functionality.
  13947. */
  13948. /* #include "sqliteInt.h" */
  13949. /************** Include vdbeInt.h in the middle of status.c ******************/
  13950. /************** Begin file vdbeInt.h *****************************************/
  13951. /*
  13952. ** 2003 September 6
  13953. **
  13954. ** The author disclaims copyright to this source code. In place of
  13955. ** a legal notice, here is a blessing:
  13956. **
  13957. ** May you do good and not evil.
  13958. ** May you find forgiveness for yourself and forgive others.
  13959. ** May you share freely, never taking more than you give.
  13960. **
  13961. *************************************************************************
  13962. ** This is the header file for information that is private to the
  13963. ** VDBE. This information used to all be at the top of the single
  13964. ** source code file "vdbe.c". When that file became too big (over
  13965. ** 6000 lines long) it was split up into several smaller files and
  13966. ** this header information was factored out.
  13967. */
  13968. #ifndef _VDBEINT_H_
  13969. #define _VDBEINT_H_
  13970. /*
  13971. ** The maximum number of times that a statement will try to reparse
  13972. ** itself before giving up and returning SQLITE_SCHEMA.
  13973. */
  13974. #ifndef SQLITE_MAX_SCHEMA_RETRY
  13975. # define SQLITE_MAX_SCHEMA_RETRY 50
  13976. #endif
  13977. /*
  13978. ** SQL is translated into a sequence of instructions to be
  13979. ** executed by a virtual machine. Each instruction is an instance
  13980. ** of the following structure.
  13981. */
  13982. typedef struct VdbeOp Op;
  13983. /*
  13984. ** Boolean values
  13985. */
  13986. typedef unsigned Bool;
  13987. /* Opaque type used by code in vdbesort.c */
  13988. typedef struct VdbeSorter VdbeSorter;
  13989. /* Opaque type used by the explainer */
  13990. typedef struct Explain Explain;
  13991. /* Elements of the linked list at Vdbe.pAuxData */
  13992. typedef struct AuxData AuxData;
  13993. /*
  13994. ** A cursor is a pointer into a single BTree within a database file.
  13995. ** The cursor can seek to a BTree entry with a particular key, or
  13996. ** loop over all entries of the Btree. You can also insert new BTree
  13997. ** entries or retrieve the key or data from the entry that the cursor
  13998. ** is currently pointing to.
  13999. **
  14000. ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
  14001. ** A pseudo-table is a single-row table implemented by registers.
  14002. **
  14003. ** Every cursor that the virtual machine has open is represented by an
  14004. ** instance of the following structure.
  14005. */
  14006. struct VdbeCursor {
  14007. BtCursor *pCursor; /* The cursor structure of the backend */
  14008. Btree *pBt; /* Separate file holding temporary table */
  14009. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  14010. int seekResult; /* Result of previous sqlite3BtreeMoveto() */
  14011. int pseudoTableReg; /* Register holding pseudotable content. */
  14012. i16 nField; /* Number of fields in the header */
  14013. u16 nHdrParsed; /* Number of header fields parsed so far */
  14014. #ifdef SQLITE_DEBUG
  14015. u8 seekOp; /* Most recent seek operation on this cursor */
  14016. #endif
  14017. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  14018. u8 nullRow; /* True if pointing to a row with no data */
  14019. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  14020. Bool isEphemeral:1; /* True for an ephemeral table */
  14021. Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
  14022. Bool isTable:1; /* True if a table requiring integer keys */
  14023. Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
  14024. Pgno pgnoRoot; /* Root page of the open btree cursor */
  14025. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  14026. i64 seqCount; /* Sequence counter */
  14027. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  14028. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  14029. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  14030. u64 maskUsed; /* Mask of columns used by this cursor */
  14031. #endif
  14032. /* Cached information about the header for the data record that the
  14033. ** cursor is currently pointing to. Only valid if cacheStatus matches
  14034. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  14035. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  14036. ** the cache is out of date.
  14037. **
  14038. ** aRow might point to (ephemeral) data for the current row, or it might
  14039. ** be NULL.
  14040. */
  14041. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  14042. u32 payloadSize; /* Total number of bytes in the record */
  14043. u32 szRow; /* Byte available in aRow */
  14044. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  14045. const u8 *aRow; /* Data for the current row, if all on one page */
  14046. u32 *aOffset; /* Pointer to aType[nField] */
  14047. u32 aType[1]; /* Type values for all entries in the record */
  14048. /* 2*nField extra array elements allocated for aType[], beyond the one
  14049. ** static element declared in the structure. nField total array slots for
  14050. ** aType[] and nField+1 array slots for aOffset[] */
  14051. };
  14052. typedef struct VdbeCursor VdbeCursor;
  14053. /*
  14054. ** When a sub-program is executed (OP_Program), a structure of this type
  14055. ** is allocated to store the current value of the program counter, as
  14056. ** well as the current memory cell array and various other frame specific
  14057. ** values stored in the Vdbe struct. When the sub-program is finished,
  14058. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  14059. ** restoring the state of the VM to as it was before the sub-program
  14060. ** began executing.
  14061. **
  14062. ** The memory for a VdbeFrame object is allocated and managed by a memory
  14063. ** cell in the parent (calling) frame. When the memory cell is deleted or
  14064. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  14065. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  14066. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  14067. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  14068. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  14069. ** child frame are released.
  14070. **
  14071. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  14072. ** set to NULL if the currently executing frame is the main program.
  14073. */
  14074. typedef struct VdbeFrame VdbeFrame;
  14075. struct VdbeFrame {
  14076. Vdbe *v; /* VM this frame belongs to */
  14077. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  14078. Op *aOp; /* Program instructions for parent frame */
  14079. i64 *anExec; /* Event counters from parent frame */
  14080. Mem *aMem; /* Array of memory cells for parent frame */
  14081. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  14082. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  14083. void *token; /* Copy of SubProgram.token */
  14084. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  14085. int nCursor; /* Number of entries in apCsr */
  14086. int pc; /* Program Counter in parent (calling) frame */
  14087. int nOp; /* Size of aOp array */
  14088. int nMem; /* Number of entries in aMem */
  14089. int nOnceFlag; /* Number of entries in aOnceFlag */
  14090. int nChildMem; /* Number of memory cells for child frame */
  14091. int nChildCsr; /* Number of cursors for child frame */
  14092. int nChange; /* Statement changes (Vdbe.nChange) */
  14093. int nDbChange; /* Value of db->nChange */
  14094. };
  14095. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  14096. /*
  14097. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  14098. */
  14099. #define CACHE_STALE 0
  14100. /*
  14101. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  14102. ** structures. Each Mem struct may cache multiple representations (string,
  14103. ** integer etc.) of the same value.
  14104. */
  14105. struct Mem {
  14106. union MemValue {
  14107. double r; /* Real value used when MEM_Real is set in flags */
  14108. i64 i; /* Integer value used when MEM_Int is set in flags */
  14109. int nZero; /* Used when bit MEM_Zero is set in flags */
  14110. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  14111. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  14112. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  14113. } u;
  14114. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  14115. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  14116. int n; /* Number of characters in string value, excluding '\0' */
  14117. char *z; /* String or BLOB value */
  14118. /* ShallowCopy only needs to copy the information above */
  14119. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  14120. int szMalloc; /* Size of the zMalloc allocation */
  14121. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  14122. sqlite3 *db; /* The associated database connection */
  14123. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  14124. #ifdef SQLITE_DEBUG
  14125. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  14126. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  14127. #endif
  14128. };
  14129. /*
  14130. ** Size of struct Mem not including the Mem.zMalloc member or anything that
  14131. ** follows.
  14132. */
  14133. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  14134. /* One or more of the following flags are set to indicate the validOK
  14135. ** representations of the value stored in the Mem struct.
  14136. **
  14137. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  14138. ** No other flags may be set in this case.
  14139. **
  14140. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  14141. ** Usually this is encoded in the same unicode encoding as the main
  14142. ** database (see below for exceptions). If the MEM_Term flag is also
  14143. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  14144. ** flags may coexist with the MEM_Str flag.
  14145. */
  14146. #define MEM_Null 0x0001 /* Value is NULL */
  14147. #define MEM_Str 0x0002 /* Value is a string */
  14148. #define MEM_Int 0x0004 /* Value is an integer */
  14149. #define MEM_Real 0x0008 /* Value is a real number */
  14150. #define MEM_Blob 0x0010 /* Value is a BLOB */
  14151. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  14152. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  14153. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  14154. #define MEM_Undefined 0x0080 /* Value is undefined */
  14155. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  14156. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  14157. /* Whenever Mem contains a valid string or blob representation, one of
  14158. ** the following flags must be set to determine the memory management
  14159. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  14160. ** string is \000 or \u0000 terminated
  14161. */
  14162. #define MEM_Term 0x0200 /* String rep is nul terminated */
  14163. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  14164. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  14165. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  14166. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  14167. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  14168. #ifdef SQLITE_OMIT_INCRBLOB
  14169. #undef MEM_Zero
  14170. #define MEM_Zero 0x0000
  14171. #endif
  14172. /*
  14173. ** Clear any existing type flags from a Mem and replace them with f
  14174. */
  14175. #define MemSetTypeFlag(p, f) \
  14176. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  14177. /*
  14178. ** Return true if a memory cell is not marked as invalid. This macro
  14179. ** is for use inside assert() statements only.
  14180. */
  14181. #ifdef SQLITE_DEBUG
  14182. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  14183. #endif
  14184. /*
  14185. ** Each auxiliary data pointer stored by a user defined function
  14186. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  14187. ** of this structure. All such structures associated with a single VM
  14188. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  14189. ** when the VM is halted (if not before).
  14190. */
  14191. struct AuxData {
  14192. int iOp; /* Instruction number of OP_Function opcode */
  14193. int iArg; /* Index of function argument. */
  14194. void *pAux; /* Aux data pointer */
  14195. void (*xDelete)(void *); /* Destructor for the aux data */
  14196. AuxData *pNext; /* Next element in list */
  14197. };
  14198. /*
  14199. ** The "context" argument for an installable function. A pointer to an
  14200. ** instance of this structure is the first argument to the routines used
  14201. ** implement the SQL functions.
  14202. **
  14203. ** There is a typedef for this structure in sqlite.h. So all routines,
  14204. ** even the public interface to SQLite, can use a pointer to this structure.
  14205. ** But this file is the only place where the internal details of this
  14206. ** structure are known.
  14207. **
  14208. ** This structure is defined inside of vdbeInt.h because it uses substructures
  14209. ** (Mem) which are only defined there.
  14210. */
  14211. struct sqlite3_context {
  14212. Mem *pOut; /* The return value is stored here */
  14213. FuncDef *pFunc; /* Pointer to function information */
  14214. Mem *pMem; /* Memory cell used to store aggregate context */
  14215. Vdbe *pVdbe; /* The VM that owns this context */
  14216. int iOp; /* Instruction number of OP_Function */
  14217. int isError; /* Error code returned by the function. */
  14218. u8 skipFlag; /* Skip accumulator loading if true */
  14219. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  14220. u8 argc; /* Number of arguments */
  14221. sqlite3_value *argv[1]; /* Argument set */
  14222. };
  14223. /*
  14224. ** An Explain object accumulates indented output which is helpful
  14225. ** in describing recursive data structures.
  14226. */
  14227. struct Explain {
  14228. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  14229. StrAccum str; /* The string being accumulated */
  14230. int nIndent; /* Number of elements in aIndent */
  14231. u16 aIndent[100]; /* Levels of indentation */
  14232. char zBase[100]; /* Initial space */
  14233. };
  14234. /* A bitfield type for use inside of structures. Always follow with :N where
  14235. ** N is the number of bits.
  14236. */
  14237. typedef unsigned bft; /* Bit Field Type */
  14238. typedef struct ScanStatus ScanStatus;
  14239. struct ScanStatus {
  14240. int addrExplain; /* OP_Explain for loop */
  14241. int addrLoop; /* Address of "loops" counter */
  14242. int addrVisit; /* Address of "rows visited" counter */
  14243. int iSelectID; /* The "Select-ID" for this loop */
  14244. LogEst nEst; /* Estimated output rows per loop */
  14245. char *zName; /* Name of table or index */
  14246. };
  14247. /*
  14248. ** An instance of the virtual machine. This structure contains the complete
  14249. ** state of the virtual machine.
  14250. **
  14251. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  14252. ** is really a pointer to an instance of this structure.
  14253. */
  14254. struct Vdbe {
  14255. sqlite3 *db; /* The database connection that owns this statement */
  14256. Op *aOp; /* Space to hold the virtual machine's program */
  14257. Mem *aMem; /* The memory locations */
  14258. Mem **apArg; /* Arguments to currently executing user function */
  14259. Mem *aColName; /* Column names to return */
  14260. Mem *pResultSet; /* Pointer to an array of results */
  14261. Parse *pParse; /* Parsing context used to create this Vdbe */
  14262. int nMem; /* Number of memory locations currently allocated */
  14263. int nOp; /* Number of instructions in the program */
  14264. int nCursor; /* Number of slots in apCsr[] */
  14265. u32 magic; /* Magic number for sanity checking */
  14266. char *zErrMsg; /* Error message written here */
  14267. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  14268. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  14269. Mem *aVar; /* Values for the OP_Variable opcode. */
  14270. char **azVar; /* Name of variables */
  14271. ynVar nVar; /* Number of entries in aVar[] */
  14272. ynVar nzVar; /* Number of entries in azVar[] */
  14273. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  14274. int pc; /* The program counter */
  14275. int rc; /* Value to return */
  14276. #ifdef SQLITE_DEBUG
  14277. int rcApp; /* errcode set by sqlite3_result_error_code() */
  14278. #endif
  14279. u16 nResColumn; /* Number of columns in one row of the result set */
  14280. u8 errorAction; /* Recovery action to do in case of an error */
  14281. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  14282. bft explain:2; /* True if EXPLAIN present on SQL command */
  14283. bft changeCntOn:1; /* True to update the change-counter */
  14284. bft expired:1; /* True if the VM needs to be recompiled */
  14285. bft runOnlyOnce:1; /* Automatically expire on reset */
  14286. bft usesStmtJournal:1; /* True if uses a statement journal */
  14287. bft readOnly:1; /* True for statements that do not write */
  14288. bft bIsReader:1; /* True for statements that read */
  14289. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  14290. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  14291. int nChange; /* Number of db changes made since last reset */
  14292. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  14293. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  14294. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  14295. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  14296. #ifndef SQLITE_OMIT_TRACE
  14297. i64 startTime; /* Time when query started - used for profiling */
  14298. #endif
  14299. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  14300. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  14301. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  14302. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  14303. char *zSql; /* Text of the SQL statement that generated this */
  14304. void *pFree; /* Free this when deleting the vdbe */
  14305. VdbeFrame *pFrame; /* Parent frame */
  14306. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  14307. int nFrame; /* Number of frames in pFrame list */
  14308. u32 expmask; /* Binding to these vars invalidates VM */
  14309. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  14310. int nOnceFlag; /* Size of array aOnceFlag[] */
  14311. u8 *aOnceFlag; /* Flags for OP_Once */
  14312. AuxData *pAuxData; /* Linked list of auxdata allocations */
  14313. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  14314. i64 *anExec; /* Number of times each op has been executed */
  14315. int nScan; /* Entries in aScan[] */
  14316. ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
  14317. #endif
  14318. };
  14319. /*
  14320. ** The following are allowed values for Vdbe.magic
  14321. */
  14322. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  14323. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  14324. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  14325. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  14326. /*
  14327. ** Function prototypes
  14328. */
  14329. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
  14330. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  14331. void sqliteVdbePopStack(Vdbe*,int);
  14332. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  14333. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  14334. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  14335. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  14336. #endif
  14337. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  14338. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  14339. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  14340. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  14341. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  14342. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  14343. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  14344. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  14345. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  14346. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  14347. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  14348. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  14349. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  14350. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  14351. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  14352. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  14353. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  14354. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  14355. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  14356. #ifdef SQLITE_OMIT_FLOATING_POINT
  14357. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  14358. #else
  14359. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  14360. #endif
  14361. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  14362. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  14363. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  14364. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  14365. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  14366. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  14367. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  14368. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  14369. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  14370. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  14371. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  14372. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  14373. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  14374. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
  14375. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  14376. #define VdbeMemDynamic(X) \
  14377. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  14378. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  14379. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  14380. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  14381. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  14382. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  14383. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  14384. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  14385. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  14386. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  14387. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  14388. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  14389. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  14390. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  14391. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  14392. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  14393. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  14394. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  14395. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  14396. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  14397. #else
  14398. # define sqlite3VdbeEnter(X)
  14399. # define sqlite3VdbeLeave(X)
  14400. #endif
  14401. #ifdef SQLITE_DEBUG
  14402. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  14403. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  14404. #endif
  14405. #ifndef SQLITE_OMIT_FOREIGN_KEY
  14406. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  14407. #else
  14408. # define sqlite3VdbeCheckFk(p,i) 0
  14409. #endif
  14410. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  14411. #ifdef SQLITE_DEBUG
  14412. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  14413. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  14414. #endif
  14415. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  14416. #ifndef SQLITE_OMIT_INCRBLOB
  14417. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  14418. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  14419. #else
  14420. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  14421. #define ExpandBlob(P) SQLITE_OK
  14422. #endif
  14423. #endif /* !defined(_VDBEINT_H_) */
  14424. /************** End of vdbeInt.h *********************************************/
  14425. /************** Continuing where we left off in status.c *********************/
  14426. /*
  14427. ** Variables in which to record status information.
  14428. */
  14429. typedef struct sqlite3StatType sqlite3StatType;
  14430. static SQLITE_WSD struct sqlite3StatType {
  14431. #if SQLITE_PTRSIZE>4
  14432. sqlite3_int64 nowValue[10]; /* Current value */
  14433. sqlite3_int64 mxValue[10]; /* Maximum value */
  14434. #else
  14435. u32 nowValue[10]; /* Current value */
  14436. u32 mxValue[10]; /* Maximum value */
  14437. #endif
  14438. } sqlite3Stat = { {0,}, {0,} };
  14439. /*
  14440. ** Elements of sqlite3Stat[] are protected by either the memory allocator
  14441. ** mutex, or by the pcache1 mutex. The following array determines which.
  14442. */
  14443. static const char statMutex[] = {
  14444. 0, /* SQLITE_STATUS_MEMORY_USED */
  14445. 1, /* SQLITE_STATUS_PAGECACHE_USED */
  14446. 1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
  14447. 0, /* SQLITE_STATUS_SCRATCH_USED */
  14448. 0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
  14449. 0, /* SQLITE_STATUS_MALLOC_SIZE */
  14450. 0, /* SQLITE_STATUS_PARSER_STACK */
  14451. 1, /* SQLITE_STATUS_PAGECACHE_SIZE */
  14452. 0, /* SQLITE_STATUS_SCRATCH_SIZE */
  14453. 0, /* SQLITE_STATUS_MALLOC_COUNT */
  14454. };
  14455. /* The "wsdStat" macro will resolve to the status information
  14456. ** state vector. If writable static data is unsupported on the target,
  14457. ** we have to locate the state vector at run-time. In the more common
  14458. ** case where writable static data is supported, wsdStat can refer directly
  14459. ** to the "sqlite3Stat" state vector declared above.
  14460. */
  14461. #ifdef SQLITE_OMIT_WSD
  14462. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  14463. # define wsdStat x[0]
  14464. #else
  14465. # define wsdStatInit
  14466. # define wsdStat sqlite3Stat
  14467. #endif
  14468. /*
  14469. ** Return the current value of a status parameter. The caller must
  14470. ** be holding the appropriate mutex.
  14471. */
  14472. SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
  14473. wsdStatInit;
  14474. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14475. assert( op>=0 && op<ArraySize(statMutex) );
  14476. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14477. : sqlite3MallocMutex()) );
  14478. return wsdStat.nowValue[op];
  14479. }
  14480. /*
  14481. ** Add N to the value of a status record. The caller must hold the
  14482. ** appropriate mutex. (Locking is checked by assert()).
  14483. **
  14484. ** The StatusUp() routine can accept positive or negative values for N.
  14485. ** The value of N is added to the current status value and the high-water
  14486. ** mark is adjusted if necessary.
  14487. **
  14488. ** The StatusDown() routine lowers the current value by N. The highwater
  14489. ** mark is unchanged. N must be non-negative for StatusDown().
  14490. */
  14491. SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
  14492. wsdStatInit;
  14493. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14494. assert( op>=0 && op<ArraySize(statMutex) );
  14495. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14496. : sqlite3MallocMutex()) );
  14497. wsdStat.nowValue[op] += N;
  14498. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  14499. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  14500. }
  14501. }
  14502. SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
  14503. wsdStatInit;
  14504. assert( N>=0 );
  14505. assert( op>=0 && op<ArraySize(statMutex) );
  14506. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14507. : sqlite3MallocMutex()) );
  14508. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14509. wsdStat.nowValue[op] -= N;
  14510. }
  14511. /*
  14512. ** Set the value of a status to X. The highwater mark is adjusted if
  14513. ** necessary. The caller must hold the appropriate mutex.
  14514. */
  14515. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  14516. wsdStatInit;
  14517. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  14518. assert( op>=0 && op<ArraySize(statMutex) );
  14519. assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
  14520. : sqlite3MallocMutex()) );
  14521. wsdStat.nowValue[op] = X;
  14522. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  14523. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  14524. }
  14525. }
  14526. /*
  14527. ** Query status information.
  14528. */
  14529. SQLITE_API int SQLITE_STDCALL sqlite3_status64(
  14530. int op,
  14531. sqlite3_int64 *pCurrent,
  14532. sqlite3_int64 *pHighwater,
  14533. int resetFlag
  14534. ){
  14535. sqlite3_mutex *pMutex;
  14536. wsdStatInit;
  14537. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  14538. return SQLITE_MISUSE_BKPT;
  14539. }
  14540. #ifdef SQLITE_ENABLE_API_ARMOR
  14541. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  14542. #endif
  14543. pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
  14544. sqlite3_mutex_enter(pMutex);
  14545. *pCurrent = wsdStat.nowValue[op];
  14546. *pHighwater = wsdStat.mxValue[op];
  14547. if( resetFlag ){
  14548. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  14549. }
  14550. sqlite3_mutex_leave(pMutex);
  14551. (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
  14552. return SQLITE_OK;
  14553. }
  14554. SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  14555. sqlite3_int64 iCur, iHwtr;
  14556. int rc;
  14557. #ifdef SQLITE_ENABLE_API_ARMOR
  14558. if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
  14559. #endif
  14560. rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
  14561. if( rc==0 ){
  14562. *pCurrent = (int)iCur;
  14563. *pHighwater = (int)iHwtr;
  14564. }
  14565. return rc;
  14566. }
  14567. /*
  14568. ** Query status information for a single database connection
  14569. */
  14570. SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
  14571. sqlite3 *db, /* The database connection whose status is desired */
  14572. int op, /* Status verb */
  14573. int *pCurrent, /* Write current value here */
  14574. int *pHighwater, /* Write high-water mark here */
  14575. int resetFlag /* Reset high-water mark if true */
  14576. ){
  14577. int rc = SQLITE_OK; /* Return code */
  14578. #ifdef SQLITE_ENABLE_API_ARMOR
  14579. if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
  14580. return SQLITE_MISUSE_BKPT;
  14581. }
  14582. #endif
  14583. sqlite3_mutex_enter(db->mutex);
  14584. switch( op ){
  14585. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  14586. *pCurrent = db->lookaside.nOut;
  14587. *pHighwater = db->lookaside.mxOut;
  14588. if( resetFlag ){
  14589. db->lookaside.mxOut = db->lookaside.nOut;
  14590. }
  14591. break;
  14592. }
  14593. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  14594. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  14595. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  14596. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  14597. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  14598. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  14599. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  14600. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  14601. *pCurrent = 0;
  14602. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  14603. if( resetFlag ){
  14604. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  14605. }
  14606. break;
  14607. }
  14608. /*
  14609. ** Return an approximation for the amount of memory currently used
  14610. ** by all pagers associated with the given database connection. The
  14611. ** highwater mark is meaningless and is returned as zero.
  14612. */
  14613. case SQLITE_DBSTATUS_CACHE_USED: {
  14614. int totalUsed = 0;
  14615. int i;
  14616. sqlite3BtreeEnterAll(db);
  14617. for(i=0; i<db->nDb; i++){
  14618. Btree *pBt = db->aDb[i].pBt;
  14619. if( pBt ){
  14620. Pager *pPager = sqlite3BtreePager(pBt);
  14621. totalUsed += sqlite3PagerMemUsed(pPager);
  14622. }
  14623. }
  14624. sqlite3BtreeLeaveAll(db);
  14625. *pCurrent = totalUsed;
  14626. *pHighwater = 0;
  14627. break;
  14628. }
  14629. /*
  14630. ** *pCurrent gets an accurate estimate of the amount of memory used
  14631. ** to store the schema for all databases (main, temp, and any ATTACHed
  14632. ** databases. *pHighwater is set to zero.
  14633. */
  14634. case SQLITE_DBSTATUS_SCHEMA_USED: {
  14635. int i; /* Used to iterate through schemas */
  14636. int nByte = 0; /* Used to accumulate return value */
  14637. sqlite3BtreeEnterAll(db);
  14638. db->pnBytesFreed = &nByte;
  14639. for(i=0; i<db->nDb; i++){
  14640. Schema *pSchema = db->aDb[i].pSchema;
  14641. if( ALWAYS(pSchema!=0) ){
  14642. HashElem *p;
  14643. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  14644. pSchema->tblHash.count
  14645. + pSchema->trigHash.count
  14646. + pSchema->idxHash.count
  14647. + pSchema->fkeyHash.count
  14648. );
  14649. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  14650. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  14651. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  14652. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  14653. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  14654. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  14655. }
  14656. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  14657. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  14658. }
  14659. }
  14660. }
  14661. db->pnBytesFreed = 0;
  14662. sqlite3BtreeLeaveAll(db);
  14663. *pHighwater = 0;
  14664. *pCurrent = nByte;
  14665. break;
  14666. }
  14667. /*
  14668. ** *pCurrent gets an accurate estimate of the amount of memory used
  14669. ** to store all prepared statements.
  14670. ** *pHighwater is set to zero.
  14671. */
  14672. case SQLITE_DBSTATUS_STMT_USED: {
  14673. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  14674. int nByte = 0; /* Used to accumulate return value */
  14675. db->pnBytesFreed = &nByte;
  14676. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  14677. sqlite3VdbeClearObject(db, pVdbe);
  14678. sqlite3DbFree(db, pVdbe);
  14679. }
  14680. db->pnBytesFreed = 0;
  14681. *pHighwater = 0; /* IMP: R-64479-57858 */
  14682. *pCurrent = nByte;
  14683. break;
  14684. }
  14685. /*
  14686. ** Set *pCurrent to the total cache hits or misses encountered by all
  14687. ** pagers the database handle is connected to. *pHighwater is always set
  14688. ** to zero.
  14689. */
  14690. case SQLITE_DBSTATUS_CACHE_HIT:
  14691. case SQLITE_DBSTATUS_CACHE_MISS:
  14692. case SQLITE_DBSTATUS_CACHE_WRITE:{
  14693. int i;
  14694. int nRet = 0;
  14695. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  14696. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  14697. for(i=0; i<db->nDb; i++){
  14698. if( db->aDb[i].pBt ){
  14699. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  14700. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  14701. }
  14702. }
  14703. *pHighwater = 0; /* IMP: R-42420-56072 */
  14704. /* IMP: R-54100-20147 */
  14705. /* IMP: R-29431-39229 */
  14706. *pCurrent = nRet;
  14707. break;
  14708. }
  14709. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  14710. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  14711. ** have been satisfied. The *pHighwater is always set to zero.
  14712. */
  14713. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  14714. *pHighwater = 0; /* IMP: R-11967-56545 */
  14715. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  14716. break;
  14717. }
  14718. default: {
  14719. rc = SQLITE_ERROR;
  14720. }
  14721. }
  14722. sqlite3_mutex_leave(db->mutex);
  14723. return rc;
  14724. }
  14725. /************** End of status.c **********************************************/
  14726. /************** Begin file date.c ********************************************/
  14727. /*
  14728. ** 2003 October 31
  14729. **
  14730. ** The author disclaims copyright to this source code. In place of
  14731. ** a legal notice, here is a blessing:
  14732. **
  14733. ** May you do good and not evil.
  14734. ** May you find forgiveness for yourself and forgive others.
  14735. ** May you share freely, never taking more than you give.
  14736. **
  14737. *************************************************************************
  14738. ** This file contains the C functions that implement date and time
  14739. ** functions for SQLite.
  14740. **
  14741. ** There is only one exported symbol in this file - the function
  14742. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  14743. ** All other code has file scope.
  14744. **
  14745. ** SQLite processes all times and dates as julian day numbers. The
  14746. ** dates and times are stored as the number of days since noon
  14747. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  14748. ** calendar system.
  14749. **
  14750. ** 1970-01-01 00:00:00 is JD 2440587.5
  14751. ** 2000-01-01 00:00:00 is JD 2451544.5
  14752. **
  14753. ** This implementation requires years to be expressed as a 4-digit number
  14754. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  14755. ** be represented, even though julian day numbers allow a much wider
  14756. ** range of dates.
  14757. **
  14758. ** The Gregorian calendar system is used for all dates and times,
  14759. ** even those that predate the Gregorian calendar. Historians usually
  14760. ** use the julian calendar for dates prior to 1582-10-15 and for some
  14761. ** dates afterwards, depending on locale. Beware of this difference.
  14762. **
  14763. ** The conversion algorithms are implemented based on descriptions
  14764. ** in the following text:
  14765. **
  14766. ** Jean Meeus
  14767. ** Astronomical Algorithms, 2nd Edition, 1998
  14768. ** ISBM 0-943396-61-1
  14769. ** Willmann-Bell, Inc
  14770. ** Richmond, Virginia (USA)
  14771. */
  14772. /* #include "sqliteInt.h" */
  14773. /* #include <stdlib.h> */
  14774. /* #include <assert.h> */
  14775. #include <time.h>
  14776. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14777. /*
  14778. ** A structure for holding a single date and time.
  14779. */
  14780. typedef struct DateTime DateTime;
  14781. struct DateTime {
  14782. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  14783. int Y, M, D; /* Year, month, and day */
  14784. int h, m; /* Hour and minutes */
  14785. int tz; /* Timezone offset in minutes */
  14786. double s; /* Seconds */
  14787. char validYMD; /* True (1) if Y,M,D are valid */
  14788. char validHMS; /* True (1) if h,m,s are valid */
  14789. char validJD; /* True (1) if iJD is valid */
  14790. char validTZ; /* True (1) if tz is valid */
  14791. };
  14792. /*
  14793. ** Convert zDate into one or more integers. Additional arguments
  14794. ** come in groups of 5 as follows:
  14795. **
  14796. ** N number of digits in the integer
  14797. ** min minimum allowed value of the integer
  14798. ** max maximum allowed value of the integer
  14799. ** nextC first character after the integer
  14800. ** pVal where to write the integers value.
  14801. **
  14802. ** Conversions continue until one with nextC==0 is encountered.
  14803. ** The function returns the number of successful conversions.
  14804. */
  14805. static int getDigits(const char *zDate, ...){
  14806. va_list ap;
  14807. int val;
  14808. int N;
  14809. int min;
  14810. int max;
  14811. int nextC;
  14812. int *pVal;
  14813. int cnt = 0;
  14814. va_start(ap, zDate);
  14815. do{
  14816. N = va_arg(ap, int);
  14817. min = va_arg(ap, int);
  14818. max = va_arg(ap, int);
  14819. nextC = va_arg(ap, int);
  14820. pVal = va_arg(ap, int*);
  14821. val = 0;
  14822. while( N-- ){
  14823. if( !sqlite3Isdigit(*zDate) ){
  14824. goto end_getDigits;
  14825. }
  14826. val = val*10 + *zDate - '0';
  14827. zDate++;
  14828. }
  14829. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  14830. goto end_getDigits;
  14831. }
  14832. *pVal = val;
  14833. zDate++;
  14834. cnt++;
  14835. }while( nextC );
  14836. end_getDigits:
  14837. va_end(ap);
  14838. return cnt;
  14839. }
  14840. /*
  14841. ** Parse a timezone extension on the end of a date-time.
  14842. ** The extension is of the form:
  14843. **
  14844. ** (+/-)HH:MM
  14845. **
  14846. ** Or the "zulu" notation:
  14847. **
  14848. ** Z
  14849. **
  14850. ** If the parse is successful, write the number of minutes
  14851. ** of change in p->tz and return 0. If a parser error occurs,
  14852. ** return non-zero.
  14853. **
  14854. ** A missing specifier is not considered an error.
  14855. */
  14856. static int parseTimezone(const char *zDate, DateTime *p){
  14857. int sgn = 0;
  14858. int nHr, nMn;
  14859. int c;
  14860. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14861. p->tz = 0;
  14862. c = *zDate;
  14863. if( c=='-' ){
  14864. sgn = -1;
  14865. }else if( c=='+' ){
  14866. sgn = +1;
  14867. }else if( c=='Z' || c=='z' ){
  14868. zDate++;
  14869. goto zulu_time;
  14870. }else{
  14871. return c!=0;
  14872. }
  14873. zDate++;
  14874. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  14875. return 1;
  14876. }
  14877. zDate += 5;
  14878. p->tz = sgn*(nMn + nHr*60);
  14879. zulu_time:
  14880. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14881. return *zDate!=0;
  14882. }
  14883. /*
  14884. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  14885. ** The HH, MM, and SS must each be exactly 2 digits. The
  14886. ** fractional seconds FFFF can be one or more digits.
  14887. **
  14888. ** Return 1 if there is a parsing error and 0 on success.
  14889. */
  14890. static int parseHhMmSs(const char *zDate, DateTime *p){
  14891. int h, m, s;
  14892. double ms = 0.0;
  14893. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  14894. return 1;
  14895. }
  14896. zDate += 5;
  14897. if( *zDate==':' ){
  14898. zDate++;
  14899. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  14900. return 1;
  14901. }
  14902. zDate += 2;
  14903. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  14904. double rScale = 1.0;
  14905. zDate++;
  14906. while( sqlite3Isdigit(*zDate) ){
  14907. ms = ms*10.0 + *zDate - '0';
  14908. rScale *= 10.0;
  14909. zDate++;
  14910. }
  14911. ms /= rScale;
  14912. }
  14913. }else{
  14914. s = 0;
  14915. }
  14916. p->validJD = 0;
  14917. p->validHMS = 1;
  14918. p->h = h;
  14919. p->m = m;
  14920. p->s = s + ms;
  14921. if( parseTimezone(zDate, p) ) return 1;
  14922. p->validTZ = (p->tz!=0)?1:0;
  14923. return 0;
  14924. }
  14925. /*
  14926. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  14927. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  14928. **
  14929. ** Reference: Meeus page 61
  14930. */
  14931. static void computeJD(DateTime *p){
  14932. int Y, M, D, A, B, X1, X2;
  14933. if( p->validJD ) return;
  14934. if( p->validYMD ){
  14935. Y = p->Y;
  14936. M = p->M;
  14937. D = p->D;
  14938. }else{
  14939. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  14940. M = 1;
  14941. D = 1;
  14942. }
  14943. if( M<=2 ){
  14944. Y--;
  14945. M += 12;
  14946. }
  14947. A = Y/100;
  14948. B = 2 - A + (A/4);
  14949. X1 = 36525*(Y+4716)/100;
  14950. X2 = 306001*(M+1)/10000;
  14951. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  14952. p->validJD = 1;
  14953. if( p->validHMS ){
  14954. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  14955. if( p->validTZ ){
  14956. p->iJD -= p->tz*60000;
  14957. p->validYMD = 0;
  14958. p->validHMS = 0;
  14959. p->validTZ = 0;
  14960. }
  14961. }
  14962. }
  14963. /*
  14964. ** Parse dates of the form
  14965. **
  14966. ** YYYY-MM-DD HH:MM:SS.FFF
  14967. ** YYYY-MM-DD HH:MM:SS
  14968. ** YYYY-MM-DD HH:MM
  14969. ** YYYY-MM-DD
  14970. **
  14971. ** Write the result into the DateTime structure and return 0
  14972. ** on success and 1 if the input string is not a well-formed
  14973. ** date.
  14974. */
  14975. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  14976. int Y, M, D, neg;
  14977. if( zDate[0]=='-' ){
  14978. zDate++;
  14979. neg = 1;
  14980. }else{
  14981. neg = 0;
  14982. }
  14983. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  14984. return 1;
  14985. }
  14986. zDate += 10;
  14987. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  14988. if( parseHhMmSs(zDate, p)==0 ){
  14989. /* We got the time */
  14990. }else if( *zDate==0 ){
  14991. p->validHMS = 0;
  14992. }else{
  14993. return 1;
  14994. }
  14995. p->validJD = 0;
  14996. p->validYMD = 1;
  14997. p->Y = neg ? -Y : Y;
  14998. p->M = M;
  14999. p->D = D;
  15000. if( p->validTZ ){
  15001. computeJD(p);
  15002. }
  15003. return 0;
  15004. }
  15005. /*
  15006. ** Set the time to the current time reported by the VFS.
  15007. **
  15008. ** Return the number of errors.
  15009. */
  15010. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  15011. p->iJD = sqlite3StmtCurrentTime(context);
  15012. if( p->iJD>0 ){
  15013. p->validJD = 1;
  15014. return 0;
  15015. }else{
  15016. return 1;
  15017. }
  15018. }
  15019. /*
  15020. ** Attempt to parse the given string into a julian day number. Return
  15021. ** the number of errors.
  15022. **
  15023. ** The following are acceptable forms for the input string:
  15024. **
  15025. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  15026. ** DDDD.DD
  15027. ** now
  15028. **
  15029. ** In the first form, the +/-HH:MM is always optional. The fractional
  15030. ** seconds extension (the ".FFF") is optional. The seconds portion
  15031. ** (":SS.FFF") is option. The year and date can be omitted as long
  15032. ** as there is a time string. The time string can be omitted as long
  15033. ** as there is a year and date.
  15034. */
  15035. static int parseDateOrTime(
  15036. sqlite3_context *context,
  15037. const char *zDate,
  15038. DateTime *p
  15039. ){
  15040. double r;
  15041. if( parseYyyyMmDd(zDate,p)==0 ){
  15042. return 0;
  15043. }else if( parseHhMmSs(zDate, p)==0 ){
  15044. return 0;
  15045. }else if( sqlite3StrICmp(zDate,"now")==0){
  15046. return setDateTimeToCurrent(context, p);
  15047. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  15048. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  15049. p->validJD = 1;
  15050. return 0;
  15051. }
  15052. return 1;
  15053. }
  15054. /*
  15055. ** Compute the Year, Month, and Day from the julian day number.
  15056. */
  15057. static void computeYMD(DateTime *p){
  15058. int Z, A, B, C, D, E, X1;
  15059. if( p->validYMD ) return;
  15060. if( !p->validJD ){
  15061. p->Y = 2000;
  15062. p->M = 1;
  15063. p->D = 1;
  15064. }else{
  15065. Z = (int)((p->iJD + 43200000)/86400000);
  15066. A = (int)((Z - 1867216.25)/36524.25);
  15067. A = Z + 1 + A - (A/4);
  15068. B = A + 1524;
  15069. C = (int)((B - 122.1)/365.25);
  15070. D = (36525*(C&32767))/100;
  15071. E = (int)((B-D)/30.6001);
  15072. X1 = (int)(30.6001*E);
  15073. p->D = B - D - X1;
  15074. p->M = E<14 ? E-1 : E-13;
  15075. p->Y = p->M>2 ? C - 4716 : C - 4715;
  15076. }
  15077. p->validYMD = 1;
  15078. }
  15079. /*
  15080. ** Compute the Hour, Minute, and Seconds from the julian day number.
  15081. */
  15082. static void computeHMS(DateTime *p){
  15083. int s;
  15084. if( p->validHMS ) return;
  15085. computeJD(p);
  15086. s = (int)((p->iJD + 43200000) % 86400000);
  15087. p->s = s/1000.0;
  15088. s = (int)p->s;
  15089. p->s -= s;
  15090. p->h = s/3600;
  15091. s -= p->h*3600;
  15092. p->m = s/60;
  15093. p->s += s - p->m*60;
  15094. p->validHMS = 1;
  15095. }
  15096. /*
  15097. ** Compute both YMD and HMS
  15098. */
  15099. static void computeYMD_HMS(DateTime *p){
  15100. computeYMD(p);
  15101. computeHMS(p);
  15102. }
  15103. /*
  15104. ** Clear the YMD and HMS and the TZ
  15105. */
  15106. static void clearYMD_HMS_TZ(DateTime *p){
  15107. p->validYMD = 0;
  15108. p->validHMS = 0;
  15109. p->validTZ = 0;
  15110. }
  15111. /*
  15112. ** On recent Windows platforms, the localtime_s() function is available
  15113. ** as part of the "Secure CRT". It is essentially equivalent to
  15114. ** localtime_r() available under most POSIX platforms, except that the
  15115. ** order of the parameters is reversed.
  15116. **
  15117. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  15118. **
  15119. ** If the user has not indicated to use localtime_r() or localtime_s()
  15120. ** already, check for an MSVC build environment that provides
  15121. ** localtime_s().
  15122. */
  15123. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
  15124. && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  15125. #undef HAVE_LOCALTIME_S
  15126. #define HAVE_LOCALTIME_S 1
  15127. #endif
  15128. #ifndef SQLITE_OMIT_LOCALTIME
  15129. /*
  15130. ** The following routine implements the rough equivalent of localtime_r()
  15131. ** using whatever operating-system specific localtime facility that
  15132. ** is available. This routine returns 0 on success and
  15133. ** non-zero on any kind of error.
  15134. **
  15135. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  15136. ** routine will always fail.
  15137. **
  15138. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  15139. ** library function localtime_r() is used to assist in the calculation of
  15140. ** local time.
  15141. */
  15142. static int osLocaltime(time_t *t, struct tm *pTm){
  15143. int rc;
  15144. #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
  15145. struct tm *pX;
  15146. #if SQLITE_THREADSAFE>0
  15147. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  15148. #endif
  15149. sqlite3_mutex_enter(mutex);
  15150. pX = localtime(t);
  15151. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15152. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  15153. #endif
  15154. if( pX ) *pTm = *pX;
  15155. sqlite3_mutex_leave(mutex);
  15156. rc = pX==0;
  15157. #else
  15158. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15159. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  15160. #endif
  15161. #if HAVE_LOCALTIME_R
  15162. rc = localtime_r(t, pTm)==0;
  15163. #else
  15164. rc = localtime_s(pTm, t);
  15165. #endif /* HAVE_LOCALTIME_R */
  15166. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  15167. return rc;
  15168. }
  15169. #endif /* SQLITE_OMIT_LOCALTIME */
  15170. #ifndef SQLITE_OMIT_LOCALTIME
  15171. /*
  15172. ** Compute the difference (in milliseconds) between localtime and UTC
  15173. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  15174. ** return this value and set *pRc to SQLITE_OK.
  15175. **
  15176. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  15177. ** is undefined in this case.
  15178. */
  15179. static sqlite3_int64 localtimeOffset(
  15180. DateTime *p, /* Date at which to calculate offset */
  15181. sqlite3_context *pCtx, /* Write error here if one occurs */
  15182. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  15183. ){
  15184. DateTime x, y;
  15185. time_t t;
  15186. struct tm sLocal;
  15187. /* Initialize the contents of sLocal to avoid a compiler warning. */
  15188. memset(&sLocal, 0, sizeof(sLocal));
  15189. x = *p;
  15190. computeYMD_HMS(&x);
  15191. if( x.Y<1971 || x.Y>=2038 ){
  15192. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  15193. ** works for years between 1970 and 2037. For dates outside this range,
  15194. ** SQLite attempts to map the year into an equivalent year within this
  15195. ** range, do the calculation, then map the year back.
  15196. */
  15197. x.Y = 2000;
  15198. x.M = 1;
  15199. x.D = 1;
  15200. x.h = 0;
  15201. x.m = 0;
  15202. x.s = 0.0;
  15203. } else {
  15204. int s = (int)(x.s + 0.5);
  15205. x.s = s;
  15206. }
  15207. x.tz = 0;
  15208. x.validJD = 0;
  15209. computeJD(&x);
  15210. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  15211. if( osLocaltime(&t, &sLocal) ){
  15212. sqlite3_result_error(pCtx, "local time unavailable", -1);
  15213. *pRc = SQLITE_ERROR;
  15214. return 0;
  15215. }
  15216. y.Y = sLocal.tm_year + 1900;
  15217. y.M = sLocal.tm_mon + 1;
  15218. y.D = sLocal.tm_mday;
  15219. y.h = sLocal.tm_hour;
  15220. y.m = sLocal.tm_min;
  15221. y.s = sLocal.tm_sec;
  15222. y.validYMD = 1;
  15223. y.validHMS = 1;
  15224. y.validJD = 0;
  15225. y.validTZ = 0;
  15226. computeJD(&y);
  15227. *pRc = SQLITE_OK;
  15228. return y.iJD - x.iJD;
  15229. }
  15230. #endif /* SQLITE_OMIT_LOCALTIME */
  15231. /*
  15232. ** Process a modifier to a date-time stamp. The modifiers are
  15233. ** as follows:
  15234. **
  15235. ** NNN days
  15236. ** NNN hours
  15237. ** NNN minutes
  15238. ** NNN.NNNN seconds
  15239. ** NNN months
  15240. ** NNN years
  15241. ** start of month
  15242. ** start of year
  15243. ** start of week
  15244. ** start of day
  15245. ** weekday N
  15246. ** unixepoch
  15247. ** localtime
  15248. ** utc
  15249. **
  15250. ** Return 0 on success and 1 if there is any kind of error. If the error
  15251. ** is in a system call (i.e. localtime()), then an error message is written
  15252. ** to context pCtx. If the error is an unrecognized modifier, no error is
  15253. ** written to pCtx.
  15254. */
  15255. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  15256. int rc = 1;
  15257. int n;
  15258. double r;
  15259. char *z, zBuf[30];
  15260. z = zBuf;
  15261. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  15262. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  15263. }
  15264. z[n] = 0;
  15265. switch( z[0] ){
  15266. #ifndef SQLITE_OMIT_LOCALTIME
  15267. case 'l': {
  15268. /* localtime
  15269. **
  15270. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  15271. ** show local time.
  15272. */
  15273. if( strcmp(z, "localtime")==0 ){
  15274. computeJD(p);
  15275. p->iJD += localtimeOffset(p, pCtx, &rc);
  15276. clearYMD_HMS_TZ(p);
  15277. }
  15278. break;
  15279. }
  15280. #endif
  15281. case 'u': {
  15282. /*
  15283. ** unixepoch
  15284. **
  15285. ** Treat the current value of p->iJD as the number of
  15286. ** seconds since 1970. Convert to a real julian day number.
  15287. */
  15288. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  15289. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  15290. clearYMD_HMS_TZ(p);
  15291. rc = 0;
  15292. }
  15293. #ifndef SQLITE_OMIT_LOCALTIME
  15294. else if( strcmp(z, "utc")==0 ){
  15295. sqlite3_int64 c1;
  15296. computeJD(p);
  15297. c1 = localtimeOffset(p, pCtx, &rc);
  15298. if( rc==SQLITE_OK ){
  15299. p->iJD -= c1;
  15300. clearYMD_HMS_TZ(p);
  15301. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  15302. }
  15303. }
  15304. #endif
  15305. break;
  15306. }
  15307. case 'w': {
  15308. /*
  15309. ** weekday N
  15310. **
  15311. ** Move the date to the same time on the next occurrence of
  15312. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  15313. ** date is already on the appropriate weekday, this is a no-op.
  15314. */
  15315. if( strncmp(z, "weekday ", 8)==0
  15316. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  15317. && (n=(int)r)==r && n>=0 && r<7 ){
  15318. sqlite3_int64 Z;
  15319. computeYMD_HMS(p);
  15320. p->validTZ = 0;
  15321. p->validJD = 0;
  15322. computeJD(p);
  15323. Z = ((p->iJD + 129600000)/86400000) % 7;
  15324. if( Z>n ) Z -= 7;
  15325. p->iJD += (n - Z)*86400000;
  15326. clearYMD_HMS_TZ(p);
  15327. rc = 0;
  15328. }
  15329. break;
  15330. }
  15331. case 's': {
  15332. /*
  15333. ** start of TTTTT
  15334. **
  15335. ** Move the date backwards to the beginning of the current day,
  15336. ** or month or year.
  15337. */
  15338. if( strncmp(z, "start of ", 9)!=0 ) break;
  15339. z += 9;
  15340. computeYMD(p);
  15341. p->validHMS = 1;
  15342. p->h = p->m = 0;
  15343. p->s = 0.0;
  15344. p->validTZ = 0;
  15345. p->validJD = 0;
  15346. if( strcmp(z,"month")==0 ){
  15347. p->D = 1;
  15348. rc = 0;
  15349. }else if( strcmp(z,"year")==0 ){
  15350. computeYMD(p);
  15351. p->M = 1;
  15352. p->D = 1;
  15353. rc = 0;
  15354. }else if( strcmp(z,"day")==0 ){
  15355. rc = 0;
  15356. }
  15357. break;
  15358. }
  15359. case '+':
  15360. case '-':
  15361. case '0':
  15362. case '1':
  15363. case '2':
  15364. case '3':
  15365. case '4':
  15366. case '5':
  15367. case '6':
  15368. case '7':
  15369. case '8':
  15370. case '9': {
  15371. double rRounder;
  15372. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  15373. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  15374. rc = 1;
  15375. break;
  15376. }
  15377. if( z[n]==':' ){
  15378. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  15379. ** specified number of hours, minutes, seconds, and fractional seconds
  15380. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  15381. ** omitted.
  15382. */
  15383. const char *z2 = z;
  15384. DateTime tx;
  15385. sqlite3_int64 day;
  15386. if( !sqlite3Isdigit(*z2) ) z2++;
  15387. memset(&tx, 0, sizeof(tx));
  15388. if( parseHhMmSs(z2, &tx) ) break;
  15389. computeJD(&tx);
  15390. tx.iJD -= 43200000;
  15391. day = tx.iJD/86400000;
  15392. tx.iJD -= day*86400000;
  15393. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  15394. computeJD(p);
  15395. clearYMD_HMS_TZ(p);
  15396. p->iJD += tx.iJD;
  15397. rc = 0;
  15398. break;
  15399. }
  15400. z += n;
  15401. while( sqlite3Isspace(*z) ) z++;
  15402. n = sqlite3Strlen30(z);
  15403. if( n>10 || n<3 ) break;
  15404. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  15405. computeJD(p);
  15406. rc = 0;
  15407. rRounder = r<0 ? -0.5 : +0.5;
  15408. if( n==3 && strcmp(z,"day")==0 ){
  15409. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  15410. }else if( n==4 && strcmp(z,"hour")==0 ){
  15411. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  15412. }else if( n==6 && strcmp(z,"minute")==0 ){
  15413. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  15414. }else if( n==6 && strcmp(z,"second")==0 ){
  15415. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  15416. }else if( n==5 && strcmp(z,"month")==0 ){
  15417. int x, y;
  15418. computeYMD_HMS(p);
  15419. p->M += (int)r;
  15420. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  15421. p->Y += x;
  15422. p->M -= x*12;
  15423. p->validJD = 0;
  15424. computeJD(p);
  15425. y = (int)r;
  15426. if( y!=r ){
  15427. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  15428. }
  15429. }else if( n==4 && strcmp(z,"year")==0 ){
  15430. int y = (int)r;
  15431. computeYMD_HMS(p);
  15432. p->Y += y;
  15433. p->validJD = 0;
  15434. computeJD(p);
  15435. if( y!=r ){
  15436. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  15437. }
  15438. }else{
  15439. rc = 1;
  15440. }
  15441. clearYMD_HMS_TZ(p);
  15442. break;
  15443. }
  15444. default: {
  15445. break;
  15446. }
  15447. }
  15448. return rc;
  15449. }
  15450. /*
  15451. ** Process time function arguments. argv[0] is a date-time stamp.
  15452. ** argv[1] and following are modifiers. Parse them all and write
  15453. ** the resulting time into the DateTime structure p. Return 0
  15454. ** on success and 1 if there are any errors.
  15455. **
  15456. ** If there are zero parameters (if even argv[0] is undefined)
  15457. ** then assume a default value of "now" for argv[0].
  15458. */
  15459. static int isDate(
  15460. sqlite3_context *context,
  15461. int argc,
  15462. sqlite3_value **argv,
  15463. DateTime *p
  15464. ){
  15465. int i;
  15466. const unsigned char *z;
  15467. int eType;
  15468. memset(p, 0, sizeof(*p));
  15469. if( argc==0 ){
  15470. return setDateTimeToCurrent(context, p);
  15471. }
  15472. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  15473. || eType==SQLITE_INTEGER ){
  15474. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  15475. p->validJD = 1;
  15476. }else{
  15477. z = sqlite3_value_text(argv[0]);
  15478. if( !z || parseDateOrTime(context, (char*)z, p) ){
  15479. return 1;
  15480. }
  15481. }
  15482. for(i=1; i<argc; i++){
  15483. z = sqlite3_value_text(argv[i]);
  15484. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  15485. }
  15486. return 0;
  15487. }
  15488. /*
  15489. ** The following routines implement the various date and time functions
  15490. ** of SQLite.
  15491. */
  15492. /*
  15493. ** julianday( TIMESTRING, MOD, MOD, ...)
  15494. **
  15495. ** Return the julian day number of the date specified in the arguments
  15496. */
  15497. static void juliandayFunc(
  15498. sqlite3_context *context,
  15499. int argc,
  15500. sqlite3_value **argv
  15501. ){
  15502. DateTime x;
  15503. if( isDate(context, argc, argv, &x)==0 ){
  15504. computeJD(&x);
  15505. sqlite3_result_double(context, x.iJD/86400000.0);
  15506. }
  15507. }
  15508. /*
  15509. ** datetime( TIMESTRING, MOD, MOD, ...)
  15510. **
  15511. ** Return YYYY-MM-DD HH:MM:SS
  15512. */
  15513. static void datetimeFunc(
  15514. sqlite3_context *context,
  15515. int argc,
  15516. sqlite3_value **argv
  15517. ){
  15518. DateTime x;
  15519. if( isDate(context, argc, argv, &x)==0 ){
  15520. char zBuf[100];
  15521. computeYMD_HMS(&x);
  15522. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  15523. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  15524. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15525. }
  15526. }
  15527. /*
  15528. ** time( TIMESTRING, MOD, MOD, ...)
  15529. **
  15530. ** Return HH:MM:SS
  15531. */
  15532. static void timeFunc(
  15533. sqlite3_context *context,
  15534. int argc,
  15535. sqlite3_value **argv
  15536. ){
  15537. DateTime x;
  15538. if( isDate(context, argc, argv, &x)==0 ){
  15539. char zBuf[100];
  15540. computeHMS(&x);
  15541. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  15542. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15543. }
  15544. }
  15545. /*
  15546. ** date( TIMESTRING, MOD, MOD, ...)
  15547. **
  15548. ** Return YYYY-MM-DD
  15549. */
  15550. static void dateFunc(
  15551. sqlite3_context *context,
  15552. int argc,
  15553. sqlite3_value **argv
  15554. ){
  15555. DateTime x;
  15556. if( isDate(context, argc, argv, &x)==0 ){
  15557. char zBuf[100];
  15558. computeYMD(&x);
  15559. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  15560. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15561. }
  15562. }
  15563. /*
  15564. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  15565. **
  15566. ** Return a string described by FORMAT. Conversions as follows:
  15567. **
  15568. ** %d day of month
  15569. ** %f ** fractional seconds SS.SSS
  15570. ** %H hour 00-24
  15571. ** %j day of year 000-366
  15572. ** %J ** julian day number
  15573. ** %m month 01-12
  15574. ** %M minute 00-59
  15575. ** %s seconds since 1970-01-01
  15576. ** %S seconds 00-59
  15577. ** %w day of week 0-6 sunday==0
  15578. ** %W week of year 00-53
  15579. ** %Y year 0000-9999
  15580. ** %% %
  15581. */
  15582. static void strftimeFunc(
  15583. sqlite3_context *context,
  15584. int argc,
  15585. sqlite3_value **argv
  15586. ){
  15587. DateTime x;
  15588. u64 n;
  15589. size_t i,j;
  15590. char *z;
  15591. sqlite3 *db;
  15592. const char *zFmt;
  15593. char zBuf[100];
  15594. if( argc==0 ) return;
  15595. zFmt = (const char*)sqlite3_value_text(argv[0]);
  15596. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  15597. db = sqlite3_context_db_handle(context);
  15598. for(i=0, n=1; zFmt[i]; i++, n++){
  15599. if( zFmt[i]=='%' ){
  15600. switch( zFmt[i+1] ){
  15601. case 'd':
  15602. case 'H':
  15603. case 'm':
  15604. case 'M':
  15605. case 'S':
  15606. case 'W':
  15607. n++;
  15608. /* fall thru */
  15609. case 'w':
  15610. case '%':
  15611. break;
  15612. case 'f':
  15613. n += 8;
  15614. break;
  15615. case 'j':
  15616. n += 3;
  15617. break;
  15618. case 'Y':
  15619. n += 8;
  15620. break;
  15621. case 's':
  15622. case 'J':
  15623. n += 50;
  15624. break;
  15625. default:
  15626. return; /* ERROR. return a NULL */
  15627. }
  15628. i++;
  15629. }
  15630. }
  15631. testcase( n==sizeof(zBuf)-1 );
  15632. testcase( n==sizeof(zBuf) );
  15633. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  15634. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  15635. if( n<sizeof(zBuf) ){
  15636. z = zBuf;
  15637. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  15638. sqlite3_result_error_toobig(context);
  15639. return;
  15640. }else{
  15641. z = sqlite3DbMallocRaw(db, (int)n);
  15642. if( z==0 ){
  15643. sqlite3_result_error_nomem(context);
  15644. return;
  15645. }
  15646. }
  15647. computeJD(&x);
  15648. computeYMD_HMS(&x);
  15649. for(i=j=0; zFmt[i]; i++){
  15650. if( zFmt[i]!='%' ){
  15651. z[j++] = zFmt[i];
  15652. }else{
  15653. i++;
  15654. switch( zFmt[i] ){
  15655. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  15656. case 'f': {
  15657. double s = x.s;
  15658. if( s>59.999 ) s = 59.999;
  15659. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  15660. j += sqlite3Strlen30(&z[j]);
  15661. break;
  15662. }
  15663. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  15664. case 'W': /* Fall thru */
  15665. case 'j': {
  15666. int nDay; /* Number of days since 1st day of year */
  15667. DateTime y = x;
  15668. y.validJD = 0;
  15669. y.M = 1;
  15670. y.D = 1;
  15671. computeJD(&y);
  15672. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  15673. if( zFmt[i]=='W' ){
  15674. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  15675. wd = (int)(((x.iJD+43200000)/86400000)%7);
  15676. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  15677. j += 2;
  15678. }else{
  15679. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  15680. j += 3;
  15681. }
  15682. break;
  15683. }
  15684. case 'J': {
  15685. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  15686. j+=sqlite3Strlen30(&z[j]);
  15687. break;
  15688. }
  15689. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  15690. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  15691. case 's': {
  15692. sqlite3_snprintf(30,&z[j],"%lld",
  15693. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  15694. j += sqlite3Strlen30(&z[j]);
  15695. break;
  15696. }
  15697. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  15698. case 'w': {
  15699. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  15700. break;
  15701. }
  15702. case 'Y': {
  15703. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  15704. break;
  15705. }
  15706. default: z[j++] = '%'; break;
  15707. }
  15708. }
  15709. }
  15710. z[j] = 0;
  15711. sqlite3_result_text(context, z, -1,
  15712. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  15713. }
  15714. /*
  15715. ** current_time()
  15716. **
  15717. ** This function returns the same value as time('now').
  15718. */
  15719. static void ctimeFunc(
  15720. sqlite3_context *context,
  15721. int NotUsed,
  15722. sqlite3_value **NotUsed2
  15723. ){
  15724. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15725. timeFunc(context, 0, 0);
  15726. }
  15727. /*
  15728. ** current_date()
  15729. **
  15730. ** This function returns the same value as date('now').
  15731. */
  15732. static void cdateFunc(
  15733. sqlite3_context *context,
  15734. int NotUsed,
  15735. sqlite3_value **NotUsed2
  15736. ){
  15737. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15738. dateFunc(context, 0, 0);
  15739. }
  15740. /*
  15741. ** current_timestamp()
  15742. **
  15743. ** This function returns the same value as datetime('now').
  15744. */
  15745. static void ctimestampFunc(
  15746. sqlite3_context *context,
  15747. int NotUsed,
  15748. sqlite3_value **NotUsed2
  15749. ){
  15750. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15751. datetimeFunc(context, 0, 0);
  15752. }
  15753. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  15754. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  15755. /*
  15756. ** If the library is compiled to omit the full-scale date and time
  15757. ** handling (to get a smaller binary), the following minimal version
  15758. ** of the functions current_time(), current_date() and current_timestamp()
  15759. ** are included instead. This is to support column declarations that
  15760. ** include "DEFAULT CURRENT_TIME" etc.
  15761. **
  15762. ** This function uses the C-library functions time(), gmtime()
  15763. ** and strftime(). The format string to pass to strftime() is supplied
  15764. ** as the user-data for the function.
  15765. */
  15766. static void currentTimeFunc(
  15767. sqlite3_context *context,
  15768. int argc,
  15769. sqlite3_value **argv
  15770. ){
  15771. time_t t;
  15772. char *zFormat = (char *)sqlite3_user_data(context);
  15773. sqlite3 *db;
  15774. sqlite3_int64 iT;
  15775. struct tm *pTm;
  15776. struct tm sNow;
  15777. char zBuf[20];
  15778. UNUSED_PARAMETER(argc);
  15779. UNUSED_PARAMETER(argv);
  15780. iT = sqlite3StmtCurrentTime(context);
  15781. if( iT<=0 ) return;
  15782. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  15783. #if HAVE_GMTIME_R
  15784. pTm = gmtime_r(&t, &sNow);
  15785. #else
  15786. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15787. pTm = gmtime(&t);
  15788. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  15789. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15790. #endif
  15791. if( pTm ){
  15792. strftime(zBuf, 20, zFormat, &sNow);
  15793. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15794. }
  15795. }
  15796. #endif
  15797. /*
  15798. ** This function registered all of the above C functions as SQL
  15799. ** functions. This should be the only routine in this file with
  15800. ** external linkage.
  15801. */
  15802. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  15803. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  15804. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  15805. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  15806. FUNCTION(date, -1, 0, 0, dateFunc ),
  15807. FUNCTION(time, -1, 0, 0, timeFunc ),
  15808. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  15809. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  15810. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  15811. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  15812. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  15813. #else
  15814. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  15815. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  15816. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  15817. #endif
  15818. };
  15819. int i;
  15820. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  15821. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  15822. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  15823. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  15824. }
  15825. }
  15826. /************** End of date.c ************************************************/
  15827. /************** Begin file os.c **********************************************/
  15828. /*
  15829. ** 2005 November 29
  15830. **
  15831. ** The author disclaims copyright to this source code. In place of
  15832. ** a legal notice, here is a blessing:
  15833. **
  15834. ** May you do good and not evil.
  15835. ** May you find forgiveness for yourself and forgive others.
  15836. ** May you share freely, never taking more than you give.
  15837. **
  15838. ******************************************************************************
  15839. **
  15840. ** This file contains OS interface code that is common to all
  15841. ** architectures.
  15842. */
  15843. #define _SQLITE_OS_C_ 1
  15844. /* #include "sqliteInt.h" */
  15845. #undef _SQLITE_OS_C_
  15846. /*
  15847. ** The default SQLite sqlite3_vfs implementations do not allocate
  15848. ** memory (actually, os_unix.c allocates a small amount of memory
  15849. ** from within OsOpen()), but some third-party implementations may.
  15850. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  15851. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  15852. **
  15853. ** The following functions are instrumented for malloc() failure
  15854. ** testing:
  15855. **
  15856. ** sqlite3OsRead()
  15857. ** sqlite3OsWrite()
  15858. ** sqlite3OsSync()
  15859. ** sqlite3OsFileSize()
  15860. ** sqlite3OsLock()
  15861. ** sqlite3OsCheckReservedLock()
  15862. ** sqlite3OsFileControl()
  15863. ** sqlite3OsShmMap()
  15864. ** sqlite3OsOpen()
  15865. ** sqlite3OsDelete()
  15866. ** sqlite3OsAccess()
  15867. ** sqlite3OsFullPathname()
  15868. **
  15869. */
  15870. #if defined(SQLITE_TEST)
  15871. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  15872. #define DO_OS_MALLOC_TEST(x) \
  15873. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  15874. void *pTstAlloc = sqlite3Malloc(10); \
  15875. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  15876. sqlite3_free(pTstAlloc); \
  15877. }
  15878. #else
  15879. #define DO_OS_MALLOC_TEST(x)
  15880. #endif
  15881. /*
  15882. ** The following routines are convenience wrappers around methods
  15883. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  15884. ** of this would be completely automatic if SQLite were coded using
  15885. ** C++ instead of plain old C.
  15886. */
  15887. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  15888. int rc = SQLITE_OK;
  15889. if( pId->pMethods ){
  15890. rc = pId->pMethods->xClose(pId);
  15891. pId->pMethods = 0;
  15892. }
  15893. return rc;
  15894. }
  15895. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  15896. DO_OS_MALLOC_TEST(id);
  15897. return id->pMethods->xRead(id, pBuf, amt, offset);
  15898. }
  15899. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  15900. DO_OS_MALLOC_TEST(id);
  15901. return id->pMethods->xWrite(id, pBuf, amt, offset);
  15902. }
  15903. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  15904. return id->pMethods->xTruncate(id, size);
  15905. }
  15906. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  15907. DO_OS_MALLOC_TEST(id);
  15908. return id->pMethods->xSync(id, flags);
  15909. }
  15910. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  15911. DO_OS_MALLOC_TEST(id);
  15912. return id->pMethods->xFileSize(id, pSize);
  15913. }
  15914. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  15915. DO_OS_MALLOC_TEST(id);
  15916. return id->pMethods->xLock(id, lockType);
  15917. }
  15918. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  15919. return id->pMethods->xUnlock(id, lockType);
  15920. }
  15921. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  15922. DO_OS_MALLOC_TEST(id);
  15923. return id->pMethods->xCheckReservedLock(id, pResOut);
  15924. }
  15925. /*
  15926. ** Use sqlite3OsFileControl() when we are doing something that might fail
  15927. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  15928. ** when simply tossing information over the wall to the VFS and we do not
  15929. ** really care if the VFS receives and understands the information since it
  15930. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  15931. ** routine has no return value since the return value would be meaningless.
  15932. */
  15933. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  15934. #ifdef SQLITE_TEST
  15935. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  15936. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  15937. ** is using a regular VFS, it is called after the corresponding
  15938. ** transaction has been committed. Injecting a fault at this point
  15939. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  15940. ** but the transaction is committed anyway.
  15941. **
  15942. ** The core must call OsFileControl() though, not OsFileControlHint(),
  15943. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  15944. ** means the commit really has failed and an error should be returned
  15945. ** to the user. */
  15946. DO_OS_MALLOC_TEST(id);
  15947. }
  15948. #endif
  15949. return id->pMethods->xFileControl(id, op, pArg);
  15950. }
  15951. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  15952. (void)id->pMethods->xFileControl(id, op, pArg);
  15953. }
  15954. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  15955. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  15956. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  15957. }
  15958. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  15959. return id->pMethods->xDeviceCharacteristics(id);
  15960. }
  15961. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  15962. return id->pMethods->xShmLock(id, offset, n, flags);
  15963. }
  15964. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  15965. id->pMethods->xShmBarrier(id);
  15966. }
  15967. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  15968. return id->pMethods->xShmUnmap(id, deleteFlag);
  15969. }
  15970. SQLITE_PRIVATE int sqlite3OsShmMap(
  15971. sqlite3_file *id, /* Database file handle */
  15972. int iPage,
  15973. int pgsz,
  15974. int bExtend, /* True to extend file if necessary */
  15975. void volatile **pp /* OUT: Pointer to mapping */
  15976. ){
  15977. DO_OS_MALLOC_TEST(id);
  15978. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  15979. }
  15980. #if SQLITE_MAX_MMAP_SIZE>0
  15981. /* The real implementation of xFetch and xUnfetch */
  15982. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15983. DO_OS_MALLOC_TEST(id);
  15984. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  15985. }
  15986. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15987. return id->pMethods->xUnfetch(id, iOff, p);
  15988. }
  15989. #else
  15990. /* No-op stubs to use when memory-mapped I/O is disabled */
  15991. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15992. *pp = 0;
  15993. return SQLITE_OK;
  15994. }
  15995. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15996. return SQLITE_OK;
  15997. }
  15998. #endif
  15999. /*
  16000. ** The next group of routines are convenience wrappers around the
  16001. ** VFS methods.
  16002. */
  16003. SQLITE_PRIVATE int sqlite3OsOpen(
  16004. sqlite3_vfs *pVfs,
  16005. const char *zPath,
  16006. sqlite3_file *pFile,
  16007. int flags,
  16008. int *pFlagsOut
  16009. ){
  16010. int rc;
  16011. DO_OS_MALLOC_TEST(0);
  16012. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  16013. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  16014. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  16015. ** reaching the VFS. */
  16016. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  16017. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  16018. return rc;
  16019. }
  16020. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  16021. DO_OS_MALLOC_TEST(0);
  16022. assert( dirSync==0 || dirSync==1 );
  16023. return pVfs->xDelete(pVfs, zPath, dirSync);
  16024. }
  16025. SQLITE_PRIVATE int sqlite3OsAccess(
  16026. sqlite3_vfs *pVfs,
  16027. const char *zPath,
  16028. int flags,
  16029. int *pResOut
  16030. ){
  16031. DO_OS_MALLOC_TEST(0);
  16032. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  16033. }
  16034. SQLITE_PRIVATE int sqlite3OsFullPathname(
  16035. sqlite3_vfs *pVfs,
  16036. const char *zPath,
  16037. int nPathOut,
  16038. char *zPathOut
  16039. ){
  16040. DO_OS_MALLOC_TEST(0);
  16041. zPathOut[0] = 0;
  16042. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  16043. }
  16044. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  16045. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  16046. return pVfs->xDlOpen(pVfs, zPath);
  16047. }
  16048. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  16049. pVfs->xDlError(pVfs, nByte, zBufOut);
  16050. }
  16051. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  16052. return pVfs->xDlSym(pVfs, pHdle, zSym);
  16053. }
  16054. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  16055. pVfs->xDlClose(pVfs, pHandle);
  16056. }
  16057. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  16058. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  16059. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  16060. }
  16061. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  16062. return pVfs->xSleep(pVfs, nMicro);
  16063. }
  16064. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  16065. int rc;
  16066. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  16067. ** method to get the current date and time if that method is available
  16068. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  16069. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  16070. ** unavailable.
  16071. */
  16072. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  16073. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  16074. }else{
  16075. double r;
  16076. rc = pVfs->xCurrentTime(pVfs, &r);
  16077. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  16078. }
  16079. return rc;
  16080. }
  16081. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  16082. sqlite3_vfs *pVfs,
  16083. const char *zFile,
  16084. sqlite3_file **ppFile,
  16085. int flags,
  16086. int *pOutFlags
  16087. ){
  16088. int rc = SQLITE_NOMEM;
  16089. sqlite3_file *pFile;
  16090. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  16091. if( pFile ){
  16092. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  16093. if( rc!=SQLITE_OK ){
  16094. sqlite3_free(pFile);
  16095. }else{
  16096. *ppFile = pFile;
  16097. }
  16098. }
  16099. return rc;
  16100. }
  16101. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  16102. int rc = SQLITE_OK;
  16103. assert( pFile );
  16104. rc = sqlite3OsClose(pFile);
  16105. sqlite3_free(pFile);
  16106. return rc;
  16107. }
  16108. /*
  16109. ** This function is a wrapper around the OS specific implementation of
  16110. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  16111. ** ability to simulate a malloc failure, so that the handling of an
  16112. ** error in sqlite3_os_init() by the upper layers can be tested.
  16113. */
  16114. SQLITE_PRIVATE int sqlite3OsInit(void){
  16115. void *p = sqlite3_malloc(10);
  16116. if( p==0 ) return SQLITE_NOMEM;
  16117. sqlite3_free(p);
  16118. return sqlite3_os_init();
  16119. }
  16120. /*
  16121. ** The list of all registered VFS implementations.
  16122. */
  16123. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  16124. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  16125. /*
  16126. ** Locate a VFS by name. If no name is given, simply return the
  16127. ** first VFS on the list.
  16128. */
  16129. SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
  16130. sqlite3_vfs *pVfs = 0;
  16131. #if SQLITE_THREADSAFE
  16132. sqlite3_mutex *mutex;
  16133. #endif
  16134. #ifndef SQLITE_OMIT_AUTOINIT
  16135. int rc = sqlite3_initialize();
  16136. if( rc ) return 0;
  16137. #endif
  16138. #if SQLITE_THREADSAFE
  16139. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16140. #endif
  16141. sqlite3_mutex_enter(mutex);
  16142. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  16143. if( zVfs==0 ) break;
  16144. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  16145. }
  16146. sqlite3_mutex_leave(mutex);
  16147. return pVfs;
  16148. }
  16149. /*
  16150. ** Unlink a VFS from the linked list
  16151. */
  16152. static void vfsUnlink(sqlite3_vfs *pVfs){
  16153. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  16154. if( pVfs==0 ){
  16155. /* No-op */
  16156. }else if( vfsList==pVfs ){
  16157. vfsList = pVfs->pNext;
  16158. }else if( vfsList ){
  16159. sqlite3_vfs *p = vfsList;
  16160. while( p->pNext && p->pNext!=pVfs ){
  16161. p = p->pNext;
  16162. }
  16163. if( p->pNext==pVfs ){
  16164. p->pNext = pVfs->pNext;
  16165. }
  16166. }
  16167. }
  16168. /*
  16169. ** Register a VFS with the system. It is harmless to register the same
  16170. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  16171. ** true.
  16172. */
  16173. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  16174. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  16175. #ifndef SQLITE_OMIT_AUTOINIT
  16176. int rc = sqlite3_initialize();
  16177. if( rc ) return rc;
  16178. #endif
  16179. #ifdef SQLITE_ENABLE_API_ARMOR
  16180. if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
  16181. #endif
  16182. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  16183. sqlite3_mutex_enter(mutex);
  16184. vfsUnlink(pVfs);
  16185. if( makeDflt || vfsList==0 ){
  16186. pVfs->pNext = vfsList;
  16187. vfsList = pVfs;
  16188. }else{
  16189. pVfs->pNext = vfsList->pNext;
  16190. vfsList->pNext = pVfs;
  16191. }
  16192. assert(vfsList);
  16193. sqlite3_mutex_leave(mutex);
  16194. return SQLITE_OK;
  16195. }
  16196. /*
  16197. ** Unregister a VFS so that it is no longer accessible.
  16198. */
  16199. SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  16200. #if SQLITE_THREADSAFE
  16201. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  16202. #endif
  16203. sqlite3_mutex_enter(mutex);
  16204. vfsUnlink(pVfs);
  16205. sqlite3_mutex_leave(mutex);
  16206. return SQLITE_OK;
  16207. }
  16208. /************** End of os.c **************************************************/
  16209. /************** Begin file fault.c *******************************************/
  16210. /*
  16211. ** 2008 Jan 22
  16212. **
  16213. ** The author disclaims copyright to this source code. In place of
  16214. ** a legal notice, here is a blessing:
  16215. **
  16216. ** May you do good and not evil.
  16217. ** May you find forgiveness for yourself and forgive others.
  16218. ** May you share freely, never taking more than you give.
  16219. **
  16220. *************************************************************************
  16221. **
  16222. ** This file contains code to support the concept of "benign"
  16223. ** malloc failures (when the xMalloc() or xRealloc() method of the
  16224. ** sqlite3_mem_methods structure fails to allocate a block of memory
  16225. ** and returns 0).
  16226. **
  16227. ** Most malloc failures are non-benign. After they occur, SQLite
  16228. ** abandons the current operation and returns an error code (usually
  16229. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  16230. ** fatal. For example, if a malloc fails while resizing a hash table, this
  16231. ** is completely recoverable simply by not carrying out the resize. The
  16232. ** hash table will continue to function normally. So a malloc failure
  16233. ** during a hash table resize is a benign fault.
  16234. */
  16235. /* #include "sqliteInt.h" */
  16236. #ifndef SQLITE_OMIT_BUILTIN_TEST
  16237. /*
  16238. ** Global variables.
  16239. */
  16240. typedef struct BenignMallocHooks BenignMallocHooks;
  16241. static SQLITE_WSD struct BenignMallocHooks {
  16242. void (*xBenignBegin)(void);
  16243. void (*xBenignEnd)(void);
  16244. } sqlite3Hooks = { 0, 0 };
  16245. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  16246. ** structure. If writable static data is unsupported on the target,
  16247. ** we have to locate the state vector at run-time. In the more common
  16248. ** case where writable static data is supported, wsdHooks can refer directly
  16249. ** to the "sqlite3Hooks" state vector declared above.
  16250. */
  16251. #ifdef SQLITE_OMIT_WSD
  16252. # define wsdHooksInit \
  16253. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  16254. # define wsdHooks x[0]
  16255. #else
  16256. # define wsdHooksInit
  16257. # define wsdHooks sqlite3Hooks
  16258. #endif
  16259. /*
  16260. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  16261. ** sqlite3EndBenignMalloc() are called, respectively.
  16262. */
  16263. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  16264. void (*xBenignBegin)(void),
  16265. void (*xBenignEnd)(void)
  16266. ){
  16267. wsdHooksInit;
  16268. wsdHooks.xBenignBegin = xBenignBegin;
  16269. wsdHooks.xBenignEnd = xBenignEnd;
  16270. }
  16271. /*
  16272. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  16273. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  16274. ** indicates that subsequent malloc failures are non-benign.
  16275. */
  16276. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  16277. wsdHooksInit;
  16278. if( wsdHooks.xBenignBegin ){
  16279. wsdHooks.xBenignBegin();
  16280. }
  16281. }
  16282. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  16283. wsdHooksInit;
  16284. if( wsdHooks.xBenignEnd ){
  16285. wsdHooks.xBenignEnd();
  16286. }
  16287. }
  16288. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  16289. /************** End of fault.c ***********************************************/
  16290. /************** Begin file mem0.c ********************************************/
  16291. /*
  16292. ** 2008 October 28
  16293. **
  16294. ** The author disclaims copyright to this source code. In place of
  16295. ** a legal notice, here is a blessing:
  16296. **
  16297. ** May you do good and not evil.
  16298. ** May you find forgiveness for yourself and forgive others.
  16299. ** May you share freely, never taking more than you give.
  16300. **
  16301. *************************************************************************
  16302. **
  16303. ** This file contains a no-op memory allocation drivers for use when
  16304. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  16305. ** here always fail. SQLite will not operate with these drivers. These
  16306. ** are merely placeholders. Real drivers must be substituted using
  16307. ** sqlite3_config() before SQLite will operate.
  16308. */
  16309. /* #include "sqliteInt.h" */
  16310. /*
  16311. ** This version of the memory allocator is the default. It is
  16312. ** used when no other memory allocator is specified using compile-time
  16313. ** macros.
  16314. */
  16315. #ifdef SQLITE_ZERO_MALLOC
  16316. /*
  16317. ** No-op versions of all memory allocation routines
  16318. */
  16319. static void *sqlite3MemMalloc(int nByte){ return 0; }
  16320. static void sqlite3MemFree(void *pPrior){ return; }
  16321. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  16322. static int sqlite3MemSize(void *pPrior){ return 0; }
  16323. static int sqlite3MemRoundup(int n){ return n; }
  16324. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  16325. static void sqlite3MemShutdown(void *NotUsed){ return; }
  16326. /*
  16327. ** This routine is the only routine in this file with external linkage.
  16328. **
  16329. ** Populate the low-level memory allocation function pointers in
  16330. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16331. */
  16332. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16333. static const sqlite3_mem_methods defaultMethods = {
  16334. sqlite3MemMalloc,
  16335. sqlite3MemFree,
  16336. sqlite3MemRealloc,
  16337. sqlite3MemSize,
  16338. sqlite3MemRoundup,
  16339. sqlite3MemInit,
  16340. sqlite3MemShutdown,
  16341. 0
  16342. };
  16343. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16344. }
  16345. #endif /* SQLITE_ZERO_MALLOC */
  16346. /************** End of mem0.c ************************************************/
  16347. /************** Begin file mem1.c ********************************************/
  16348. /*
  16349. ** 2007 August 14
  16350. **
  16351. ** The author disclaims copyright to this source code. In place of
  16352. ** a legal notice, here is a blessing:
  16353. **
  16354. ** May you do good and not evil.
  16355. ** May you find forgiveness for yourself and forgive others.
  16356. ** May you share freely, never taking more than you give.
  16357. **
  16358. *************************************************************************
  16359. **
  16360. ** This file contains low-level memory allocation drivers for when
  16361. ** SQLite will use the standard C-library malloc/realloc/free interface
  16362. ** to obtain the memory it needs.
  16363. **
  16364. ** This file contains implementations of the low-level memory allocation
  16365. ** routines specified in the sqlite3_mem_methods object. The content of
  16366. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  16367. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  16368. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  16369. ** default configuration is to use memory allocation routines in this
  16370. ** file.
  16371. **
  16372. ** C-preprocessor macro summary:
  16373. **
  16374. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  16375. ** the malloc_usable_size() interface exists
  16376. ** on the target platform. Or, this symbol
  16377. ** can be set manually, if desired.
  16378. ** If an equivalent interface exists by
  16379. ** a different name, using a separate -D
  16380. ** option to rename it.
  16381. **
  16382. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  16383. ** memory allocator. Set this symbol to enable
  16384. ** building on older macs.
  16385. **
  16386. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  16387. ** _msize() on windows systems. This might
  16388. ** be necessary when compiling for Delphi,
  16389. ** for example.
  16390. */
  16391. /* #include "sqliteInt.h" */
  16392. /*
  16393. ** This version of the memory allocator is the default. It is
  16394. ** used when no other memory allocator is specified using compile-time
  16395. ** macros.
  16396. */
  16397. #ifdef SQLITE_SYSTEM_MALLOC
  16398. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  16399. /*
  16400. ** Use the zone allocator available on apple products unless the
  16401. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  16402. */
  16403. #include <sys/sysctl.h>
  16404. #include <malloc/malloc.h>
  16405. #include <libkern/OSAtomic.h>
  16406. static malloc_zone_t* _sqliteZone_;
  16407. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  16408. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  16409. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  16410. #define SQLITE_MALLOCSIZE(x) \
  16411. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  16412. #else /* if not __APPLE__ */
  16413. /*
  16414. ** Use standard C library malloc and free on non-Apple systems.
  16415. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  16416. */
  16417. #define SQLITE_MALLOC(x) malloc(x)
  16418. #define SQLITE_FREE(x) free(x)
  16419. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  16420. /*
  16421. ** The malloc.h header file is needed for malloc_usable_size() function
  16422. ** on some systems (e.g. Linux).
  16423. */
  16424. #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
  16425. # define SQLITE_USE_MALLOC_H 1
  16426. # define SQLITE_USE_MALLOC_USABLE_SIZE 1
  16427. /*
  16428. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  16429. ** use of _msize() is automatic, but can be disabled by compiling with
  16430. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  16431. ** the malloc.h header file.
  16432. */
  16433. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  16434. # define SQLITE_USE_MALLOC_H
  16435. # define SQLITE_USE_MSIZE
  16436. #endif
  16437. /*
  16438. ** Include the malloc.h header file, if necessary. Also set define macro
  16439. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  16440. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  16441. ** The memory size function can always be overridden manually by defining
  16442. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  16443. */
  16444. #if defined(SQLITE_USE_MALLOC_H)
  16445. # include <malloc.h>
  16446. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  16447. # if !defined(SQLITE_MALLOCSIZE)
  16448. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  16449. # endif
  16450. # elif defined(SQLITE_USE_MSIZE)
  16451. # if !defined(SQLITE_MALLOCSIZE)
  16452. # define SQLITE_MALLOCSIZE _msize
  16453. # endif
  16454. # endif
  16455. #endif /* defined(SQLITE_USE_MALLOC_H) */
  16456. #endif /* __APPLE__ or not __APPLE__ */
  16457. /*
  16458. ** Like malloc(), but remember the size of the allocation
  16459. ** so that we can find it later using sqlite3MemSize().
  16460. **
  16461. ** For this low-level routine, we are guaranteed that nByte>0 because
  16462. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  16463. ** routines.
  16464. */
  16465. static void *sqlite3MemMalloc(int nByte){
  16466. #ifdef SQLITE_MALLOCSIZE
  16467. void *p = SQLITE_MALLOC( nByte );
  16468. if( p==0 ){
  16469. testcase( sqlite3GlobalConfig.xLog!=0 );
  16470. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  16471. }
  16472. return p;
  16473. #else
  16474. sqlite3_int64 *p;
  16475. assert( nByte>0 );
  16476. nByte = ROUND8(nByte);
  16477. p = SQLITE_MALLOC( nByte+8 );
  16478. if( p ){
  16479. p[0] = nByte;
  16480. p++;
  16481. }else{
  16482. testcase( sqlite3GlobalConfig.xLog!=0 );
  16483. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  16484. }
  16485. return (void *)p;
  16486. #endif
  16487. }
  16488. /*
  16489. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  16490. ** or sqlite3MemRealloc().
  16491. **
  16492. ** For this low-level routine, we already know that pPrior!=0 since
  16493. ** cases where pPrior==0 will have been intecepted and dealt with
  16494. ** by higher-level routines.
  16495. */
  16496. static void sqlite3MemFree(void *pPrior){
  16497. #ifdef SQLITE_MALLOCSIZE
  16498. SQLITE_FREE(pPrior);
  16499. #else
  16500. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  16501. assert( pPrior!=0 );
  16502. p--;
  16503. SQLITE_FREE(p);
  16504. #endif
  16505. }
  16506. /*
  16507. ** Report the allocated size of a prior return from xMalloc()
  16508. ** or xRealloc().
  16509. */
  16510. static int sqlite3MemSize(void *pPrior){
  16511. #ifdef SQLITE_MALLOCSIZE
  16512. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  16513. #else
  16514. sqlite3_int64 *p;
  16515. if( pPrior==0 ) return 0;
  16516. p = (sqlite3_int64*)pPrior;
  16517. p--;
  16518. return (int)p[0];
  16519. #endif
  16520. }
  16521. /*
  16522. ** Like realloc(). Resize an allocation previously obtained from
  16523. ** sqlite3MemMalloc().
  16524. **
  16525. ** For this low-level interface, we know that pPrior!=0. Cases where
  16526. ** pPrior==0 while have been intercepted by higher-level routine and
  16527. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  16528. ** cases where nByte<=0 will have been intercepted by higher-level
  16529. ** routines and redirected to xFree.
  16530. */
  16531. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  16532. #ifdef SQLITE_MALLOCSIZE
  16533. void *p = SQLITE_REALLOC(pPrior, nByte);
  16534. if( p==0 ){
  16535. testcase( sqlite3GlobalConfig.xLog!=0 );
  16536. sqlite3_log(SQLITE_NOMEM,
  16537. "failed memory resize %u to %u bytes",
  16538. SQLITE_MALLOCSIZE(pPrior), nByte);
  16539. }
  16540. return p;
  16541. #else
  16542. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  16543. assert( pPrior!=0 && nByte>0 );
  16544. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  16545. p--;
  16546. p = SQLITE_REALLOC(p, nByte+8 );
  16547. if( p ){
  16548. p[0] = nByte;
  16549. p++;
  16550. }else{
  16551. testcase( sqlite3GlobalConfig.xLog!=0 );
  16552. sqlite3_log(SQLITE_NOMEM,
  16553. "failed memory resize %u to %u bytes",
  16554. sqlite3MemSize(pPrior), nByte);
  16555. }
  16556. return (void*)p;
  16557. #endif
  16558. }
  16559. /*
  16560. ** Round up a request size to the next valid allocation size.
  16561. */
  16562. static int sqlite3MemRoundup(int n){
  16563. return ROUND8(n);
  16564. }
  16565. /*
  16566. ** Initialize this module.
  16567. */
  16568. static int sqlite3MemInit(void *NotUsed){
  16569. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  16570. int cpuCount;
  16571. size_t len;
  16572. if( _sqliteZone_ ){
  16573. return SQLITE_OK;
  16574. }
  16575. len = sizeof(cpuCount);
  16576. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  16577. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  16578. if( cpuCount>1 ){
  16579. /* defer MT decisions to system malloc */
  16580. _sqliteZone_ = malloc_default_zone();
  16581. }else{
  16582. /* only 1 core, use our own zone to contention over global locks,
  16583. ** e.g. we have our own dedicated locks */
  16584. bool success;
  16585. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  16586. malloc_set_zone_name(newzone, "Sqlite_Heap");
  16587. do{
  16588. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  16589. (void * volatile *)&_sqliteZone_);
  16590. }while(!_sqliteZone_);
  16591. if( !success ){
  16592. /* somebody registered a zone first */
  16593. malloc_destroy_zone(newzone);
  16594. }
  16595. }
  16596. #endif
  16597. UNUSED_PARAMETER(NotUsed);
  16598. return SQLITE_OK;
  16599. }
  16600. /*
  16601. ** Deinitialize this module.
  16602. */
  16603. static void sqlite3MemShutdown(void *NotUsed){
  16604. UNUSED_PARAMETER(NotUsed);
  16605. return;
  16606. }
  16607. /*
  16608. ** This routine is the only routine in this file with external linkage.
  16609. **
  16610. ** Populate the low-level memory allocation function pointers in
  16611. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16612. */
  16613. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16614. static const sqlite3_mem_methods defaultMethods = {
  16615. sqlite3MemMalloc,
  16616. sqlite3MemFree,
  16617. sqlite3MemRealloc,
  16618. sqlite3MemSize,
  16619. sqlite3MemRoundup,
  16620. sqlite3MemInit,
  16621. sqlite3MemShutdown,
  16622. 0
  16623. };
  16624. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16625. }
  16626. #endif /* SQLITE_SYSTEM_MALLOC */
  16627. /************** End of mem1.c ************************************************/
  16628. /************** Begin file mem2.c ********************************************/
  16629. /*
  16630. ** 2007 August 15
  16631. **
  16632. ** The author disclaims copyright to this source code. In place of
  16633. ** a legal notice, here is a blessing:
  16634. **
  16635. ** May you do good and not evil.
  16636. ** May you find forgiveness for yourself and forgive others.
  16637. ** May you share freely, never taking more than you give.
  16638. **
  16639. *************************************************************************
  16640. **
  16641. ** This file contains low-level memory allocation drivers for when
  16642. ** SQLite will use the standard C-library malloc/realloc/free interface
  16643. ** to obtain the memory it needs while adding lots of additional debugging
  16644. ** information to each allocation in order to help detect and fix memory
  16645. ** leaks and memory usage errors.
  16646. **
  16647. ** This file contains implementations of the low-level memory allocation
  16648. ** routines specified in the sqlite3_mem_methods object.
  16649. */
  16650. /* #include "sqliteInt.h" */
  16651. /*
  16652. ** This version of the memory allocator is used only if the
  16653. ** SQLITE_MEMDEBUG macro is defined
  16654. */
  16655. #ifdef SQLITE_MEMDEBUG
  16656. /*
  16657. ** The backtrace functionality is only available with GLIBC
  16658. */
  16659. #ifdef __GLIBC__
  16660. extern int backtrace(void**,int);
  16661. extern void backtrace_symbols_fd(void*const*,int,int);
  16662. #else
  16663. # define backtrace(A,B) 1
  16664. # define backtrace_symbols_fd(A,B,C)
  16665. #endif
  16666. /* #include <stdio.h> */
  16667. /*
  16668. ** Each memory allocation looks like this:
  16669. **
  16670. ** ------------------------------------------------------------------------
  16671. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  16672. ** ------------------------------------------------------------------------
  16673. **
  16674. ** The application code sees only a pointer to the allocation. We have
  16675. ** to back up from the allocation pointer to find the MemBlockHdr. The
  16676. ** MemBlockHdr tells us the size of the allocation and the number of
  16677. ** backtrace pointers. There is also a guard word at the end of the
  16678. ** MemBlockHdr.
  16679. */
  16680. struct MemBlockHdr {
  16681. i64 iSize; /* Size of this allocation */
  16682. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  16683. char nBacktrace; /* Number of backtraces on this alloc */
  16684. char nBacktraceSlots; /* Available backtrace slots */
  16685. u8 nTitle; /* Bytes of title; includes '\0' */
  16686. u8 eType; /* Allocation type code */
  16687. int iForeGuard; /* Guard word for sanity */
  16688. };
  16689. /*
  16690. ** Guard words
  16691. */
  16692. #define FOREGUARD 0x80F5E153
  16693. #define REARGUARD 0xE4676B53
  16694. /*
  16695. ** Number of malloc size increments to track.
  16696. */
  16697. #define NCSIZE 1000
  16698. /*
  16699. ** All of the static variables used by this module are collected
  16700. ** into a single structure named "mem". This is to keep the
  16701. ** static variables organized and to reduce namespace pollution
  16702. ** when this module is combined with other in the amalgamation.
  16703. */
  16704. static struct {
  16705. /*
  16706. ** Mutex to control access to the memory allocation subsystem.
  16707. */
  16708. sqlite3_mutex *mutex;
  16709. /*
  16710. ** Head and tail of a linked list of all outstanding allocations
  16711. */
  16712. struct MemBlockHdr *pFirst;
  16713. struct MemBlockHdr *pLast;
  16714. /*
  16715. ** The number of levels of backtrace to save in new allocations.
  16716. */
  16717. int nBacktrace;
  16718. void (*xBacktrace)(int, int, void **);
  16719. /*
  16720. ** Title text to insert in front of each block
  16721. */
  16722. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  16723. char zTitle[100]; /* The title text */
  16724. /*
  16725. ** sqlite3MallocDisallow() increments the following counter.
  16726. ** sqlite3MallocAllow() decrements it.
  16727. */
  16728. int disallow; /* Do not allow memory allocation */
  16729. /*
  16730. ** Gather statistics on the sizes of memory allocations.
  16731. ** nAlloc[i] is the number of allocation attempts of i*8
  16732. ** bytes. i==NCSIZE is the number of allocation attempts for
  16733. ** sizes more than NCSIZE*8 bytes.
  16734. */
  16735. int nAlloc[NCSIZE]; /* Total number of allocations */
  16736. int nCurrent[NCSIZE]; /* Current number of allocations */
  16737. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  16738. } mem;
  16739. /*
  16740. ** Adjust memory usage statistics
  16741. */
  16742. static void adjustStats(int iSize, int increment){
  16743. int i = ROUND8(iSize)/8;
  16744. if( i>NCSIZE-1 ){
  16745. i = NCSIZE - 1;
  16746. }
  16747. if( increment>0 ){
  16748. mem.nAlloc[i]++;
  16749. mem.nCurrent[i]++;
  16750. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  16751. mem.mxCurrent[i] = mem.nCurrent[i];
  16752. }
  16753. }else{
  16754. mem.nCurrent[i]--;
  16755. assert( mem.nCurrent[i]>=0 );
  16756. }
  16757. }
  16758. /*
  16759. ** Given an allocation, find the MemBlockHdr for that allocation.
  16760. **
  16761. ** This routine checks the guards at either end of the allocation and
  16762. ** if they are incorrect it asserts.
  16763. */
  16764. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  16765. struct MemBlockHdr *p;
  16766. int *pInt;
  16767. u8 *pU8;
  16768. int nReserve;
  16769. p = (struct MemBlockHdr*)pAllocation;
  16770. p--;
  16771. assert( p->iForeGuard==(int)FOREGUARD );
  16772. nReserve = ROUND8(p->iSize);
  16773. pInt = (int*)pAllocation;
  16774. pU8 = (u8*)pAllocation;
  16775. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  16776. /* This checks any of the "extra" bytes allocated due
  16777. ** to rounding up to an 8 byte boundary to ensure
  16778. ** they haven't been overwritten.
  16779. */
  16780. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  16781. return p;
  16782. }
  16783. /*
  16784. ** Return the number of bytes currently allocated at address p.
  16785. */
  16786. static int sqlite3MemSize(void *p){
  16787. struct MemBlockHdr *pHdr;
  16788. if( !p ){
  16789. return 0;
  16790. }
  16791. pHdr = sqlite3MemsysGetHeader(p);
  16792. return (int)pHdr->iSize;
  16793. }
  16794. /*
  16795. ** Initialize the memory allocation subsystem.
  16796. */
  16797. static int sqlite3MemInit(void *NotUsed){
  16798. UNUSED_PARAMETER(NotUsed);
  16799. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  16800. if( !sqlite3GlobalConfig.bMemstat ){
  16801. /* If memory status is enabled, then the malloc.c wrapper will already
  16802. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  16803. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16804. }
  16805. return SQLITE_OK;
  16806. }
  16807. /*
  16808. ** Deinitialize the memory allocation subsystem.
  16809. */
  16810. static void sqlite3MemShutdown(void *NotUsed){
  16811. UNUSED_PARAMETER(NotUsed);
  16812. mem.mutex = 0;
  16813. }
  16814. /*
  16815. ** Round up a request size to the next valid allocation size.
  16816. */
  16817. static int sqlite3MemRoundup(int n){
  16818. return ROUND8(n);
  16819. }
  16820. /*
  16821. ** Fill a buffer with pseudo-random bytes. This is used to preset
  16822. ** the content of a new memory allocation to unpredictable values and
  16823. ** to clear the content of a freed allocation to unpredictable values.
  16824. */
  16825. static void randomFill(char *pBuf, int nByte){
  16826. unsigned int x, y, r;
  16827. x = SQLITE_PTR_TO_INT(pBuf);
  16828. y = nByte | 1;
  16829. while( nByte >= 4 ){
  16830. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16831. y = y*1103515245 + 12345;
  16832. r = x ^ y;
  16833. *(int*)pBuf = r;
  16834. pBuf += 4;
  16835. nByte -= 4;
  16836. }
  16837. while( nByte-- > 0 ){
  16838. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16839. y = y*1103515245 + 12345;
  16840. r = x ^ y;
  16841. *(pBuf++) = r & 0xff;
  16842. }
  16843. }
  16844. /*
  16845. ** Allocate nByte bytes of memory.
  16846. */
  16847. static void *sqlite3MemMalloc(int nByte){
  16848. struct MemBlockHdr *pHdr;
  16849. void **pBt;
  16850. char *z;
  16851. int *pInt;
  16852. void *p = 0;
  16853. int totalSize;
  16854. int nReserve;
  16855. sqlite3_mutex_enter(mem.mutex);
  16856. assert( mem.disallow==0 );
  16857. nReserve = ROUND8(nByte);
  16858. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  16859. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  16860. p = malloc(totalSize);
  16861. if( p ){
  16862. z = p;
  16863. pBt = (void**)&z[mem.nTitle];
  16864. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  16865. pHdr->pNext = 0;
  16866. pHdr->pPrev = mem.pLast;
  16867. if( mem.pLast ){
  16868. mem.pLast->pNext = pHdr;
  16869. }else{
  16870. mem.pFirst = pHdr;
  16871. }
  16872. mem.pLast = pHdr;
  16873. pHdr->iForeGuard = FOREGUARD;
  16874. pHdr->eType = MEMTYPE_HEAP;
  16875. pHdr->nBacktraceSlots = mem.nBacktrace;
  16876. pHdr->nTitle = mem.nTitle;
  16877. if( mem.nBacktrace ){
  16878. void *aAddr[40];
  16879. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  16880. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  16881. assert(pBt[0]);
  16882. if( mem.xBacktrace ){
  16883. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  16884. }
  16885. }else{
  16886. pHdr->nBacktrace = 0;
  16887. }
  16888. if( mem.nTitle ){
  16889. memcpy(z, mem.zTitle, mem.nTitle);
  16890. }
  16891. pHdr->iSize = nByte;
  16892. adjustStats(nByte, +1);
  16893. pInt = (int*)&pHdr[1];
  16894. pInt[nReserve/sizeof(int)] = REARGUARD;
  16895. randomFill((char*)pInt, nByte);
  16896. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  16897. p = (void*)pInt;
  16898. }
  16899. sqlite3_mutex_leave(mem.mutex);
  16900. return p;
  16901. }
  16902. /*
  16903. ** Free memory.
  16904. */
  16905. static void sqlite3MemFree(void *pPrior){
  16906. struct MemBlockHdr *pHdr;
  16907. void **pBt;
  16908. char *z;
  16909. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  16910. || mem.mutex!=0 );
  16911. pHdr = sqlite3MemsysGetHeader(pPrior);
  16912. pBt = (void**)pHdr;
  16913. pBt -= pHdr->nBacktraceSlots;
  16914. sqlite3_mutex_enter(mem.mutex);
  16915. if( pHdr->pPrev ){
  16916. assert( pHdr->pPrev->pNext==pHdr );
  16917. pHdr->pPrev->pNext = pHdr->pNext;
  16918. }else{
  16919. assert( mem.pFirst==pHdr );
  16920. mem.pFirst = pHdr->pNext;
  16921. }
  16922. if( pHdr->pNext ){
  16923. assert( pHdr->pNext->pPrev==pHdr );
  16924. pHdr->pNext->pPrev = pHdr->pPrev;
  16925. }else{
  16926. assert( mem.pLast==pHdr );
  16927. mem.pLast = pHdr->pPrev;
  16928. }
  16929. z = (char*)pBt;
  16930. z -= pHdr->nTitle;
  16931. adjustStats((int)pHdr->iSize, -1);
  16932. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  16933. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  16934. free(z);
  16935. sqlite3_mutex_leave(mem.mutex);
  16936. }
  16937. /*
  16938. ** Change the size of an existing memory allocation.
  16939. **
  16940. ** For this debugging implementation, we *always* make a copy of the
  16941. ** allocation into a new place in memory. In this way, if the
  16942. ** higher level code is using pointer to the old allocation, it is
  16943. ** much more likely to break and we are much more liking to find
  16944. ** the error.
  16945. */
  16946. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  16947. struct MemBlockHdr *pOldHdr;
  16948. void *pNew;
  16949. assert( mem.disallow==0 );
  16950. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  16951. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  16952. pNew = sqlite3MemMalloc(nByte);
  16953. if( pNew ){
  16954. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  16955. if( nByte>pOldHdr->iSize ){
  16956. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  16957. }
  16958. sqlite3MemFree(pPrior);
  16959. }
  16960. return pNew;
  16961. }
  16962. /*
  16963. ** Populate the low-level memory allocation function pointers in
  16964. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16965. */
  16966. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16967. static const sqlite3_mem_methods defaultMethods = {
  16968. sqlite3MemMalloc,
  16969. sqlite3MemFree,
  16970. sqlite3MemRealloc,
  16971. sqlite3MemSize,
  16972. sqlite3MemRoundup,
  16973. sqlite3MemInit,
  16974. sqlite3MemShutdown,
  16975. 0
  16976. };
  16977. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16978. }
  16979. /*
  16980. ** Set the "type" of an allocation.
  16981. */
  16982. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  16983. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16984. struct MemBlockHdr *pHdr;
  16985. pHdr = sqlite3MemsysGetHeader(p);
  16986. assert( pHdr->iForeGuard==FOREGUARD );
  16987. pHdr->eType = eType;
  16988. }
  16989. }
  16990. /*
  16991. ** Return TRUE if the mask of type in eType matches the type of the
  16992. ** allocation p. Also return true if p==NULL.
  16993. **
  16994. ** This routine is designed for use within an assert() statement, to
  16995. ** verify the type of an allocation. For example:
  16996. **
  16997. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  16998. */
  16999. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  17000. int rc = 1;
  17001. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17002. struct MemBlockHdr *pHdr;
  17003. pHdr = sqlite3MemsysGetHeader(p);
  17004. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  17005. if( (pHdr->eType&eType)==0 ){
  17006. rc = 0;
  17007. }
  17008. }
  17009. return rc;
  17010. }
  17011. /*
  17012. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  17013. ** allocation p. Also return true if p==NULL.
  17014. **
  17015. ** This routine is designed for use within an assert() statement, to
  17016. ** verify the type of an allocation. For example:
  17017. **
  17018. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  17019. */
  17020. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  17021. int rc = 1;
  17022. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  17023. struct MemBlockHdr *pHdr;
  17024. pHdr = sqlite3MemsysGetHeader(p);
  17025. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  17026. if( (pHdr->eType&eType)!=0 ){
  17027. rc = 0;
  17028. }
  17029. }
  17030. return rc;
  17031. }
  17032. /*
  17033. ** Set the number of backtrace levels kept for each allocation.
  17034. ** A value of zero turns off backtracing. The number is always rounded
  17035. ** up to a multiple of 2.
  17036. */
  17037. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  17038. if( depth<0 ){ depth = 0; }
  17039. if( depth>20 ){ depth = 20; }
  17040. depth = (depth+1)&0xfe;
  17041. mem.nBacktrace = depth;
  17042. }
  17043. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  17044. mem.xBacktrace = xBacktrace;
  17045. }
  17046. /*
  17047. ** Set the title string for subsequent allocations.
  17048. */
  17049. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  17050. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  17051. sqlite3_mutex_enter(mem.mutex);
  17052. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  17053. memcpy(mem.zTitle, zTitle, n);
  17054. mem.zTitle[n] = 0;
  17055. mem.nTitle = ROUND8(n);
  17056. sqlite3_mutex_leave(mem.mutex);
  17057. }
  17058. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  17059. struct MemBlockHdr *pHdr;
  17060. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  17061. void **pBt = (void**)pHdr;
  17062. pBt -= pHdr->nBacktraceSlots;
  17063. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  17064. }
  17065. }
  17066. /*
  17067. ** Open the file indicated and write a log of all unfreed memory
  17068. ** allocations into that log.
  17069. */
  17070. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  17071. FILE *out;
  17072. struct MemBlockHdr *pHdr;
  17073. void **pBt;
  17074. int i;
  17075. out = fopen(zFilename, "w");
  17076. if( out==0 ){
  17077. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17078. zFilename);
  17079. return;
  17080. }
  17081. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  17082. char *z = (char*)pHdr;
  17083. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  17084. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  17085. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  17086. if( pHdr->nBacktrace ){
  17087. fflush(out);
  17088. pBt = (void**)pHdr;
  17089. pBt -= pHdr->nBacktraceSlots;
  17090. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  17091. fprintf(out, "\n");
  17092. }
  17093. }
  17094. fprintf(out, "COUNTS:\n");
  17095. for(i=0; i<NCSIZE-1; i++){
  17096. if( mem.nAlloc[i] ){
  17097. fprintf(out, " %5d: %10d %10d %10d\n",
  17098. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  17099. }
  17100. }
  17101. if( mem.nAlloc[NCSIZE-1] ){
  17102. fprintf(out, " %5d: %10d %10d %10d\n",
  17103. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  17104. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  17105. }
  17106. fclose(out);
  17107. }
  17108. /*
  17109. ** Return the number of times sqlite3MemMalloc() has been called.
  17110. */
  17111. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  17112. int i;
  17113. int nTotal = 0;
  17114. for(i=0; i<NCSIZE; i++){
  17115. nTotal += mem.nAlloc[i];
  17116. }
  17117. return nTotal;
  17118. }
  17119. #endif /* SQLITE_MEMDEBUG */
  17120. /************** End of mem2.c ************************************************/
  17121. /************** Begin file mem3.c ********************************************/
  17122. /*
  17123. ** 2007 October 14
  17124. **
  17125. ** The author disclaims copyright to this source code. In place of
  17126. ** a legal notice, here is a blessing:
  17127. **
  17128. ** May you do good and not evil.
  17129. ** May you find forgiveness for yourself and forgive others.
  17130. ** May you share freely, never taking more than you give.
  17131. **
  17132. *************************************************************************
  17133. ** This file contains the C functions that implement a memory
  17134. ** allocation subsystem for use by SQLite.
  17135. **
  17136. ** This version of the memory allocation subsystem omits all
  17137. ** use of malloc(). The SQLite user supplies a block of memory
  17138. ** before calling sqlite3_initialize() from which allocations
  17139. ** are made and returned by the xMalloc() and xRealloc()
  17140. ** implementations. Once sqlite3_initialize() has been called,
  17141. ** the amount of memory available to SQLite is fixed and cannot
  17142. ** be changed.
  17143. **
  17144. ** This version of the memory allocation subsystem is included
  17145. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  17146. */
  17147. /* #include "sqliteInt.h" */
  17148. /*
  17149. ** This version of the memory allocator is only built into the library
  17150. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  17151. ** mean that the library will use a memory-pool by default, just that
  17152. ** it is available. The mempool allocator is activated by calling
  17153. ** sqlite3_config().
  17154. */
  17155. #ifdef SQLITE_ENABLE_MEMSYS3
  17156. /*
  17157. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  17158. */
  17159. #define MX_SMALL 10
  17160. /*
  17161. ** Number of freelist hash slots
  17162. */
  17163. #define N_HASH 61
  17164. /*
  17165. ** A memory allocation (also called a "chunk") consists of two or
  17166. ** more blocks where each block is 8 bytes. The first 8 bytes are
  17167. ** a header that is not returned to the user.
  17168. **
  17169. ** A chunk is two or more blocks that is either checked out or
  17170. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  17171. ** size of the allocation in blocks if the allocation is free.
  17172. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  17173. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  17174. ** is true if the previous chunk is checked out and false if the
  17175. ** previous chunk is free. The u.hdr.prevSize field is the size of
  17176. ** the previous chunk in blocks if the previous chunk is on the
  17177. ** freelist. If the previous chunk is checked out, then
  17178. ** u.hdr.prevSize can be part of the data for that chunk and should
  17179. ** not be read or written.
  17180. **
  17181. ** We often identify a chunk by its index in mem3.aPool[]. When
  17182. ** this is done, the chunk index refers to the second block of
  17183. ** the chunk. In this way, the first chunk has an index of 1.
  17184. ** A chunk index of 0 means "no such chunk" and is the equivalent
  17185. ** of a NULL pointer.
  17186. **
  17187. ** The second block of free chunks is of the form u.list. The
  17188. ** two fields form a double-linked list of chunks of related sizes.
  17189. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  17190. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  17191. **
  17192. ** The second block of a chunk is user data if the chunk is checked
  17193. ** out. If a chunk is checked out, the user data may extend into
  17194. ** the u.hdr.prevSize value of the following chunk.
  17195. */
  17196. typedef struct Mem3Block Mem3Block;
  17197. struct Mem3Block {
  17198. union {
  17199. struct {
  17200. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  17201. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  17202. } hdr;
  17203. struct {
  17204. u32 next; /* Index in mem3.aPool[] of next free chunk */
  17205. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  17206. } list;
  17207. } u;
  17208. };
  17209. /*
  17210. ** All of the static variables used by this module are collected
  17211. ** into a single structure named "mem3". This is to keep the
  17212. ** static variables organized and to reduce namespace pollution
  17213. ** when this module is combined with other in the amalgamation.
  17214. */
  17215. static SQLITE_WSD struct Mem3Global {
  17216. /*
  17217. ** Memory available for allocation. nPool is the size of the array
  17218. ** (in Mem3Blocks) pointed to by aPool less 2.
  17219. */
  17220. u32 nPool;
  17221. Mem3Block *aPool;
  17222. /*
  17223. ** True if we are evaluating an out-of-memory callback.
  17224. */
  17225. int alarmBusy;
  17226. /*
  17227. ** Mutex to control access to the memory allocation subsystem.
  17228. */
  17229. sqlite3_mutex *mutex;
  17230. /*
  17231. ** The minimum amount of free space that we have seen.
  17232. */
  17233. u32 mnMaster;
  17234. /*
  17235. ** iMaster is the index of the master chunk. Most new allocations
  17236. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  17237. ** of the current master. iMaster is 0 if there is not master chunk.
  17238. ** The master chunk is not in either the aiHash[] or aiSmall[].
  17239. */
  17240. u32 iMaster;
  17241. u32 szMaster;
  17242. /*
  17243. ** Array of lists of free blocks according to the block size
  17244. ** for smaller chunks, or a hash on the block size for larger
  17245. ** chunks.
  17246. */
  17247. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  17248. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  17249. } mem3 = { 97535575 };
  17250. #define mem3 GLOBAL(struct Mem3Global, mem3)
  17251. /*
  17252. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  17253. ** on. *pRoot is the list that i is a member of.
  17254. */
  17255. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  17256. u32 next = mem3.aPool[i].u.list.next;
  17257. u32 prev = mem3.aPool[i].u.list.prev;
  17258. assert( sqlite3_mutex_held(mem3.mutex) );
  17259. if( prev==0 ){
  17260. *pRoot = next;
  17261. }else{
  17262. mem3.aPool[prev].u.list.next = next;
  17263. }
  17264. if( next ){
  17265. mem3.aPool[next].u.list.prev = prev;
  17266. }
  17267. mem3.aPool[i].u.list.next = 0;
  17268. mem3.aPool[i].u.list.prev = 0;
  17269. }
  17270. /*
  17271. ** Unlink the chunk at index i from
  17272. ** whatever list is currently a member of.
  17273. */
  17274. static void memsys3Unlink(u32 i){
  17275. u32 size, hash;
  17276. assert( sqlite3_mutex_held(mem3.mutex) );
  17277. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  17278. assert( i>=1 );
  17279. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17280. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  17281. assert( size>=2 );
  17282. if( size <= MX_SMALL ){
  17283. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  17284. }else{
  17285. hash = size % N_HASH;
  17286. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  17287. }
  17288. }
  17289. /*
  17290. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  17291. ** at *pRoot.
  17292. */
  17293. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  17294. assert( sqlite3_mutex_held(mem3.mutex) );
  17295. mem3.aPool[i].u.list.next = *pRoot;
  17296. mem3.aPool[i].u.list.prev = 0;
  17297. if( *pRoot ){
  17298. mem3.aPool[*pRoot].u.list.prev = i;
  17299. }
  17300. *pRoot = i;
  17301. }
  17302. /*
  17303. ** Link the chunk at index i into either the appropriate
  17304. ** small chunk list, or into the large chunk hash table.
  17305. */
  17306. static void memsys3Link(u32 i){
  17307. u32 size, hash;
  17308. assert( sqlite3_mutex_held(mem3.mutex) );
  17309. assert( i>=1 );
  17310. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  17311. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17312. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  17313. assert( size>=2 );
  17314. if( size <= MX_SMALL ){
  17315. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  17316. }else{
  17317. hash = size % N_HASH;
  17318. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  17319. }
  17320. }
  17321. /*
  17322. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  17323. ** will already be held (obtained by code in malloc.c) if
  17324. ** sqlite3GlobalConfig.bMemStat is true.
  17325. */
  17326. static void memsys3Enter(void){
  17327. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  17328. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17329. }
  17330. sqlite3_mutex_enter(mem3.mutex);
  17331. }
  17332. static void memsys3Leave(void){
  17333. sqlite3_mutex_leave(mem3.mutex);
  17334. }
  17335. /*
  17336. ** Called when we are unable to satisfy an allocation of nBytes.
  17337. */
  17338. static void memsys3OutOfMemory(int nByte){
  17339. if( !mem3.alarmBusy ){
  17340. mem3.alarmBusy = 1;
  17341. assert( sqlite3_mutex_held(mem3.mutex) );
  17342. sqlite3_mutex_leave(mem3.mutex);
  17343. sqlite3_release_memory(nByte);
  17344. sqlite3_mutex_enter(mem3.mutex);
  17345. mem3.alarmBusy = 0;
  17346. }
  17347. }
  17348. /*
  17349. ** Chunk i is a free chunk that has been unlinked. Adjust its
  17350. ** size parameters for check-out and return a pointer to the
  17351. ** user portion of the chunk.
  17352. */
  17353. static void *memsys3Checkout(u32 i, u32 nBlock){
  17354. u32 x;
  17355. assert( sqlite3_mutex_held(mem3.mutex) );
  17356. assert( i>=1 );
  17357. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  17358. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  17359. x = mem3.aPool[i-1].u.hdr.size4x;
  17360. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  17361. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  17362. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  17363. return &mem3.aPool[i];
  17364. }
  17365. /*
  17366. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  17367. ** Return a pointer to the new allocation. Or, if the master chunk
  17368. ** is not large enough, return 0.
  17369. */
  17370. static void *memsys3FromMaster(u32 nBlock){
  17371. assert( sqlite3_mutex_held(mem3.mutex) );
  17372. assert( mem3.szMaster>=nBlock );
  17373. if( nBlock>=mem3.szMaster-1 ){
  17374. /* Use the entire master */
  17375. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  17376. mem3.iMaster = 0;
  17377. mem3.szMaster = 0;
  17378. mem3.mnMaster = 0;
  17379. return p;
  17380. }else{
  17381. /* Split the master block. Return the tail. */
  17382. u32 newi, x;
  17383. newi = mem3.iMaster + mem3.szMaster - nBlock;
  17384. assert( newi > mem3.iMaster+1 );
  17385. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  17386. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  17387. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  17388. mem3.szMaster -= nBlock;
  17389. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  17390. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  17391. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  17392. if( mem3.szMaster < mem3.mnMaster ){
  17393. mem3.mnMaster = mem3.szMaster;
  17394. }
  17395. return (void*)&mem3.aPool[newi];
  17396. }
  17397. }
  17398. /*
  17399. ** *pRoot is the head of a list of free chunks of the same size
  17400. ** or same size hash. In other words, *pRoot is an entry in either
  17401. ** mem3.aiSmall[] or mem3.aiHash[].
  17402. **
  17403. ** This routine examines all entries on the given list and tries
  17404. ** to coalesce each entries with adjacent free chunks.
  17405. **
  17406. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  17407. ** the current mem3.iMaster with the new larger chunk. In order for
  17408. ** this mem3.iMaster replacement to work, the master chunk must be
  17409. ** linked into the hash tables. That is not the normal state of
  17410. ** affairs, of course. The calling routine must link the master
  17411. ** chunk before invoking this routine, then must unlink the (possibly
  17412. ** changed) master chunk once this routine has finished.
  17413. */
  17414. static void memsys3Merge(u32 *pRoot){
  17415. u32 iNext, prev, size, i, x;
  17416. assert( sqlite3_mutex_held(mem3.mutex) );
  17417. for(i=*pRoot; i>0; i=iNext){
  17418. iNext = mem3.aPool[i].u.list.next;
  17419. size = mem3.aPool[i-1].u.hdr.size4x;
  17420. assert( (size&1)==0 );
  17421. if( (size&2)==0 ){
  17422. memsys3UnlinkFromList(i, pRoot);
  17423. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  17424. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  17425. if( prev==iNext ){
  17426. iNext = mem3.aPool[prev].u.list.next;
  17427. }
  17428. memsys3Unlink(prev);
  17429. size = i + size/4 - prev;
  17430. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  17431. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  17432. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  17433. memsys3Link(prev);
  17434. i = prev;
  17435. }else{
  17436. size /= 4;
  17437. }
  17438. if( size>mem3.szMaster ){
  17439. mem3.iMaster = i;
  17440. mem3.szMaster = size;
  17441. }
  17442. }
  17443. }
  17444. /*
  17445. ** Return a block of memory of at least nBytes in size.
  17446. ** Return NULL if unable.
  17447. **
  17448. ** This function assumes that the necessary mutexes, if any, are
  17449. ** already held by the caller. Hence "Unsafe".
  17450. */
  17451. static void *memsys3MallocUnsafe(int nByte){
  17452. u32 i;
  17453. u32 nBlock;
  17454. u32 toFree;
  17455. assert( sqlite3_mutex_held(mem3.mutex) );
  17456. assert( sizeof(Mem3Block)==8 );
  17457. if( nByte<=12 ){
  17458. nBlock = 2;
  17459. }else{
  17460. nBlock = (nByte + 11)/8;
  17461. }
  17462. assert( nBlock>=2 );
  17463. /* STEP 1:
  17464. ** Look for an entry of the correct size in either the small
  17465. ** chunk table or in the large chunk hash table. This is
  17466. ** successful most of the time (about 9 times out of 10).
  17467. */
  17468. if( nBlock <= MX_SMALL ){
  17469. i = mem3.aiSmall[nBlock-2];
  17470. if( i>0 ){
  17471. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  17472. return memsys3Checkout(i, nBlock);
  17473. }
  17474. }else{
  17475. int hash = nBlock % N_HASH;
  17476. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  17477. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  17478. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  17479. return memsys3Checkout(i, nBlock);
  17480. }
  17481. }
  17482. }
  17483. /* STEP 2:
  17484. ** Try to satisfy the allocation by carving a piece off of the end
  17485. ** of the master chunk. This step usually works if step 1 fails.
  17486. */
  17487. if( mem3.szMaster>=nBlock ){
  17488. return memsys3FromMaster(nBlock);
  17489. }
  17490. /* STEP 3:
  17491. ** Loop through the entire memory pool. Coalesce adjacent free
  17492. ** chunks. Recompute the master chunk as the largest free chunk.
  17493. ** Then try again to satisfy the allocation by carving a piece off
  17494. ** of the end of the master chunk. This step happens very
  17495. ** rarely (we hope!)
  17496. */
  17497. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  17498. memsys3OutOfMemory(toFree);
  17499. if( mem3.iMaster ){
  17500. memsys3Link(mem3.iMaster);
  17501. mem3.iMaster = 0;
  17502. mem3.szMaster = 0;
  17503. }
  17504. for(i=0; i<N_HASH; i++){
  17505. memsys3Merge(&mem3.aiHash[i]);
  17506. }
  17507. for(i=0; i<MX_SMALL-1; i++){
  17508. memsys3Merge(&mem3.aiSmall[i]);
  17509. }
  17510. if( mem3.szMaster ){
  17511. memsys3Unlink(mem3.iMaster);
  17512. if( mem3.szMaster>=nBlock ){
  17513. return memsys3FromMaster(nBlock);
  17514. }
  17515. }
  17516. }
  17517. /* If none of the above worked, then we fail. */
  17518. return 0;
  17519. }
  17520. /*
  17521. ** Free an outstanding memory allocation.
  17522. **
  17523. ** This function assumes that the necessary mutexes, if any, are
  17524. ** already held by the caller. Hence "Unsafe".
  17525. */
  17526. static void memsys3FreeUnsafe(void *pOld){
  17527. Mem3Block *p = (Mem3Block*)pOld;
  17528. int i;
  17529. u32 size, x;
  17530. assert( sqlite3_mutex_held(mem3.mutex) );
  17531. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  17532. i = p - mem3.aPool;
  17533. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  17534. size = mem3.aPool[i-1].u.hdr.size4x/4;
  17535. assert( i+size<=mem3.nPool+1 );
  17536. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  17537. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  17538. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  17539. memsys3Link(i);
  17540. /* Try to expand the master using the newly freed chunk */
  17541. if( mem3.iMaster ){
  17542. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  17543. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  17544. mem3.iMaster -= size;
  17545. mem3.szMaster += size;
  17546. memsys3Unlink(mem3.iMaster);
  17547. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  17548. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  17549. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  17550. }
  17551. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  17552. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  17553. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  17554. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  17555. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  17556. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  17557. }
  17558. }
  17559. }
  17560. /*
  17561. ** Return the size of an outstanding allocation, in bytes. The
  17562. ** size returned omits the 8-byte header overhead. This only
  17563. ** works for chunks that are currently checked out.
  17564. */
  17565. static int memsys3Size(void *p){
  17566. Mem3Block *pBlock;
  17567. if( p==0 ) return 0;
  17568. pBlock = (Mem3Block*)p;
  17569. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  17570. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  17571. }
  17572. /*
  17573. ** Round up a request size to the next valid allocation size.
  17574. */
  17575. static int memsys3Roundup(int n){
  17576. if( n<=12 ){
  17577. return 12;
  17578. }else{
  17579. return ((n+11)&~7) - 4;
  17580. }
  17581. }
  17582. /*
  17583. ** Allocate nBytes of memory.
  17584. */
  17585. static void *memsys3Malloc(int nBytes){
  17586. sqlite3_int64 *p;
  17587. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  17588. memsys3Enter();
  17589. p = memsys3MallocUnsafe(nBytes);
  17590. memsys3Leave();
  17591. return (void*)p;
  17592. }
  17593. /*
  17594. ** Free memory.
  17595. */
  17596. static void memsys3Free(void *pPrior){
  17597. assert( pPrior );
  17598. memsys3Enter();
  17599. memsys3FreeUnsafe(pPrior);
  17600. memsys3Leave();
  17601. }
  17602. /*
  17603. ** Change the size of an existing memory allocation
  17604. */
  17605. static void *memsys3Realloc(void *pPrior, int nBytes){
  17606. int nOld;
  17607. void *p;
  17608. if( pPrior==0 ){
  17609. return sqlite3_malloc(nBytes);
  17610. }
  17611. if( nBytes<=0 ){
  17612. sqlite3_free(pPrior);
  17613. return 0;
  17614. }
  17615. nOld = memsys3Size(pPrior);
  17616. if( nBytes<=nOld && nBytes>=nOld-128 ){
  17617. return pPrior;
  17618. }
  17619. memsys3Enter();
  17620. p = memsys3MallocUnsafe(nBytes);
  17621. if( p ){
  17622. if( nOld<nBytes ){
  17623. memcpy(p, pPrior, nOld);
  17624. }else{
  17625. memcpy(p, pPrior, nBytes);
  17626. }
  17627. memsys3FreeUnsafe(pPrior);
  17628. }
  17629. memsys3Leave();
  17630. return p;
  17631. }
  17632. /*
  17633. ** Initialize this module.
  17634. */
  17635. static int memsys3Init(void *NotUsed){
  17636. UNUSED_PARAMETER(NotUsed);
  17637. if( !sqlite3GlobalConfig.pHeap ){
  17638. return SQLITE_ERROR;
  17639. }
  17640. /* Store a pointer to the memory block in global structure mem3. */
  17641. assert( sizeof(Mem3Block)==8 );
  17642. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  17643. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  17644. /* Initialize the master block. */
  17645. mem3.szMaster = mem3.nPool;
  17646. mem3.mnMaster = mem3.szMaster;
  17647. mem3.iMaster = 1;
  17648. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  17649. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  17650. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  17651. return SQLITE_OK;
  17652. }
  17653. /*
  17654. ** Deinitialize this module.
  17655. */
  17656. static void memsys3Shutdown(void *NotUsed){
  17657. UNUSED_PARAMETER(NotUsed);
  17658. mem3.mutex = 0;
  17659. return;
  17660. }
  17661. /*
  17662. ** Open the file indicated and write a log of all unfreed memory
  17663. ** allocations into that log.
  17664. */
  17665. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  17666. #ifdef SQLITE_DEBUG
  17667. FILE *out;
  17668. u32 i, j;
  17669. u32 size;
  17670. if( zFilename==0 || zFilename[0]==0 ){
  17671. out = stdout;
  17672. }else{
  17673. out = fopen(zFilename, "w");
  17674. if( out==0 ){
  17675. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17676. zFilename);
  17677. return;
  17678. }
  17679. }
  17680. memsys3Enter();
  17681. fprintf(out, "CHUNKS:\n");
  17682. for(i=1; i<=mem3.nPool; i+=size/4){
  17683. size = mem3.aPool[i-1].u.hdr.size4x;
  17684. if( size/4<=1 ){
  17685. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  17686. assert( 0 );
  17687. break;
  17688. }
  17689. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  17690. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  17691. assert( 0 );
  17692. break;
  17693. }
  17694. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  17695. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  17696. assert( 0 );
  17697. break;
  17698. }
  17699. if( size&1 ){
  17700. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  17701. }else{
  17702. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  17703. i==mem3.iMaster ? " **master**" : "");
  17704. }
  17705. }
  17706. for(i=0; i<MX_SMALL-1; i++){
  17707. if( mem3.aiSmall[i]==0 ) continue;
  17708. fprintf(out, "small(%2d):", i);
  17709. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  17710. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17711. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17712. }
  17713. fprintf(out, "\n");
  17714. }
  17715. for(i=0; i<N_HASH; i++){
  17716. if( mem3.aiHash[i]==0 ) continue;
  17717. fprintf(out, "hash(%2d):", i);
  17718. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  17719. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17720. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17721. }
  17722. fprintf(out, "\n");
  17723. }
  17724. fprintf(out, "master=%d\n", mem3.iMaster);
  17725. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  17726. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  17727. sqlite3_mutex_leave(mem3.mutex);
  17728. if( out==stdout ){
  17729. fflush(stdout);
  17730. }else{
  17731. fclose(out);
  17732. }
  17733. #else
  17734. UNUSED_PARAMETER(zFilename);
  17735. #endif
  17736. }
  17737. /*
  17738. ** This routine is the only routine in this file with external
  17739. ** linkage.
  17740. **
  17741. ** Populate the low-level memory allocation function pointers in
  17742. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  17743. ** arguments specify the block of memory to manage.
  17744. **
  17745. ** This routine is only called by sqlite3_config(), and therefore
  17746. ** is not required to be threadsafe (it is not).
  17747. */
  17748. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  17749. static const sqlite3_mem_methods mempoolMethods = {
  17750. memsys3Malloc,
  17751. memsys3Free,
  17752. memsys3Realloc,
  17753. memsys3Size,
  17754. memsys3Roundup,
  17755. memsys3Init,
  17756. memsys3Shutdown,
  17757. 0
  17758. };
  17759. return &mempoolMethods;
  17760. }
  17761. #endif /* SQLITE_ENABLE_MEMSYS3 */
  17762. /************** End of mem3.c ************************************************/
  17763. /************** Begin file mem5.c ********************************************/
  17764. /*
  17765. ** 2007 October 14
  17766. **
  17767. ** The author disclaims copyright to this source code. In place of
  17768. ** a legal notice, here is a blessing:
  17769. **
  17770. ** May you do good and not evil.
  17771. ** May you find forgiveness for yourself and forgive others.
  17772. ** May you share freely, never taking more than you give.
  17773. **
  17774. *************************************************************************
  17775. ** This file contains the C functions that implement a memory
  17776. ** allocation subsystem for use by SQLite.
  17777. **
  17778. ** This version of the memory allocation subsystem omits all
  17779. ** use of malloc(). The application gives SQLite a block of memory
  17780. ** before calling sqlite3_initialize() from which allocations
  17781. ** are made and returned by the xMalloc() and xRealloc()
  17782. ** implementations. Once sqlite3_initialize() has been called,
  17783. ** the amount of memory available to SQLite is fixed and cannot
  17784. ** be changed.
  17785. **
  17786. ** This version of the memory allocation subsystem is included
  17787. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  17788. **
  17789. ** This memory allocator uses the following algorithm:
  17790. **
  17791. ** 1. All memory allocations sizes are rounded up to a power of 2.
  17792. **
  17793. ** 2. If two adjacent free blocks are the halves of a larger block,
  17794. ** then the two blocks are coalesced into the single larger block.
  17795. **
  17796. ** 3. New memory is allocated from the first available free block.
  17797. **
  17798. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  17799. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  17800. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  17801. **
  17802. ** Let n be the size of the largest allocation divided by the minimum
  17803. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  17804. ** be the maximum amount of memory ever outstanding at one time. Let
  17805. ** N be the total amount of memory available for allocation. Robson
  17806. ** proved that this memory allocator will never breakdown due to
  17807. ** fragmentation as long as the following constraint holds:
  17808. **
  17809. ** N >= M*(1 + log2(n)/2) - n + 1
  17810. **
  17811. ** The sqlite3_status() logic tracks the maximum values of n and M so
  17812. ** that an application can, at any time, verify this constraint.
  17813. */
  17814. /* #include "sqliteInt.h" */
  17815. /*
  17816. ** This version of the memory allocator is used only when
  17817. ** SQLITE_ENABLE_MEMSYS5 is defined.
  17818. */
  17819. #ifdef SQLITE_ENABLE_MEMSYS5
  17820. /*
  17821. ** A minimum allocation is an instance of the following structure.
  17822. ** Larger allocations are an array of these structures where the
  17823. ** size of the array is a power of 2.
  17824. **
  17825. ** The size of this object must be a power of two. That fact is
  17826. ** verified in memsys5Init().
  17827. */
  17828. typedef struct Mem5Link Mem5Link;
  17829. struct Mem5Link {
  17830. int next; /* Index of next free chunk */
  17831. int prev; /* Index of previous free chunk */
  17832. };
  17833. /*
  17834. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  17835. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  17836. ** it is not actually possible to reach this limit.
  17837. */
  17838. #define LOGMAX 30
  17839. /*
  17840. ** Masks used for mem5.aCtrl[] elements.
  17841. */
  17842. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  17843. #define CTRL_FREE 0x20 /* True if not checked out */
  17844. /*
  17845. ** All of the static variables used by this module are collected
  17846. ** into a single structure named "mem5". This is to keep the
  17847. ** static variables organized and to reduce namespace pollution
  17848. ** when this module is combined with other in the amalgamation.
  17849. */
  17850. static SQLITE_WSD struct Mem5Global {
  17851. /*
  17852. ** Memory available for allocation
  17853. */
  17854. int szAtom; /* Smallest possible allocation in bytes */
  17855. int nBlock; /* Number of szAtom sized blocks in zPool */
  17856. u8 *zPool; /* Memory available to be allocated */
  17857. /*
  17858. ** Mutex to control access to the memory allocation subsystem.
  17859. */
  17860. sqlite3_mutex *mutex;
  17861. /*
  17862. ** Performance statistics
  17863. */
  17864. u64 nAlloc; /* Total number of calls to malloc */
  17865. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  17866. u64 totalExcess; /* Total internal fragmentation */
  17867. u32 currentOut; /* Current checkout, including internal fragmentation */
  17868. u32 currentCount; /* Current number of distinct checkouts */
  17869. u32 maxOut; /* Maximum instantaneous currentOut */
  17870. u32 maxCount; /* Maximum instantaneous currentCount */
  17871. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  17872. /*
  17873. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  17874. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  17875. ** and so forth.
  17876. */
  17877. int aiFreelist[LOGMAX+1];
  17878. /*
  17879. ** Space for tracking which blocks are checked out and the size
  17880. ** of each block. One byte per block.
  17881. */
  17882. u8 *aCtrl;
  17883. } mem5;
  17884. /*
  17885. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  17886. */
  17887. #define mem5 GLOBAL(struct Mem5Global, mem5)
  17888. /*
  17889. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  17890. ** structures, return a pointer to the idx-th such link.
  17891. */
  17892. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  17893. /*
  17894. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  17895. ** on. It should be found on mem5.aiFreelist[iLogsize].
  17896. */
  17897. static void memsys5Unlink(int i, int iLogsize){
  17898. int next, prev;
  17899. assert( i>=0 && i<mem5.nBlock );
  17900. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17901. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17902. next = MEM5LINK(i)->next;
  17903. prev = MEM5LINK(i)->prev;
  17904. if( prev<0 ){
  17905. mem5.aiFreelist[iLogsize] = next;
  17906. }else{
  17907. MEM5LINK(prev)->next = next;
  17908. }
  17909. if( next>=0 ){
  17910. MEM5LINK(next)->prev = prev;
  17911. }
  17912. }
  17913. /*
  17914. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  17915. ** free list.
  17916. */
  17917. static void memsys5Link(int i, int iLogsize){
  17918. int x;
  17919. assert( sqlite3_mutex_held(mem5.mutex) );
  17920. assert( i>=0 && i<mem5.nBlock );
  17921. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17922. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17923. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  17924. MEM5LINK(i)->prev = -1;
  17925. if( x>=0 ){
  17926. assert( x<mem5.nBlock );
  17927. MEM5LINK(x)->prev = i;
  17928. }
  17929. mem5.aiFreelist[iLogsize] = i;
  17930. }
  17931. /*
  17932. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  17933. ** will already be held (obtained by code in malloc.c) if
  17934. ** sqlite3GlobalConfig.bMemStat is true.
  17935. */
  17936. static void memsys5Enter(void){
  17937. sqlite3_mutex_enter(mem5.mutex);
  17938. }
  17939. static void memsys5Leave(void){
  17940. sqlite3_mutex_leave(mem5.mutex);
  17941. }
  17942. /*
  17943. ** Return the size of an outstanding allocation, in bytes. The
  17944. ** size returned omits the 8-byte header overhead. This only
  17945. ** works for chunks that are currently checked out.
  17946. */
  17947. static int memsys5Size(void *p){
  17948. int iSize = 0;
  17949. if( p ){
  17950. int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  17951. assert( i>=0 && i<mem5.nBlock );
  17952. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  17953. }
  17954. return iSize;
  17955. }
  17956. /*
  17957. ** Return a block of memory of at least nBytes in size.
  17958. ** Return NULL if unable. Return NULL if nBytes==0.
  17959. **
  17960. ** The caller guarantees that nByte is positive.
  17961. **
  17962. ** The caller has obtained a mutex prior to invoking this
  17963. ** routine so there is never any chance that two or more
  17964. ** threads can be in this routine at the same time.
  17965. */
  17966. static void *memsys5MallocUnsafe(int nByte){
  17967. int i; /* Index of a mem5.aPool[] slot */
  17968. int iBin; /* Index into mem5.aiFreelist[] */
  17969. int iFullSz; /* Size of allocation rounded up to power of 2 */
  17970. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  17971. /* nByte must be a positive */
  17972. assert( nByte>0 );
  17973. /* Keep track of the maximum allocation request. Even unfulfilled
  17974. ** requests are counted */
  17975. if( (u32)nByte>mem5.maxRequest ){
  17976. mem5.maxRequest = nByte;
  17977. }
  17978. /* Abort if the requested allocation size is larger than the largest
  17979. ** power of two that we can represent using 32-bit signed integers.
  17980. */
  17981. if( nByte > 0x40000000 ){
  17982. return 0;
  17983. }
  17984. /* Round nByte up to the next valid power of two */
  17985. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  17986. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  17987. ** block. If not, then split a block of the next larger power of
  17988. ** two in order to create a new free block of size iLogsize.
  17989. */
  17990. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  17991. if( iBin>LOGMAX ){
  17992. testcase( sqlite3GlobalConfig.xLog!=0 );
  17993. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  17994. return 0;
  17995. }
  17996. i = mem5.aiFreelist[iBin];
  17997. memsys5Unlink(i, iBin);
  17998. while( iBin>iLogsize ){
  17999. int newSize;
  18000. iBin--;
  18001. newSize = 1 << iBin;
  18002. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  18003. memsys5Link(i+newSize, iBin);
  18004. }
  18005. mem5.aCtrl[i] = iLogsize;
  18006. /* Update allocator performance statistics. */
  18007. mem5.nAlloc++;
  18008. mem5.totalAlloc += iFullSz;
  18009. mem5.totalExcess += iFullSz - nByte;
  18010. mem5.currentCount++;
  18011. mem5.currentOut += iFullSz;
  18012. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  18013. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  18014. #ifdef SQLITE_DEBUG
  18015. /* Make sure the allocated memory does not assume that it is set to zero
  18016. ** or retains a value from a previous allocation */
  18017. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  18018. #endif
  18019. /* Return a pointer to the allocated memory. */
  18020. return (void*)&mem5.zPool[i*mem5.szAtom];
  18021. }
  18022. /*
  18023. ** Free an outstanding memory allocation.
  18024. */
  18025. static void memsys5FreeUnsafe(void *pOld){
  18026. u32 size, iLogsize;
  18027. int iBlock;
  18028. /* Set iBlock to the index of the block pointed to by pOld in
  18029. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  18030. */
  18031. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  18032. /* Check that the pointer pOld points to a valid, non-free block. */
  18033. assert( iBlock>=0 && iBlock<mem5.nBlock );
  18034. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  18035. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  18036. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  18037. size = 1<<iLogsize;
  18038. assert( iBlock+size-1<(u32)mem5.nBlock );
  18039. mem5.aCtrl[iBlock] |= CTRL_FREE;
  18040. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  18041. assert( mem5.currentCount>0 );
  18042. assert( mem5.currentOut>=(size*mem5.szAtom) );
  18043. mem5.currentCount--;
  18044. mem5.currentOut -= size*mem5.szAtom;
  18045. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  18046. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  18047. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  18048. while( ALWAYS(iLogsize<LOGMAX) ){
  18049. int iBuddy;
  18050. if( (iBlock>>iLogsize) & 1 ){
  18051. iBuddy = iBlock - size;
  18052. }else{
  18053. iBuddy = iBlock + size;
  18054. }
  18055. assert( iBuddy>=0 );
  18056. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  18057. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  18058. memsys5Unlink(iBuddy, iLogsize);
  18059. iLogsize++;
  18060. if( iBuddy<iBlock ){
  18061. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  18062. mem5.aCtrl[iBlock] = 0;
  18063. iBlock = iBuddy;
  18064. }else{
  18065. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  18066. mem5.aCtrl[iBuddy] = 0;
  18067. }
  18068. size *= 2;
  18069. }
  18070. #ifdef SQLITE_DEBUG
  18071. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  18072. ** not used after being freed */
  18073. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  18074. #endif
  18075. memsys5Link(iBlock, iLogsize);
  18076. }
  18077. /*
  18078. ** Allocate nBytes of memory.
  18079. */
  18080. static void *memsys5Malloc(int nBytes){
  18081. sqlite3_int64 *p = 0;
  18082. if( nBytes>0 ){
  18083. memsys5Enter();
  18084. p = memsys5MallocUnsafe(nBytes);
  18085. memsys5Leave();
  18086. }
  18087. return (void*)p;
  18088. }
  18089. /*
  18090. ** Free memory.
  18091. **
  18092. ** The outer layer memory allocator prevents this routine from
  18093. ** being called with pPrior==0.
  18094. */
  18095. static void memsys5Free(void *pPrior){
  18096. assert( pPrior!=0 );
  18097. memsys5Enter();
  18098. memsys5FreeUnsafe(pPrior);
  18099. memsys5Leave();
  18100. }
  18101. /*
  18102. ** Change the size of an existing memory allocation.
  18103. **
  18104. ** The outer layer memory allocator prevents this routine from
  18105. ** being called with pPrior==0.
  18106. **
  18107. ** nBytes is always a value obtained from a prior call to
  18108. ** memsys5Round(). Hence nBytes is always a non-negative power
  18109. ** of two. If nBytes==0 that means that an oversize allocation
  18110. ** (an allocation larger than 0x40000000) was requested and this
  18111. ** routine should return 0 without freeing pPrior.
  18112. */
  18113. static void *memsys5Realloc(void *pPrior, int nBytes){
  18114. int nOld;
  18115. void *p;
  18116. assert( pPrior!=0 );
  18117. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  18118. assert( nBytes>=0 );
  18119. if( nBytes==0 ){
  18120. return 0;
  18121. }
  18122. nOld = memsys5Size(pPrior);
  18123. if( nBytes<=nOld ){
  18124. return pPrior;
  18125. }
  18126. memsys5Enter();
  18127. p = memsys5MallocUnsafe(nBytes);
  18128. if( p ){
  18129. memcpy(p, pPrior, nOld);
  18130. memsys5FreeUnsafe(pPrior);
  18131. }
  18132. memsys5Leave();
  18133. return p;
  18134. }
  18135. /*
  18136. ** Round up a request size to the next valid allocation size. If
  18137. ** the allocation is too large to be handled by this allocation system,
  18138. ** return 0.
  18139. **
  18140. ** All allocations must be a power of two and must be expressed by a
  18141. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  18142. ** or 1073741824 bytes.
  18143. */
  18144. static int memsys5Roundup(int n){
  18145. int iFullSz;
  18146. if( n > 0x40000000 ) return 0;
  18147. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  18148. return iFullSz;
  18149. }
  18150. /*
  18151. ** Return the ceiling of the logarithm base 2 of iValue.
  18152. **
  18153. ** Examples: memsys5Log(1) -> 0
  18154. ** memsys5Log(2) -> 1
  18155. ** memsys5Log(4) -> 2
  18156. ** memsys5Log(5) -> 3
  18157. ** memsys5Log(8) -> 3
  18158. ** memsys5Log(9) -> 4
  18159. */
  18160. static int memsys5Log(int iValue){
  18161. int iLog;
  18162. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  18163. return iLog;
  18164. }
  18165. /*
  18166. ** Initialize the memory allocator.
  18167. **
  18168. ** This routine is not threadsafe. The caller must be holding a mutex
  18169. ** to prevent multiple threads from entering at the same time.
  18170. */
  18171. static int memsys5Init(void *NotUsed){
  18172. int ii; /* Loop counter */
  18173. int nByte; /* Number of bytes of memory available to this allocator */
  18174. u8 *zByte; /* Memory usable by this allocator */
  18175. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  18176. int iOffset; /* An offset into mem5.aCtrl[] */
  18177. UNUSED_PARAMETER(NotUsed);
  18178. /* For the purposes of this routine, disable the mutex */
  18179. mem5.mutex = 0;
  18180. /* The size of a Mem5Link object must be a power of two. Verify that
  18181. ** this is case.
  18182. */
  18183. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  18184. nByte = sqlite3GlobalConfig.nHeap;
  18185. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  18186. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  18187. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  18188. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  18189. mem5.szAtom = (1<<nMinLog);
  18190. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  18191. mem5.szAtom = mem5.szAtom << 1;
  18192. }
  18193. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  18194. mem5.zPool = zByte;
  18195. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  18196. for(ii=0; ii<=LOGMAX; ii++){
  18197. mem5.aiFreelist[ii] = -1;
  18198. }
  18199. iOffset = 0;
  18200. for(ii=LOGMAX; ii>=0; ii--){
  18201. int nAlloc = (1<<ii);
  18202. if( (iOffset+nAlloc)<=mem5.nBlock ){
  18203. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  18204. memsys5Link(iOffset, ii);
  18205. iOffset += nAlloc;
  18206. }
  18207. assert((iOffset+nAlloc)>mem5.nBlock);
  18208. }
  18209. /* If a mutex is required for normal operation, allocate one */
  18210. if( sqlite3GlobalConfig.bMemstat==0 ){
  18211. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18212. }
  18213. return SQLITE_OK;
  18214. }
  18215. /*
  18216. ** Deinitialize this module.
  18217. */
  18218. static void memsys5Shutdown(void *NotUsed){
  18219. UNUSED_PARAMETER(NotUsed);
  18220. mem5.mutex = 0;
  18221. return;
  18222. }
  18223. #ifdef SQLITE_TEST
  18224. /*
  18225. ** Open the file indicated and write a log of all unfreed memory
  18226. ** allocations into that log.
  18227. */
  18228. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  18229. FILE *out;
  18230. int i, j, n;
  18231. int nMinLog;
  18232. if( zFilename==0 || zFilename[0]==0 ){
  18233. out = stdout;
  18234. }else{
  18235. out = fopen(zFilename, "w");
  18236. if( out==0 ){
  18237. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  18238. zFilename);
  18239. return;
  18240. }
  18241. }
  18242. memsys5Enter();
  18243. nMinLog = memsys5Log(mem5.szAtom);
  18244. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  18245. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  18246. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  18247. }
  18248. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  18249. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  18250. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  18251. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  18252. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  18253. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  18254. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  18255. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  18256. memsys5Leave();
  18257. if( out==stdout ){
  18258. fflush(stdout);
  18259. }else{
  18260. fclose(out);
  18261. }
  18262. }
  18263. #endif
  18264. /*
  18265. ** This routine is the only routine in this file with external
  18266. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  18267. ** struct populated with the memsys5 methods.
  18268. */
  18269. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  18270. static const sqlite3_mem_methods memsys5Methods = {
  18271. memsys5Malloc,
  18272. memsys5Free,
  18273. memsys5Realloc,
  18274. memsys5Size,
  18275. memsys5Roundup,
  18276. memsys5Init,
  18277. memsys5Shutdown,
  18278. 0
  18279. };
  18280. return &memsys5Methods;
  18281. }
  18282. #endif /* SQLITE_ENABLE_MEMSYS5 */
  18283. /************** End of mem5.c ************************************************/
  18284. /************** Begin file mutex.c *******************************************/
  18285. /*
  18286. ** 2007 August 14
  18287. **
  18288. ** The author disclaims copyright to this source code. In place of
  18289. ** a legal notice, here is a blessing:
  18290. **
  18291. ** May you do good and not evil.
  18292. ** May you find forgiveness for yourself and forgive others.
  18293. ** May you share freely, never taking more than you give.
  18294. **
  18295. *************************************************************************
  18296. ** This file contains the C functions that implement mutexes.
  18297. **
  18298. ** This file contains code that is common across all mutex implementations.
  18299. */
  18300. /* #include "sqliteInt.h" */
  18301. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  18302. /*
  18303. ** For debugging purposes, record when the mutex subsystem is initialized
  18304. ** and uninitialized so that we can assert() if there is an attempt to
  18305. ** allocate a mutex while the system is uninitialized.
  18306. */
  18307. static SQLITE_WSD int mutexIsInit = 0;
  18308. #endif /* SQLITE_DEBUG */
  18309. #ifndef SQLITE_MUTEX_OMIT
  18310. /*
  18311. ** Initialize the mutex system.
  18312. */
  18313. SQLITE_PRIVATE int sqlite3MutexInit(void){
  18314. int rc = SQLITE_OK;
  18315. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  18316. /* If the xMutexAlloc method has not been set, then the user did not
  18317. ** install a mutex implementation via sqlite3_config() prior to
  18318. ** sqlite3_initialize() being called. This block copies pointers to
  18319. ** the default implementation into the sqlite3GlobalConfig structure.
  18320. */
  18321. sqlite3_mutex_methods const *pFrom;
  18322. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  18323. if( sqlite3GlobalConfig.bCoreMutex ){
  18324. pFrom = sqlite3DefaultMutex();
  18325. }else{
  18326. pFrom = sqlite3NoopMutex();
  18327. }
  18328. pTo->xMutexInit = pFrom->xMutexInit;
  18329. pTo->xMutexEnd = pFrom->xMutexEnd;
  18330. pTo->xMutexFree = pFrom->xMutexFree;
  18331. pTo->xMutexEnter = pFrom->xMutexEnter;
  18332. pTo->xMutexTry = pFrom->xMutexTry;
  18333. pTo->xMutexLeave = pFrom->xMutexLeave;
  18334. pTo->xMutexHeld = pFrom->xMutexHeld;
  18335. pTo->xMutexNotheld = pFrom->xMutexNotheld;
  18336. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  18337. }
  18338. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  18339. #ifdef SQLITE_DEBUG
  18340. GLOBAL(int, mutexIsInit) = 1;
  18341. #endif
  18342. return rc;
  18343. }
  18344. /*
  18345. ** Shutdown the mutex system. This call frees resources allocated by
  18346. ** sqlite3MutexInit().
  18347. */
  18348. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  18349. int rc = SQLITE_OK;
  18350. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  18351. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  18352. }
  18353. #ifdef SQLITE_DEBUG
  18354. GLOBAL(int, mutexIsInit) = 0;
  18355. #endif
  18356. return rc;
  18357. }
  18358. /*
  18359. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  18360. */
  18361. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
  18362. #ifndef SQLITE_OMIT_AUTOINIT
  18363. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  18364. if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
  18365. #endif
  18366. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  18367. }
  18368. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  18369. if( !sqlite3GlobalConfig.bCoreMutex ){
  18370. return 0;
  18371. }
  18372. assert( GLOBAL(int, mutexIsInit) );
  18373. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  18374. }
  18375. /*
  18376. ** Free a dynamic mutex.
  18377. */
  18378. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
  18379. if( p ){
  18380. sqlite3GlobalConfig.mutex.xMutexFree(p);
  18381. }
  18382. }
  18383. /*
  18384. ** Obtain the mutex p. If some other thread already has the mutex, block
  18385. ** until it can be obtained.
  18386. */
  18387. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
  18388. if( p ){
  18389. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  18390. }
  18391. }
  18392. /*
  18393. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  18394. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  18395. */
  18396. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
  18397. int rc = SQLITE_OK;
  18398. if( p ){
  18399. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  18400. }
  18401. return rc;
  18402. }
  18403. /*
  18404. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  18405. ** entered by the same thread. The behavior is undefined if the mutex
  18406. ** is not currently entered. If a NULL pointer is passed as an argument
  18407. ** this function is a no-op.
  18408. */
  18409. SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
  18410. if( p ){
  18411. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  18412. }
  18413. }
  18414. #ifndef NDEBUG
  18415. /*
  18416. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18417. ** intended for use inside assert() statements.
  18418. */
  18419. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
  18420. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  18421. }
  18422. SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
  18423. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  18424. }
  18425. #endif
  18426. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  18427. /************** End of mutex.c ***********************************************/
  18428. /************** Begin file mutex_noop.c **************************************/
  18429. /*
  18430. ** 2008 October 07
  18431. **
  18432. ** The author disclaims copyright to this source code. In place of
  18433. ** a legal notice, here is a blessing:
  18434. **
  18435. ** May you do good and not evil.
  18436. ** May you find forgiveness for yourself and forgive others.
  18437. ** May you share freely, never taking more than you give.
  18438. **
  18439. *************************************************************************
  18440. ** This file contains the C functions that implement mutexes.
  18441. **
  18442. ** This implementation in this file does not provide any mutual
  18443. ** exclusion and is thus suitable for use only in applications
  18444. ** that use SQLite in a single thread. The routines defined
  18445. ** here are place-holders. Applications can substitute working
  18446. ** mutex routines at start-time using the
  18447. **
  18448. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  18449. **
  18450. ** interface.
  18451. **
  18452. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  18453. ** that does error checking on mutexes to make sure they are being
  18454. ** called correctly.
  18455. */
  18456. /* #include "sqliteInt.h" */
  18457. #ifndef SQLITE_MUTEX_OMIT
  18458. #ifndef SQLITE_DEBUG
  18459. /*
  18460. ** Stub routines for all mutex methods.
  18461. **
  18462. ** This routines provide no mutual exclusion or error checking.
  18463. */
  18464. static int noopMutexInit(void){ return SQLITE_OK; }
  18465. static int noopMutexEnd(void){ return SQLITE_OK; }
  18466. static sqlite3_mutex *noopMutexAlloc(int id){
  18467. UNUSED_PARAMETER(id);
  18468. return (sqlite3_mutex*)8;
  18469. }
  18470. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  18471. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  18472. static int noopMutexTry(sqlite3_mutex *p){
  18473. UNUSED_PARAMETER(p);
  18474. return SQLITE_OK;
  18475. }
  18476. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  18477. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  18478. static const sqlite3_mutex_methods sMutex = {
  18479. noopMutexInit,
  18480. noopMutexEnd,
  18481. noopMutexAlloc,
  18482. noopMutexFree,
  18483. noopMutexEnter,
  18484. noopMutexTry,
  18485. noopMutexLeave,
  18486. 0,
  18487. 0,
  18488. };
  18489. return &sMutex;
  18490. }
  18491. #endif /* !SQLITE_DEBUG */
  18492. #ifdef SQLITE_DEBUG
  18493. /*
  18494. ** In this implementation, error checking is provided for testing
  18495. ** and debugging purposes. The mutexes still do not provide any
  18496. ** mutual exclusion.
  18497. */
  18498. /*
  18499. ** The mutex object
  18500. */
  18501. typedef struct sqlite3_debug_mutex {
  18502. int id; /* The mutex type */
  18503. int cnt; /* Number of entries without a matching leave */
  18504. } sqlite3_debug_mutex;
  18505. /*
  18506. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18507. ** intended for use inside assert() statements.
  18508. */
  18509. static int debugMutexHeld(sqlite3_mutex *pX){
  18510. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18511. return p==0 || p->cnt>0;
  18512. }
  18513. static int debugMutexNotheld(sqlite3_mutex *pX){
  18514. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18515. return p==0 || p->cnt==0;
  18516. }
  18517. /*
  18518. ** Initialize and deinitialize the mutex subsystem.
  18519. */
  18520. static int debugMutexInit(void){ return SQLITE_OK; }
  18521. static int debugMutexEnd(void){ return SQLITE_OK; }
  18522. /*
  18523. ** The sqlite3_mutex_alloc() routine allocates a new
  18524. ** mutex and returns a pointer to it. If it returns NULL
  18525. ** that means that a mutex could not be allocated.
  18526. */
  18527. static sqlite3_mutex *debugMutexAlloc(int id){
  18528. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
  18529. sqlite3_debug_mutex *pNew = 0;
  18530. switch( id ){
  18531. case SQLITE_MUTEX_FAST:
  18532. case SQLITE_MUTEX_RECURSIVE: {
  18533. pNew = sqlite3Malloc(sizeof(*pNew));
  18534. if( pNew ){
  18535. pNew->id = id;
  18536. pNew->cnt = 0;
  18537. }
  18538. break;
  18539. }
  18540. default: {
  18541. #ifdef SQLITE_ENABLE_API_ARMOR
  18542. if( id-2<0 || id-2>=ArraySize(aStatic) ){
  18543. (void)SQLITE_MISUSE_BKPT;
  18544. return 0;
  18545. }
  18546. #endif
  18547. pNew = &aStatic[id-2];
  18548. pNew->id = id;
  18549. break;
  18550. }
  18551. }
  18552. return (sqlite3_mutex*)pNew;
  18553. }
  18554. /*
  18555. ** This routine deallocates a previously allocated mutex.
  18556. */
  18557. static void debugMutexFree(sqlite3_mutex *pX){
  18558. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18559. assert( p->cnt==0 );
  18560. if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
  18561. sqlite3_free(p);
  18562. }else{
  18563. #ifdef SQLITE_ENABLE_API_ARMOR
  18564. (void)SQLITE_MISUSE_BKPT;
  18565. #endif
  18566. }
  18567. }
  18568. /*
  18569. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18570. ** to enter a mutex. If another thread is already within the mutex,
  18571. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18572. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18573. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18574. ** be entered multiple times by the same thread. In such cases the,
  18575. ** mutex must be exited an equal number of times before another thread
  18576. ** can enter. If the same thread tries to enter any other kind of mutex
  18577. ** more than once, the behavior is undefined.
  18578. */
  18579. static void debugMutexEnter(sqlite3_mutex *pX){
  18580. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18581. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  18582. p->cnt++;
  18583. }
  18584. static int debugMutexTry(sqlite3_mutex *pX){
  18585. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18586. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  18587. p->cnt++;
  18588. return SQLITE_OK;
  18589. }
  18590. /*
  18591. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18592. ** previously entered by the same thread. The behavior
  18593. ** is undefined if the mutex is not currently entered or
  18594. ** is not currently allocated. SQLite will never do either.
  18595. */
  18596. static void debugMutexLeave(sqlite3_mutex *pX){
  18597. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  18598. assert( debugMutexHeld(pX) );
  18599. p->cnt--;
  18600. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  18601. }
  18602. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  18603. static const sqlite3_mutex_methods sMutex = {
  18604. debugMutexInit,
  18605. debugMutexEnd,
  18606. debugMutexAlloc,
  18607. debugMutexFree,
  18608. debugMutexEnter,
  18609. debugMutexTry,
  18610. debugMutexLeave,
  18611. debugMutexHeld,
  18612. debugMutexNotheld
  18613. };
  18614. return &sMutex;
  18615. }
  18616. #endif /* SQLITE_DEBUG */
  18617. /*
  18618. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  18619. ** is used regardless of the run-time threadsafety setting.
  18620. */
  18621. #ifdef SQLITE_MUTEX_NOOP
  18622. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18623. return sqlite3NoopMutex();
  18624. }
  18625. #endif /* defined(SQLITE_MUTEX_NOOP) */
  18626. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  18627. /************** End of mutex_noop.c ******************************************/
  18628. /************** Begin file mutex_unix.c **************************************/
  18629. /*
  18630. ** 2007 August 28
  18631. **
  18632. ** The author disclaims copyright to this source code. In place of
  18633. ** a legal notice, here is a blessing:
  18634. **
  18635. ** May you do good and not evil.
  18636. ** May you find forgiveness for yourself and forgive others.
  18637. ** May you share freely, never taking more than you give.
  18638. **
  18639. *************************************************************************
  18640. ** This file contains the C functions that implement mutexes for pthreads
  18641. */
  18642. /* #include "sqliteInt.h" */
  18643. /*
  18644. ** The code in this file is only used if we are compiling threadsafe
  18645. ** under unix with pthreads.
  18646. **
  18647. ** Note that this implementation requires a version of pthreads that
  18648. ** supports recursive mutexes.
  18649. */
  18650. #ifdef SQLITE_MUTEX_PTHREADS
  18651. #include <pthread.h>
  18652. /*
  18653. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  18654. ** are necessary under two condidtions: (1) Debug builds and (2) using
  18655. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  18656. */
  18657. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  18658. # define SQLITE_MUTEX_NREF 1
  18659. #else
  18660. # define SQLITE_MUTEX_NREF 0
  18661. #endif
  18662. /*
  18663. ** Each recursive mutex is an instance of the following structure.
  18664. */
  18665. struct sqlite3_mutex {
  18666. pthread_mutex_t mutex; /* Mutex controlling the lock */
  18667. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  18668. int id; /* Mutex type */
  18669. #endif
  18670. #if SQLITE_MUTEX_NREF
  18671. volatile int nRef; /* Number of entrances */
  18672. volatile pthread_t owner; /* Thread that is within this mutex */
  18673. int trace; /* True to trace changes */
  18674. #endif
  18675. };
  18676. #if SQLITE_MUTEX_NREF
  18677. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  18678. #else
  18679. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  18680. #endif
  18681. /*
  18682. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18683. ** intended for use only inside assert() statements. On some platforms,
  18684. ** there might be race conditions that can cause these routines to
  18685. ** deliver incorrect results. In particular, if pthread_equal() is
  18686. ** not an atomic operation, then these routines might delivery
  18687. ** incorrect results. On most platforms, pthread_equal() is a
  18688. ** comparison of two integers and is therefore atomic. But we are
  18689. ** told that HPUX is not such a platform. If so, then these routines
  18690. ** will not always work correctly on HPUX.
  18691. **
  18692. ** On those platforms where pthread_equal() is not atomic, SQLite
  18693. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  18694. ** make sure no assert() statements are evaluated and hence these
  18695. ** routines are never called.
  18696. */
  18697. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  18698. static int pthreadMutexHeld(sqlite3_mutex *p){
  18699. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  18700. }
  18701. static int pthreadMutexNotheld(sqlite3_mutex *p){
  18702. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  18703. }
  18704. #endif
  18705. /*
  18706. ** Initialize and deinitialize the mutex subsystem.
  18707. */
  18708. static int pthreadMutexInit(void){ return SQLITE_OK; }
  18709. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  18710. /*
  18711. ** The sqlite3_mutex_alloc() routine allocates a new
  18712. ** mutex and returns a pointer to it. If it returns NULL
  18713. ** that means that a mutex could not be allocated. SQLite
  18714. ** will unwind its stack and return an error. The argument
  18715. ** to sqlite3_mutex_alloc() is one of these integer constants:
  18716. **
  18717. ** <ul>
  18718. ** <li> SQLITE_MUTEX_FAST
  18719. ** <li> SQLITE_MUTEX_RECURSIVE
  18720. ** <li> SQLITE_MUTEX_STATIC_MASTER
  18721. ** <li> SQLITE_MUTEX_STATIC_MEM
  18722. ** <li> SQLITE_MUTEX_STATIC_OPEN
  18723. ** <li> SQLITE_MUTEX_STATIC_PRNG
  18724. ** <li> SQLITE_MUTEX_STATIC_LRU
  18725. ** <li> SQLITE_MUTEX_STATIC_PMEM
  18726. ** <li> SQLITE_MUTEX_STATIC_APP1
  18727. ** <li> SQLITE_MUTEX_STATIC_APP2
  18728. ** <li> SQLITE_MUTEX_STATIC_APP3
  18729. ** <li> SQLITE_MUTEX_STATIC_VFS1
  18730. ** <li> SQLITE_MUTEX_STATIC_VFS2
  18731. ** <li> SQLITE_MUTEX_STATIC_VFS3
  18732. ** </ul>
  18733. **
  18734. ** The first two constants cause sqlite3_mutex_alloc() to create
  18735. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  18736. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  18737. ** The mutex implementation does not need to make a distinction
  18738. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  18739. ** not want to. But SQLite will only request a recursive mutex in
  18740. ** cases where it really needs one. If a faster non-recursive mutex
  18741. ** implementation is available on the host platform, the mutex subsystem
  18742. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  18743. **
  18744. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  18745. ** a pointer to a static preexisting mutex. Six static mutexes are
  18746. ** used by the current version of SQLite. Future versions of SQLite
  18747. ** may add additional static mutexes. Static mutexes are for internal
  18748. ** use by SQLite only. Applications that use SQLite mutexes should
  18749. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  18750. ** SQLITE_MUTEX_RECURSIVE.
  18751. **
  18752. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18753. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18754. ** returns a different mutex on every call. But for the static
  18755. ** mutex types, the same mutex is returned on every call that has
  18756. ** the same type number.
  18757. */
  18758. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  18759. static sqlite3_mutex staticMutexes[] = {
  18760. SQLITE3_MUTEX_INITIALIZER,
  18761. SQLITE3_MUTEX_INITIALIZER,
  18762. SQLITE3_MUTEX_INITIALIZER,
  18763. SQLITE3_MUTEX_INITIALIZER,
  18764. SQLITE3_MUTEX_INITIALIZER,
  18765. SQLITE3_MUTEX_INITIALIZER,
  18766. SQLITE3_MUTEX_INITIALIZER,
  18767. SQLITE3_MUTEX_INITIALIZER,
  18768. SQLITE3_MUTEX_INITIALIZER,
  18769. SQLITE3_MUTEX_INITIALIZER,
  18770. SQLITE3_MUTEX_INITIALIZER,
  18771. SQLITE3_MUTEX_INITIALIZER
  18772. };
  18773. sqlite3_mutex *p;
  18774. switch( iType ){
  18775. case SQLITE_MUTEX_RECURSIVE: {
  18776. p = sqlite3MallocZero( sizeof(*p) );
  18777. if( p ){
  18778. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18779. /* If recursive mutexes are not available, we will have to
  18780. ** build our own. See below. */
  18781. pthread_mutex_init(&p->mutex, 0);
  18782. #else
  18783. /* Use a recursive mutex if it is available */
  18784. pthread_mutexattr_t recursiveAttr;
  18785. pthread_mutexattr_init(&recursiveAttr);
  18786. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  18787. pthread_mutex_init(&p->mutex, &recursiveAttr);
  18788. pthread_mutexattr_destroy(&recursiveAttr);
  18789. #endif
  18790. }
  18791. break;
  18792. }
  18793. case SQLITE_MUTEX_FAST: {
  18794. p = sqlite3MallocZero( sizeof(*p) );
  18795. if( p ){
  18796. pthread_mutex_init(&p->mutex, 0);
  18797. }
  18798. break;
  18799. }
  18800. default: {
  18801. #ifdef SQLITE_ENABLE_API_ARMOR
  18802. if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
  18803. (void)SQLITE_MISUSE_BKPT;
  18804. return 0;
  18805. }
  18806. #endif
  18807. p = &staticMutexes[iType-2];
  18808. break;
  18809. }
  18810. }
  18811. #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
  18812. if( p ) p->id = iType;
  18813. #endif
  18814. return p;
  18815. }
  18816. /*
  18817. ** This routine deallocates a previously
  18818. ** allocated mutex. SQLite is careful to deallocate every
  18819. ** mutex that it allocates.
  18820. */
  18821. static void pthreadMutexFree(sqlite3_mutex *p){
  18822. assert( p->nRef==0 );
  18823. #if SQLITE_ENABLE_API_ARMOR
  18824. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
  18825. #endif
  18826. {
  18827. pthread_mutex_destroy(&p->mutex);
  18828. sqlite3_free(p);
  18829. }
  18830. #ifdef SQLITE_ENABLE_API_ARMOR
  18831. else{
  18832. (void)SQLITE_MISUSE_BKPT;
  18833. }
  18834. #endif
  18835. }
  18836. /*
  18837. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18838. ** to enter a mutex. If another thread is already within the mutex,
  18839. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18840. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18841. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18842. ** be entered multiple times by the same thread. In such cases the,
  18843. ** mutex must be exited an equal number of times before another thread
  18844. ** can enter. If the same thread tries to enter any other kind of mutex
  18845. ** more than once, the behavior is undefined.
  18846. */
  18847. static void pthreadMutexEnter(sqlite3_mutex *p){
  18848. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18849. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18850. /* If recursive mutexes are not available, then we have to grow
  18851. ** our own. This implementation assumes that pthread_equal()
  18852. ** is atomic - that it cannot be deceived into thinking self
  18853. ** and p->owner are equal if p->owner changes between two values
  18854. ** that are not equal to self while the comparison is taking place.
  18855. ** This implementation also assumes a coherent cache - that
  18856. ** separate processes cannot read different values from the same
  18857. ** address at the same time. If either of these two conditions
  18858. ** are not met, then the mutexes will fail and problems will result.
  18859. */
  18860. {
  18861. pthread_t self = pthread_self();
  18862. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18863. p->nRef++;
  18864. }else{
  18865. pthread_mutex_lock(&p->mutex);
  18866. assert( p->nRef==0 );
  18867. p->owner = self;
  18868. p->nRef = 1;
  18869. }
  18870. }
  18871. #else
  18872. /* Use the built-in recursive mutexes if they are available.
  18873. */
  18874. pthread_mutex_lock(&p->mutex);
  18875. #if SQLITE_MUTEX_NREF
  18876. assert( p->nRef>0 || p->owner==0 );
  18877. p->owner = pthread_self();
  18878. p->nRef++;
  18879. #endif
  18880. #endif
  18881. #ifdef SQLITE_DEBUG
  18882. if( p->trace ){
  18883. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18884. }
  18885. #endif
  18886. }
  18887. static int pthreadMutexTry(sqlite3_mutex *p){
  18888. int rc;
  18889. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18890. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18891. /* If recursive mutexes are not available, then we have to grow
  18892. ** our own. This implementation assumes that pthread_equal()
  18893. ** is atomic - that it cannot be deceived into thinking self
  18894. ** and p->owner are equal if p->owner changes between two values
  18895. ** that are not equal to self while the comparison is taking place.
  18896. ** This implementation also assumes a coherent cache - that
  18897. ** separate processes cannot read different values from the same
  18898. ** address at the same time. If either of these two conditions
  18899. ** are not met, then the mutexes will fail and problems will result.
  18900. */
  18901. {
  18902. pthread_t self = pthread_self();
  18903. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18904. p->nRef++;
  18905. rc = SQLITE_OK;
  18906. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  18907. assert( p->nRef==0 );
  18908. p->owner = self;
  18909. p->nRef = 1;
  18910. rc = SQLITE_OK;
  18911. }else{
  18912. rc = SQLITE_BUSY;
  18913. }
  18914. }
  18915. #else
  18916. /* Use the built-in recursive mutexes if they are available.
  18917. */
  18918. if( pthread_mutex_trylock(&p->mutex)==0 ){
  18919. #if SQLITE_MUTEX_NREF
  18920. p->owner = pthread_self();
  18921. p->nRef++;
  18922. #endif
  18923. rc = SQLITE_OK;
  18924. }else{
  18925. rc = SQLITE_BUSY;
  18926. }
  18927. #endif
  18928. #ifdef SQLITE_DEBUG
  18929. if( rc==SQLITE_OK && p->trace ){
  18930. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18931. }
  18932. #endif
  18933. return rc;
  18934. }
  18935. /*
  18936. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18937. ** previously entered by the same thread. The behavior
  18938. ** is undefined if the mutex is not currently entered or
  18939. ** is not currently allocated. SQLite will never do either.
  18940. */
  18941. static void pthreadMutexLeave(sqlite3_mutex *p){
  18942. assert( pthreadMutexHeld(p) );
  18943. #if SQLITE_MUTEX_NREF
  18944. p->nRef--;
  18945. if( p->nRef==0 ) p->owner = 0;
  18946. #endif
  18947. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18948. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18949. if( p->nRef==0 ){
  18950. pthread_mutex_unlock(&p->mutex);
  18951. }
  18952. #else
  18953. pthread_mutex_unlock(&p->mutex);
  18954. #endif
  18955. #ifdef SQLITE_DEBUG
  18956. if( p->trace ){
  18957. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18958. }
  18959. #endif
  18960. }
  18961. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18962. static const sqlite3_mutex_methods sMutex = {
  18963. pthreadMutexInit,
  18964. pthreadMutexEnd,
  18965. pthreadMutexAlloc,
  18966. pthreadMutexFree,
  18967. pthreadMutexEnter,
  18968. pthreadMutexTry,
  18969. pthreadMutexLeave,
  18970. #ifdef SQLITE_DEBUG
  18971. pthreadMutexHeld,
  18972. pthreadMutexNotheld
  18973. #else
  18974. 0,
  18975. 0
  18976. #endif
  18977. };
  18978. return &sMutex;
  18979. }
  18980. #endif /* SQLITE_MUTEX_PTHREADS */
  18981. /************** End of mutex_unix.c ******************************************/
  18982. /************** Begin file mutex_w32.c ***************************************/
  18983. /*
  18984. ** 2007 August 14
  18985. **
  18986. ** The author disclaims copyright to this source code. In place of
  18987. ** a legal notice, here is a blessing:
  18988. **
  18989. ** May you do good and not evil.
  18990. ** May you find forgiveness for yourself and forgive others.
  18991. ** May you share freely, never taking more than you give.
  18992. **
  18993. *************************************************************************
  18994. ** This file contains the C functions that implement mutexes for Win32.
  18995. */
  18996. /* #include "sqliteInt.h" */
  18997. #if SQLITE_OS_WIN
  18998. /*
  18999. ** Include code that is common to all os_*.c files
  19000. */
  19001. /************** Include os_common.h in the middle of mutex_w32.c *************/
  19002. /************** Begin file os_common.h ***************************************/
  19003. /*
  19004. ** 2004 May 22
  19005. **
  19006. ** The author disclaims copyright to this source code. In place of
  19007. ** a legal notice, here is a blessing:
  19008. **
  19009. ** May you do good and not evil.
  19010. ** May you find forgiveness for yourself and forgive others.
  19011. ** May you share freely, never taking more than you give.
  19012. **
  19013. ******************************************************************************
  19014. **
  19015. ** This file contains macros and a little bit of code that is common to
  19016. ** all of the platform-specific files (os_*.c) and is #included into those
  19017. ** files.
  19018. **
  19019. ** This file should be #included by the os_*.c files only. It is not a
  19020. ** general purpose header file.
  19021. */
  19022. #ifndef _OS_COMMON_H_
  19023. #define _OS_COMMON_H_
  19024. /*
  19025. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  19026. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  19027. ** switch. The following code should catch this problem at compile-time.
  19028. */
  19029. #ifdef MEMORY_DEBUG
  19030. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  19031. #endif
  19032. /*
  19033. ** Macros for performance tracing. Normally turned off. Only works
  19034. ** on i486 hardware.
  19035. */
  19036. #ifdef SQLITE_PERFORMANCE_TRACE
  19037. /*
  19038. ** hwtime.h contains inline assembler code for implementing
  19039. ** high-performance timing routines.
  19040. */
  19041. /************** Include hwtime.h in the middle of os_common.h ****************/
  19042. /************** Begin file hwtime.h ******************************************/
  19043. /*
  19044. ** 2008 May 27
  19045. **
  19046. ** The author disclaims copyright to this source code. In place of
  19047. ** a legal notice, here is a blessing:
  19048. **
  19049. ** May you do good and not evil.
  19050. ** May you find forgiveness for yourself and forgive others.
  19051. ** May you share freely, never taking more than you give.
  19052. **
  19053. ******************************************************************************
  19054. **
  19055. ** This file contains inline asm code for retrieving "high-performance"
  19056. ** counters for x86 class CPUs.
  19057. */
  19058. #ifndef _HWTIME_H_
  19059. #define _HWTIME_H_
  19060. /*
  19061. ** The following routine only works on pentium-class (or newer) processors.
  19062. ** It uses the RDTSC opcode to read the cycle count value out of the
  19063. ** processor and returns that value. This can be used for high-res
  19064. ** profiling.
  19065. */
  19066. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  19067. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  19068. #if defined(__GNUC__)
  19069. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19070. unsigned int lo, hi;
  19071. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  19072. return (sqlite_uint64)hi << 32 | lo;
  19073. }
  19074. #elif defined(_MSC_VER)
  19075. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  19076. __asm {
  19077. rdtsc
  19078. ret ; return value at EDX:EAX
  19079. }
  19080. }
  19081. #endif
  19082. #elif (defined(__GNUC__) && defined(__x86_64__))
  19083. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19084. unsigned long val;
  19085. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  19086. return val;
  19087. }
  19088. #elif (defined(__GNUC__) && defined(__ppc__))
  19089. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  19090. unsigned long long retval;
  19091. unsigned long junk;
  19092. __asm__ __volatile__ ("\n\
  19093. 1: mftbu %1\n\
  19094. mftb %L0\n\
  19095. mftbu %0\n\
  19096. cmpw %0,%1\n\
  19097. bne 1b"
  19098. : "=r" (retval), "=r" (junk));
  19099. return retval;
  19100. }
  19101. #else
  19102. #error Need implementation of sqlite3Hwtime() for your platform.
  19103. /*
  19104. ** To compile without implementing sqlite3Hwtime() for your platform,
  19105. ** you can remove the above #error and use the following
  19106. ** stub function. You will lose timing support for many
  19107. ** of the debugging and testing utilities, but it should at
  19108. ** least compile and run.
  19109. */
  19110. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  19111. #endif
  19112. #endif /* !defined(_HWTIME_H_) */
  19113. /************** End of hwtime.h **********************************************/
  19114. /************** Continuing where we left off in os_common.h ******************/
  19115. static sqlite_uint64 g_start;
  19116. static sqlite_uint64 g_elapsed;
  19117. #define TIMER_START g_start=sqlite3Hwtime()
  19118. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  19119. #define TIMER_ELAPSED g_elapsed
  19120. #else
  19121. #define TIMER_START
  19122. #define TIMER_END
  19123. #define TIMER_ELAPSED ((sqlite_uint64)0)
  19124. #endif
  19125. /*
  19126. ** If we compile with the SQLITE_TEST macro set, then the following block
  19127. ** of code will give us the ability to simulate a disk I/O error. This
  19128. ** is used for testing the I/O recovery logic.
  19129. */
  19130. #ifdef SQLITE_TEST
  19131. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  19132. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  19133. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  19134. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  19135. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  19136. SQLITE_API int sqlite3_diskfull_pending = 0;
  19137. SQLITE_API int sqlite3_diskfull = 0;
  19138. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  19139. #define SimulateIOError(CODE) \
  19140. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  19141. || sqlite3_io_error_pending-- == 1 ) \
  19142. { local_ioerr(); CODE; }
  19143. static void local_ioerr(){
  19144. IOTRACE(("IOERR\n"));
  19145. sqlite3_io_error_hit++;
  19146. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  19147. }
  19148. #define SimulateDiskfullError(CODE) \
  19149. if( sqlite3_diskfull_pending ){ \
  19150. if( sqlite3_diskfull_pending == 1 ){ \
  19151. local_ioerr(); \
  19152. sqlite3_diskfull = 1; \
  19153. sqlite3_io_error_hit = 1; \
  19154. CODE; \
  19155. }else{ \
  19156. sqlite3_diskfull_pending--; \
  19157. } \
  19158. }
  19159. #else
  19160. #define SimulateIOErrorBenign(X)
  19161. #define SimulateIOError(A)
  19162. #define SimulateDiskfullError(A)
  19163. #endif
  19164. /*
  19165. ** When testing, keep a count of the number of open files.
  19166. */
  19167. #ifdef SQLITE_TEST
  19168. SQLITE_API int sqlite3_open_file_count = 0;
  19169. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  19170. #else
  19171. #define OpenCounter(X)
  19172. #endif
  19173. #endif /* !defined(_OS_COMMON_H_) */
  19174. /************** End of os_common.h *******************************************/
  19175. /************** Continuing where we left off in mutex_w32.c ******************/
  19176. /*
  19177. ** Include the header file for the Windows VFS.
  19178. */
  19179. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  19180. /************** Begin file os_win.h ******************************************/
  19181. /*
  19182. ** 2013 November 25
  19183. **
  19184. ** The author disclaims copyright to this source code. In place of
  19185. ** a legal notice, here is a blessing:
  19186. **
  19187. ** May you do good and not evil.
  19188. ** May you find forgiveness for yourself and forgive others.
  19189. ** May you share freely, never taking more than you give.
  19190. **
  19191. ******************************************************************************
  19192. **
  19193. ** This file contains code that is specific to Windows.
  19194. */
  19195. #ifndef _OS_WIN_H_
  19196. #define _OS_WIN_H_
  19197. /*
  19198. ** Include the primary Windows SDK header file.
  19199. */
  19200. #include "windows.h"
  19201. #ifdef __CYGWIN__
  19202. # include <sys/cygwin.h>
  19203. # include <errno.h> /* amalgamator: dontcache */
  19204. #endif
  19205. /*
  19206. ** Determine if we are dealing with Windows NT.
  19207. **
  19208. ** We ought to be able to determine if we are compiling for Windows 9x or
  19209. ** Windows NT using the _WIN32_WINNT macro as follows:
  19210. **
  19211. ** #if defined(_WIN32_WINNT)
  19212. ** # define SQLITE_OS_WINNT 1
  19213. ** #else
  19214. ** # define SQLITE_OS_WINNT 0
  19215. ** #endif
  19216. **
  19217. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  19218. ** it ought to, so the above test does not work. We'll just assume that
  19219. ** everything is Windows NT unless the programmer explicitly says otherwise
  19220. ** by setting SQLITE_OS_WINNT to 0.
  19221. */
  19222. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  19223. # define SQLITE_OS_WINNT 1
  19224. #endif
  19225. /*
  19226. ** Determine if we are dealing with Windows CE - which has a much reduced
  19227. ** API.
  19228. */
  19229. #if defined(_WIN32_WCE)
  19230. # define SQLITE_OS_WINCE 1
  19231. #else
  19232. # define SQLITE_OS_WINCE 0
  19233. #endif
  19234. /*
  19235. ** Determine if we are dealing with WinRT, which provides only a subset of
  19236. ** the full Win32 API.
  19237. */
  19238. #if !defined(SQLITE_OS_WINRT)
  19239. # define SQLITE_OS_WINRT 0
  19240. #endif
  19241. /*
  19242. ** For WinCE, some API function parameters do not appear to be declared as
  19243. ** volatile.
  19244. */
  19245. #if SQLITE_OS_WINCE
  19246. # define SQLITE_WIN32_VOLATILE
  19247. #else
  19248. # define SQLITE_WIN32_VOLATILE volatile
  19249. #endif
  19250. /*
  19251. ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
  19252. ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
  19253. */
  19254. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  19255. SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
  19256. # define SQLITE_OS_WIN_THREADS 1
  19257. #else
  19258. # define SQLITE_OS_WIN_THREADS 0
  19259. #endif
  19260. #endif /* _OS_WIN_H_ */
  19261. /************** End of os_win.h **********************************************/
  19262. /************** Continuing where we left off in mutex_w32.c ******************/
  19263. #endif
  19264. /*
  19265. ** The code in this file is only used if we are compiling multithreaded
  19266. ** on a Win32 system.
  19267. */
  19268. #ifdef SQLITE_MUTEX_W32
  19269. /*
  19270. ** Each recursive mutex is an instance of the following structure.
  19271. */
  19272. struct sqlite3_mutex {
  19273. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  19274. int id; /* Mutex type */
  19275. #ifdef SQLITE_DEBUG
  19276. volatile int nRef; /* Number of enterances */
  19277. volatile DWORD owner; /* Thread holding this mutex */
  19278. volatile int trace; /* True to trace changes */
  19279. #endif
  19280. };
  19281. /*
  19282. ** These are the initializer values used when declaring a "static" mutex
  19283. ** on Win32. It should be noted that all mutexes require initialization
  19284. ** on the Win32 platform.
  19285. */
  19286. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  19287. #ifdef SQLITE_DEBUG
  19288. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  19289. 0L, (DWORD)0, 0 }
  19290. #else
  19291. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  19292. #endif
  19293. #ifdef SQLITE_DEBUG
  19294. /*
  19295. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  19296. ** intended for use only inside assert() statements.
  19297. */
  19298. static int winMutexHeld(sqlite3_mutex *p){
  19299. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  19300. }
  19301. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  19302. return p->nRef==0 || p->owner!=tid;
  19303. }
  19304. static int winMutexNotheld(sqlite3_mutex *p){
  19305. DWORD tid = GetCurrentThreadId();
  19306. return winMutexNotheld2(p, tid);
  19307. }
  19308. #endif
  19309. /*
  19310. ** Initialize and deinitialize the mutex subsystem.
  19311. */
  19312. static sqlite3_mutex winMutex_staticMutexes[] = {
  19313. SQLITE3_MUTEX_INITIALIZER,
  19314. SQLITE3_MUTEX_INITIALIZER,
  19315. SQLITE3_MUTEX_INITIALIZER,
  19316. SQLITE3_MUTEX_INITIALIZER,
  19317. SQLITE3_MUTEX_INITIALIZER,
  19318. SQLITE3_MUTEX_INITIALIZER,
  19319. SQLITE3_MUTEX_INITIALIZER,
  19320. SQLITE3_MUTEX_INITIALIZER,
  19321. SQLITE3_MUTEX_INITIALIZER,
  19322. SQLITE3_MUTEX_INITIALIZER,
  19323. SQLITE3_MUTEX_INITIALIZER,
  19324. SQLITE3_MUTEX_INITIALIZER
  19325. };
  19326. static int winMutex_isInit = 0;
  19327. static int winMutex_isNt = -1; /* <0 means "need to query" */
  19328. /* As the winMutexInit() and winMutexEnd() functions are called as part
  19329. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  19330. ** "interlocked" magic used here is probably not strictly necessary.
  19331. */
  19332. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  19333. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
  19334. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  19335. static int winMutexInit(void){
  19336. /* The first to increment to 1 does actual initialization */
  19337. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  19338. int i;
  19339. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  19340. #if SQLITE_OS_WINRT
  19341. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  19342. #else
  19343. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  19344. #endif
  19345. }
  19346. winMutex_isInit = 1;
  19347. }else{
  19348. /* Another thread is (in the process of) initializing the static
  19349. ** mutexes */
  19350. while( !winMutex_isInit ){
  19351. sqlite3_win32_sleep(1);
  19352. }
  19353. }
  19354. return SQLITE_OK;
  19355. }
  19356. static int winMutexEnd(void){
  19357. /* The first to decrement to 0 does actual shutdown
  19358. ** (which should be the last to shutdown.) */
  19359. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  19360. if( winMutex_isInit==1 ){
  19361. int i;
  19362. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  19363. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  19364. }
  19365. winMutex_isInit = 0;
  19366. }
  19367. }
  19368. return SQLITE_OK;
  19369. }
  19370. /*
  19371. ** The sqlite3_mutex_alloc() routine allocates a new
  19372. ** mutex and returns a pointer to it. If it returns NULL
  19373. ** that means that a mutex could not be allocated. SQLite
  19374. ** will unwind its stack and return an error. The argument
  19375. ** to sqlite3_mutex_alloc() is one of these integer constants:
  19376. **
  19377. ** <ul>
  19378. ** <li> SQLITE_MUTEX_FAST
  19379. ** <li> SQLITE_MUTEX_RECURSIVE
  19380. ** <li> SQLITE_MUTEX_STATIC_MASTER
  19381. ** <li> SQLITE_MUTEX_STATIC_MEM
  19382. ** <li> SQLITE_MUTEX_STATIC_OPEN
  19383. ** <li> SQLITE_MUTEX_STATIC_PRNG
  19384. ** <li> SQLITE_MUTEX_STATIC_LRU
  19385. ** <li> SQLITE_MUTEX_STATIC_PMEM
  19386. ** <li> SQLITE_MUTEX_STATIC_APP1
  19387. ** <li> SQLITE_MUTEX_STATIC_APP2
  19388. ** <li> SQLITE_MUTEX_STATIC_APP3
  19389. ** <li> SQLITE_MUTEX_STATIC_VFS1
  19390. ** <li> SQLITE_MUTEX_STATIC_VFS2
  19391. ** <li> SQLITE_MUTEX_STATIC_VFS3
  19392. ** </ul>
  19393. **
  19394. ** The first two constants cause sqlite3_mutex_alloc() to create
  19395. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  19396. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  19397. ** The mutex implementation does not need to make a distinction
  19398. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  19399. ** not want to. But SQLite will only request a recursive mutex in
  19400. ** cases where it really needs one. If a faster non-recursive mutex
  19401. ** implementation is available on the host platform, the mutex subsystem
  19402. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  19403. **
  19404. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  19405. ** a pointer to a static preexisting mutex. Six static mutexes are
  19406. ** used by the current version of SQLite. Future versions of SQLite
  19407. ** may add additional static mutexes. Static mutexes are for internal
  19408. ** use by SQLite only. Applications that use SQLite mutexes should
  19409. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  19410. ** SQLITE_MUTEX_RECURSIVE.
  19411. **
  19412. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  19413. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  19414. ** returns a different mutex on every call. But for the static
  19415. ** mutex types, the same mutex is returned on every call that has
  19416. ** the same type number.
  19417. */
  19418. static sqlite3_mutex *winMutexAlloc(int iType){
  19419. sqlite3_mutex *p;
  19420. switch( iType ){
  19421. case SQLITE_MUTEX_FAST:
  19422. case SQLITE_MUTEX_RECURSIVE: {
  19423. p = sqlite3MallocZero( sizeof(*p) );
  19424. if( p ){
  19425. p->id = iType;
  19426. #ifdef SQLITE_DEBUG
  19427. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  19428. p->trace = 1;
  19429. #endif
  19430. #endif
  19431. #if SQLITE_OS_WINRT
  19432. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  19433. #else
  19434. InitializeCriticalSection(&p->mutex);
  19435. #endif
  19436. }
  19437. break;
  19438. }
  19439. default: {
  19440. #ifdef SQLITE_ENABLE_API_ARMOR
  19441. if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
  19442. (void)SQLITE_MISUSE_BKPT;
  19443. return 0;
  19444. }
  19445. #endif
  19446. p = &winMutex_staticMutexes[iType-2];
  19447. p->id = iType;
  19448. #ifdef SQLITE_DEBUG
  19449. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  19450. p->trace = 1;
  19451. #endif
  19452. #endif
  19453. break;
  19454. }
  19455. }
  19456. return p;
  19457. }
  19458. /*
  19459. ** This routine deallocates a previously
  19460. ** allocated mutex. SQLite is careful to deallocate every
  19461. ** mutex that it allocates.
  19462. */
  19463. static void winMutexFree(sqlite3_mutex *p){
  19464. assert( p );
  19465. assert( p->nRef==0 && p->owner==0 );
  19466. if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
  19467. DeleteCriticalSection(&p->mutex);
  19468. sqlite3_free(p);
  19469. }else{
  19470. #ifdef SQLITE_ENABLE_API_ARMOR
  19471. (void)SQLITE_MISUSE_BKPT;
  19472. #endif
  19473. }
  19474. }
  19475. /*
  19476. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  19477. ** to enter a mutex. If another thread is already within the mutex,
  19478. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  19479. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  19480. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  19481. ** be entered multiple times by the same thread. In such cases the,
  19482. ** mutex must be exited an equal number of times before another thread
  19483. ** can enter. If the same thread tries to enter any other kind of mutex
  19484. ** more than once, the behavior is undefined.
  19485. */
  19486. static void winMutexEnter(sqlite3_mutex *p){
  19487. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19488. DWORD tid = GetCurrentThreadId();
  19489. #endif
  19490. #ifdef SQLITE_DEBUG
  19491. assert( p );
  19492. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  19493. #else
  19494. assert( p );
  19495. #endif
  19496. assert( winMutex_isInit==1 );
  19497. EnterCriticalSection(&p->mutex);
  19498. #ifdef SQLITE_DEBUG
  19499. assert( p->nRef>0 || p->owner==0 );
  19500. p->owner = tid;
  19501. p->nRef++;
  19502. if( p->trace ){
  19503. OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  19504. tid, p, p->trace, p->nRef));
  19505. }
  19506. #endif
  19507. }
  19508. static int winMutexTry(sqlite3_mutex *p){
  19509. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19510. DWORD tid = GetCurrentThreadId();
  19511. #endif
  19512. int rc = SQLITE_BUSY;
  19513. assert( p );
  19514. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  19515. /*
  19516. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  19517. ** is used it is merely an optimization. So it is OK for it to always
  19518. ** fail.
  19519. **
  19520. ** The TryEnterCriticalSection() interface is only available on WinNT.
  19521. ** And some windows compilers complain if you try to use it without
  19522. ** first doing some #defines that prevent SQLite from building on Win98.
  19523. ** For that reason, we will omit this optimization for now. See
  19524. ** ticket #2685.
  19525. */
  19526. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  19527. assert( winMutex_isInit==1 );
  19528. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  19529. if( winMutex_isNt<0 ){
  19530. winMutex_isNt = sqlite3_win32_is_nt();
  19531. }
  19532. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  19533. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  19534. #ifdef SQLITE_DEBUG
  19535. p->owner = tid;
  19536. p->nRef++;
  19537. #endif
  19538. rc = SQLITE_OK;
  19539. }
  19540. #else
  19541. UNUSED_PARAMETER(p);
  19542. #endif
  19543. #ifdef SQLITE_DEBUG
  19544. if( p->trace ){
  19545. OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  19546. tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  19547. }
  19548. #endif
  19549. return rc;
  19550. }
  19551. /*
  19552. ** The sqlite3_mutex_leave() routine exits a mutex that was
  19553. ** previously entered by the same thread. The behavior
  19554. ** is undefined if the mutex is not currently entered or
  19555. ** is not currently allocated. SQLite will never do either.
  19556. */
  19557. static void winMutexLeave(sqlite3_mutex *p){
  19558. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  19559. DWORD tid = GetCurrentThreadId();
  19560. #endif
  19561. assert( p );
  19562. #ifdef SQLITE_DEBUG
  19563. assert( p->nRef>0 );
  19564. assert( p->owner==tid );
  19565. p->nRef--;
  19566. if( p->nRef==0 ) p->owner = 0;
  19567. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  19568. #endif
  19569. assert( winMutex_isInit==1 );
  19570. LeaveCriticalSection(&p->mutex);
  19571. #ifdef SQLITE_DEBUG
  19572. if( p->trace ){
  19573. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  19574. tid, p, p->trace, p->nRef));
  19575. }
  19576. #endif
  19577. }
  19578. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  19579. static const sqlite3_mutex_methods sMutex = {
  19580. winMutexInit,
  19581. winMutexEnd,
  19582. winMutexAlloc,
  19583. winMutexFree,
  19584. winMutexEnter,
  19585. winMutexTry,
  19586. winMutexLeave,
  19587. #ifdef SQLITE_DEBUG
  19588. winMutexHeld,
  19589. winMutexNotheld
  19590. #else
  19591. 0,
  19592. 0
  19593. #endif
  19594. };
  19595. return &sMutex;
  19596. }
  19597. #endif /* SQLITE_MUTEX_W32 */
  19598. /************** End of mutex_w32.c *******************************************/
  19599. /************** Begin file malloc.c ******************************************/
  19600. /*
  19601. ** 2001 September 15
  19602. **
  19603. ** The author disclaims copyright to this source code. In place of
  19604. ** a legal notice, here is a blessing:
  19605. **
  19606. ** May you do good and not evil.
  19607. ** May you find forgiveness for yourself and forgive others.
  19608. ** May you share freely, never taking more than you give.
  19609. **
  19610. *************************************************************************
  19611. **
  19612. ** Memory allocation functions used throughout sqlite.
  19613. */
  19614. /* #include "sqliteInt.h" */
  19615. /* #include <stdarg.h> */
  19616. /*
  19617. ** Attempt to release up to n bytes of non-essential memory currently
  19618. ** held by SQLite. An example of non-essential memory is memory used to
  19619. ** cache database pages that are not currently in use.
  19620. */
  19621. SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
  19622. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  19623. return sqlite3PcacheReleaseMemory(n);
  19624. #else
  19625. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  19626. ** is a no-op returning zero if SQLite is not compiled with
  19627. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  19628. UNUSED_PARAMETER(n);
  19629. return 0;
  19630. #endif
  19631. }
  19632. /*
  19633. ** An instance of the following object records the location of
  19634. ** each unused scratch buffer.
  19635. */
  19636. typedef struct ScratchFreeslot {
  19637. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  19638. } ScratchFreeslot;
  19639. /*
  19640. ** State information local to the memory allocation subsystem.
  19641. */
  19642. static SQLITE_WSD struct Mem0Global {
  19643. sqlite3_mutex *mutex; /* Mutex to serialize access */
  19644. /*
  19645. ** The alarm callback and its arguments. The mem0.mutex lock will
  19646. ** be held while the callback is running. Recursive calls into
  19647. ** the memory subsystem are allowed, but no new callbacks will be
  19648. ** issued.
  19649. */
  19650. sqlite3_int64 alarmThreshold;
  19651. void (*alarmCallback)(void*, sqlite3_int64,int);
  19652. void *alarmArg;
  19653. /*
  19654. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  19655. ** (so that a range test can be used to determine if an allocation
  19656. ** being freed came from pScratch) and a pointer to the list of
  19657. ** unused scratch allocations.
  19658. */
  19659. void *pScratchEnd;
  19660. ScratchFreeslot *pScratchFree;
  19661. u32 nScratchFree;
  19662. /*
  19663. ** True if heap is nearly "full" where "full" is defined by the
  19664. ** sqlite3_soft_heap_limit() setting.
  19665. */
  19666. int nearlyFull;
  19667. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  19668. #define mem0 GLOBAL(struct Mem0Global, mem0)
  19669. /*
  19670. ** Return the memory allocator mutex. sqlite3_status() needs it.
  19671. */
  19672. SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
  19673. return mem0.mutex;
  19674. }
  19675. /*
  19676. ** This routine runs when the memory allocator sees that the
  19677. ** total memory allocation is about to exceed the soft heap
  19678. ** limit.
  19679. */
  19680. static void softHeapLimitEnforcer(
  19681. void *NotUsed,
  19682. sqlite3_int64 NotUsed2,
  19683. int allocSize
  19684. ){
  19685. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  19686. sqlite3_release_memory(allocSize);
  19687. }
  19688. /*
  19689. ** Change the alarm callback
  19690. */
  19691. static int sqlite3MemoryAlarm(
  19692. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  19693. void *pArg,
  19694. sqlite3_int64 iThreshold
  19695. ){
  19696. sqlite3_int64 nUsed;
  19697. sqlite3_mutex_enter(mem0.mutex);
  19698. mem0.alarmCallback = xCallback;
  19699. mem0.alarmArg = pArg;
  19700. mem0.alarmThreshold = iThreshold;
  19701. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19702. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  19703. sqlite3_mutex_leave(mem0.mutex);
  19704. return SQLITE_OK;
  19705. }
  19706. #ifndef SQLITE_OMIT_DEPRECATED
  19707. /*
  19708. ** Deprecated external interface. Internal/core SQLite code
  19709. ** should call sqlite3MemoryAlarm.
  19710. */
  19711. SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
  19712. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  19713. void *pArg,
  19714. sqlite3_int64 iThreshold
  19715. ){
  19716. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  19717. }
  19718. #endif
  19719. /*
  19720. ** Set the soft heap-size limit for the library. Passing a zero or
  19721. ** negative value indicates no limit.
  19722. */
  19723. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
  19724. sqlite3_int64 priorLimit;
  19725. sqlite3_int64 excess;
  19726. #ifndef SQLITE_OMIT_AUTOINIT
  19727. int rc = sqlite3_initialize();
  19728. if( rc ) return -1;
  19729. #endif
  19730. sqlite3_mutex_enter(mem0.mutex);
  19731. priorLimit = mem0.alarmThreshold;
  19732. sqlite3_mutex_leave(mem0.mutex);
  19733. if( n<0 ) return priorLimit;
  19734. if( n>0 ){
  19735. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  19736. }else{
  19737. sqlite3MemoryAlarm(0, 0, 0);
  19738. }
  19739. excess = sqlite3_memory_used() - n;
  19740. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  19741. return priorLimit;
  19742. }
  19743. SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
  19744. if( n<0 ) n = 0;
  19745. sqlite3_soft_heap_limit64(n);
  19746. }
  19747. /*
  19748. ** Initialize the memory allocation subsystem.
  19749. */
  19750. SQLITE_PRIVATE int sqlite3MallocInit(void){
  19751. int rc;
  19752. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  19753. sqlite3MemSetDefault();
  19754. }
  19755. memset(&mem0, 0, sizeof(mem0));
  19756. if( sqlite3GlobalConfig.bCoreMutex ){
  19757. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  19758. }
  19759. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  19760. && sqlite3GlobalConfig.nScratch>0 ){
  19761. int i, n, sz;
  19762. ScratchFreeslot *pSlot;
  19763. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  19764. sqlite3GlobalConfig.szScratch = sz;
  19765. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  19766. n = sqlite3GlobalConfig.nScratch;
  19767. mem0.pScratchFree = pSlot;
  19768. mem0.nScratchFree = n;
  19769. for(i=0; i<n-1; i++){
  19770. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  19771. pSlot = pSlot->pNext;
  19772. }
  19773. pSlot->pNext = 0;
  19774. mem0.pScratchEnd = (void*)&pSlot[1];
  19775. }else{
  19776. mem0.pScratchEnd = 0;
  19777. sqlite3GlobalConfig.pScratch = 0;
  19778. sqlite3GlobalConfig.szScratch = 0;
  19779. sqlite3GlobalConfig.nScratch = 0;
  19780. }
  19781. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  19782. || sqlite3GlobalConfig.nPage<=0 ){
  19783. sqlite3GlobalConfig.pPage = 0;
  19784. sqlite3GlobalConfig.szPage = 0;
  19785. }
  19786. rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  19787. if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
  19788. return rc;
  19789. }
  19790. /*
  19791. ** Return true if the heap is currently under memory pressure - in other
  19792. ** words if the amount of heap used is close to the limit set by
  19793. ** sqlite3_soft_heap_limit().
  19794. */
  19795. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  19796. return mem0.nearlyFull;
  19797. }
  19798. /*
  19799. ** Deinitialize the memory allocation subsystem.
  19800. */
  19801. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  19802. if( sqlite3GlobalConfig.m.xShutdown ){
  19803. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  19804. }
  19805. memset(&mem0, 0, sizeof(mem0));
  19806. }
  19807. /*
  19808. ** Return the amount of memory currently checked out.
  19809. */
  19810. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
  19811. sqlite3_int64 res, mx;
  19812. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, 0);
  19813. return res;
  19814. }
  19815. /*
  19816. ** Return the maximum amount of memory that has ever been
  19817. ** checked out since either the beginning of this process
  19818. ** or since the most recent reset.
  19819. */
  19820. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
  19821. sqlite3_int64 res, mx;
  19822. sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
  19823. return mx;
  19824. }
  19825. /*
  19826. ** Trigger the alarm
  19827. */
  19828. static void sqlite3MallocAlarm(int nByte){
  19829. void (*xCallback)(void*,sqlite3_int64,int);
  19830. sqlite3_int64 nowUsed;
  19831. void *pArg;
  19832. if( mem0.alarmCallback==0 ) return;
  19833. xCallback = mem0.alarmCallback;
  19834. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19835. pArg = mem0.alarmArg;
  19836. mem0.alarmCallback = 0;
  19837. sqlite3_mutex_leave(mem0.mutex);
  19838. xCallback(pArg, nowUsed, nByte);
  19839. sqlite3_mutex_enter(mem0.mutex);
  19840. mem0.alarmCallback = xCallback;
  19841. mem0.alarmArg = pArg;
  19842. }
  19843. /*
  19844. ** Do a memory allocation with statistics and alarms. Assume the
  19845. ** lock is already held.
  19846. */
  19847. static int mallocWithAlarm(int n, void **pp){
  19848. int nFull;
  19849. void *p;
  19850. assert( sqlite3_mutex_held(mem0.mutex) );
  19851. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  19852. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  19853. if( mem0.alarmCallback!=0 ){
  19854. sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19855. if( nUsed >= mem0.alarmThreshold - nFull ){
  19856. mem0.nearlyFull = 1;
  19857. sqlite3MallocAlarm(nFull);
  19858. }else{
  19859. mem0.nearlyFull = 0;
  19860. }
  19861. }
  19862. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19863. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  19864. if( p==0 && mem0.alarmCallback ){
  19865. sqlite3MallocAlarm(nFull);
  19866. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19867. }
  19868. #endif
  19869. if( p ){
  19870. nFull = sqlite3MallocSize(p);
  19871. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
  19872. sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
  19873. }
  19874. *pp = p;
  19875. return nFull;
  19876. }
  19877. /*
  19878. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  19879. ** assumes the memory subsystem has already been initialized.
  19880. */
  19881. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  19882. void *p;
  19883. if( n==0 || n>=0x7fffff00 ){
  19884. /* A memory allocation of a number of bytes which is near the maximum
  19885. ** signed integer value might cause an integer overflow inside of the
  19886. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  19887. ** 255 bytes of overhead. SQLite itself will never use anything near
  19888. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  19889. p = 0;
  19890. }else if( sqlite3GlobalConfig.bMemstat ){
  19891. sqlite3_mutex_enter(mem0.mutex);
  19892. mallocWithAlarm((int)n, &p);
  19893. sqlite3_mutex_leave(mem0.mutex);
  19894. }else{
  19895. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  19896. }
  19897. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  19898. return p;
  19899. }
  19900. /*
  19901. ** This version of the memory allocation is for use by the application.
  19902. ** First make sure the memory subsystem is initialized, then do the
  19903. ** allocation.
  19904. */
  19905. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
  19906. #ifndef SQLITE_OMIT_AUTOINIT
  19907. if( sqlite3_initialize() ) return 0;
  19908. #endif
  19909. return n<=0 ? 0 : sqlite3Malloc(n);
  19910. }
  19911. SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
  19912. #ifndef SQLITE_OMIT_AUTOINIT
  19913. if( sqlite3_initialize() ) return 0;
  19914. #endif
  19915. return sqlite3Malloc(n);
  19916. }
  19917. /*
  19918. ** Each thread may only have a single outstanding allocation from
  19919. ** xScratchMalloc(). We verify this constraint in the single-threaded
  19920. ** case by setting scratchAllocOut to 1 when an allocation
  19921. ** is outstanding clearing it when the allocation is freed.
  19922. */
  19923. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19924. static int scratchAllocOut = 0;
  19925. #endif
  19926. /*
  19927. ** Allocate memory that is to be used and released right away.
  19928. ** This routine is similar to alloca() in that it is not intended
  19929. ** for situations where the memory might be held long-term. This
  19930. ** routine is intended to get memory to old large transient data
  19931. ** structures that would not normally fit on the stack of an
  19932. ** embedded processor.
  19933. */
  19934. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  19935. void *p;
  19936. assert( n>0 );
  19937. sqlite3_mutex_enter(mem0.mutex);
  19938. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  19939. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  19940. p = mem0.pScratchFree;
  19941. mem0.pScratchFree = mem0.pScratchFree->pNext;
  19942. mem0.nScratchFree--;
  19943. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
  19944. sqlite3_mutex_leave(mem0.mutex);
  19945. }else{
  19946. sqlite3_mutex_leave(mem0.mutex);
  19947. p = sqlite3Malloc(n);
  19948. if( sqlite3GlobalConfig.bMemstat && p ){
  19949. sqlite3_mutex_enter(mem0.mutex);
  19950. sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  19951. sqlite3_mutex_leave(mem0.mutex);
  19952. }
  19953. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  19954. }
  19955. assert( sqlite3_mutex_notheld(mem0.mutex) );
  19956. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19957. /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
  19958. ** buffers per thread.
  19959. **
  19960. ** This can only be checked in single-threaded mode.
  19961. */
  19962. assert( scratchAllocOut==0 );
  19963. if( p ) scratchAllocOut++;
  19964. #endif
  19965. return p;
  19966. }
  19967. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  19968. if( p ){
  19969. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19970. /* Verify that no more than two scratch allocation per thread
  19971. ** is outstanding at one time. (This is only checked in the
  19972. ** single-threaded case since checking in the multi-threaded case
  19973. ** would be much more complicated.) */
  19974. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  19975. scratchAllocOut--;
  19976. #endif
  19977. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  19978. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  19979. ScratchFreeslot *pSlot;
  19980. pSlot = (ScratchFreeslot*)p;
  19981. sqlite3_mutex_enter(mem0.mutex);
  19982. pSlot->pNext = mem0.pScratchFree;
  19983. mem0.pScratchFree = pSlot;
  19984. mem0.nScratchFree++;
  19985. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  19986. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
  19987. sqlite3_mutex_leave(mem0.mutex);
  19988. }else{
  19989. /* Release memory back to the heap */
  19990. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  19991. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
  19992. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19993. if( sqlite3GlobalConfig.bMemstat ){
  19994. int iSize = sqlite3MallocSize(p);
  19995. sqlite3_mutex_enter(mem0.mutex);
  19996. sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
  19997. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
  19998. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  19999. sqlite3GlobalConfig.m.xFree(p);
  20000. sqlite3_mutex_leave(mem0.mutex);
  20001. }else{
  20002. sqlite3GlobalConfig.m.xFree(p);
  20003. }
  20004. }
  20005. }
  20006. }
  20007. /*
  20008. ** TRUE if p is a lookaside memory allocation from db
  20009. */
  20010. #ifndef SQLITE_OMIT_LOOKASIDE
  20011. static int isLookaside(sqlite3 *db, void *p){
  20012. return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  20013. }
  20014. #else
  20015. #define isLookaside(A,B) 0
  20016. #endif
  20017. /*
  20018. ** Return the size of a memory allocation previously obtained from
  20019. ** sqlite3Malloc() or sqlite3_malloc().
  20020. */
  20021. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  20022. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20023. return sqlite3GlobalConfig.m.xSize(p);
  20024. }
  20025. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  20026. if( db==0 ){
  20027. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  20028. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20029. return sqlite3MallocSize(p);
  20030. }else{
  20031. assert( sqlite3_mutex_held(db->mutex) );
  20032. if( isLookaside(db, p) ){
  20033. return db->lookaside.sz;
  20034. }else{
  20035. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20036. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20037. return sqlite3GlobalConfig.m.xSize(p);
  20038. }
  20039. }
  20040. }
  20041. SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
  20042. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  20043. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20044. return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
  20045. }
  20046. /*
  20047. ** Free memory previously obtained from sqlite3Malloc().
  20048. */
  20049. SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
  20050. if( p==0 ) return; /* IMP: R-49053-54554 */
  20051. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  20052. assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
  20053. if( sqlite3GlobalConfig.bMemstat ){
  20054. sqlite3_mutex_enter(mem0.mutex);
  20055. sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
  20056. sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
  20057. sqlite3GlobalConfig.m.xFree(p);
  20058. sqlite3_mutex_leave(mem0.mutex);
  20059. }else{
  20060. sqlite3GlobalConfig.m.xFree(p);
  20061. }
  20062. }
  20063. /*
  20064. ** Add the size of memory allocation "p" to the count in
  20065. ** *db->pnBytesFreed.
  20066. */
  20067. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  20068. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  20069. }
  20070. /*
  20071. ** Free memory that might be associated with a particular database
  20072. ** connection.
  20073. */
  20074. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  20075. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  20076. if( p==0 ) return;
  20077. if( db ){
  20078. if( db->pnBytesFreed ){
  20079. measureAllocationSize(db, p);
  20080. return;
  20081. }
  20082. if( isLookaside(db, p) ){
  20083. LookasideSlot *pBuf = (LookasideSlot*)p;
  20084. #if SQLITE_DEBUG
  20085. /* Trash all content in the buffer being freed */
  20086. memset(p, 0xaa, db->lookaside.sz);
  20087. #endif
  20088. pBuf->pNext = db->lookaside.pFree;
  20089. db->lookaside.pFree = pBuf;
  20090. db->lookaside.nOut--;
  20091. return;
  20092. }
  20093. }
  20094. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20095. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20096. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  20097. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  20098. sqlite3_free(p);
  20099. }
  20100. /*
  20101. ** Change the size of an existing memory allocation
  20102. */
  20103. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  20104. int nOld, nNew, nDiff;
  20105. void *pNew;
  20106. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  20107. assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
  20108. if( pOld==0 ){
  20109. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  20110. }
  20111. if( nBytes==0 ){
  20112. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  20113. return 0;
  20114. }
  20115. if( nBytes>=0x7fffff00 ){
  20116. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  20117. return 0;
  20118. }
  20119. nOld = sqlite3MallocSize(pOld);
  20120. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  20121. ** argument to xRealloc is always a value returned by a prior call to
  20122. ** xRoundup. */
  20123. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  20124. if( nOld==nNew ){
  20125. pNew = pOld;
  20126. }else if( sqlite3GlobalConfig.bMemstat ){
  20127. sqlite3_mutex_enter(mem0.mutex);
  20128. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  20129. nDiff = nNew - nOld;
  20130. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  20131. mem0.alarmThreshold-nDiff ){
  20132. sqlite3MallocAlarm(nDiff);
  20133. }
  20134. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20135. if( pNew==0 && mem0.alarmCallback ){
  20136. sqlite3MallocAlarm((int)nBytes);
  20137. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20138. }
  20139. if( pNew ){
  20140. nNew = sqlite3MallocSize(pNew);
  20141. sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  20142. }
  20143. sqlite3_mutex_leave(mem0.mutex);
  20144. }else{
  20145. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  20146. }
  20147. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  20148. return pNew;
  20149. }
  20150. /*
  20151. ** The public interface to sqlite3Realloc. Make sure that the memory
  20152. ** subsystem is initialized prior to invoking sqliteRealloc.
  20153. */
  20154. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
  20155. #ifndef SQLITE_OMIT_AUTOINIT
  20156. if( sqlite3_initialize() ) return 0;
  20157. #endif
  20158. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  20159. return sqlite3Realloc(pOld, n);
  20160. }
  20161. SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  20162. #ifndef SQLITE_OMIT_AUTOINIT
  20163. if( sqlite3_initialize() ) return 0;
  20164. #endif
  20165. return sqlite3Realloc(pOld, n);
  20166. }
  20167. /*
  20168. ** Allocate and zero memory.
  20169. */
  20170. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  20171. void *p = sqlite3Malloc(n);
  20172. if( p ){
  20173. memset(p, 0, (size_t)n);
  20174. }
  20175. return p;
  20176. }
  20177. /*
  20178. ** Allocate and zero memory. If the allocation fails, make
  20179. ** the mallocFailed flag in the connection pointer.
  20180. */
  20181. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  20182. void *p = sqlite3DbMallocRaw(db, n);
  20183. if( p ){
  20184. memset(p, 0, (size_t)n);
  20185. }
  20186. return p;
  20187. }
  20188. /*
  20189. ** Allocate and zero memory. If the allocation fails, make
  20190. ** the mallocFailed flag in the connection pointer.
  20191. **
  20192. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  20193. ** failure on the same database connection) then always return 0.
  20194. ** Hence for a particular database connection, once malloc starts
  20195. ** failing, it fails consistently until mallocFailed is reset.
  20196. ** This is an important assumption. There are many places in the
  20197. ** code that do things like this:
  20198. **
  20199. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  20200. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  20201. ** if( b ) a[10] = 9;
  20202. **
  20203. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  20204. ** that all prior mallocs (ex: "a") worked too.
  20205. */
  20206. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  20207. void *p;
  20208. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  20209. assert( db==0 || db->pnBytesFreed==0 );
  20210. #ifndef SQLITE_OMIT_LOOKASIDE
  20211. if( db ){
  20212. LookasideSlot *pBuf;
  20213. if( db->mallocFailed ){
  20214. return 0;
  20215. }
  20216. if( db->lookaside.bEnabled ){
  20217. if( n>db->lookaside.sz ){
  20218. db->lookaside.anStat[1]++;
  20219. }else if( (pBuf = db->lookaside.pFree)==0 ){
  20220. db->lookaside.anStat[2]++;
  20221. }else{
  20222. db->lookaside.pFree = pBuf->pNext;
  20223. db->lookaside.nOut++;
  20224. db->lookaside.anStat[0]++;
  20225. if( db->lookaside.nOut>db->lookaside.mxOut ){
  20226. db->lookaside.mxOut = db->lookaside.nOut;
  20227. }
  20228. return (void*)pBuf;
  20229. }
  20230. }
  20231. }
  20232. #else
  20233. if( db && db->mallocFailed ){
  20234. return 0;
  20235. }
  20236. #endif
  20237. p = sqlite3Malloc(n);
  20238. if( !p && db ){
  20239. db->mallocFailed = 1;
  20240. }
  20241. sqlite3MemdebugSetType(p,
  20242. (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  20243. return p;
  20244. }
  20245. /*
  20246. ** Resize the block of memory pointed to by p to n bytes. If the
  20247. ** resize fails, set the mallocFailed flag in the connection object.
  20248. */
  20249. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  20250. void *pNew = 0;
  20251. assert( db!=0 );
  20252. assert( sqlite3_mutex_held(db->mutex) );
  20253. if( db->mallocFailed==0 ){
  20254. if( p==0 ){
  20255. return sqlite3DbMallocRaw(db, n);
  20256. }
  20257. if( isLookaside(db, p) ){
  20258. if( n<=db->lookaside.sz ){
  20259. return p;
  20260. }
  20261. pNew = sqlite3DbMallocRaw(db, n);
  20262. if( pNew ){
  20263. memcpy(pNew, p, db->lookaside.sz);
  20264. sqlite3DbFree(db, p);
  20265. }
  20266. }else{
  20267. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20268. assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  20269. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  20270. pNew = sqlite3_realloc64(p, n);
  20271. if( !pNew ){
  20272. db->mallocFailed = 1;
  20273. }
  20274. sqlite3MemdebugSetType(pNew,
  20275. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  20276. }
  20277. }
  20278. return pNew;
  20279. }
  20280. /*
  20281. ** Attempt to reallocate p. If the reallocation fails, then free p
  20282. ** and set the mallocFailed flag in the database connection.
  20283. */
  20284. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  20285. void *pNew;
  20286. pNew = sqlite3DbRealloc(db, p, n);
  20287. if( !pNew ){
  20288. sqlite3DbFree(db, p);
  20289. }
  20290. return pNew;
  20291. }
  20292. /*
  20293. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  20294. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  20295. ** is because when memory debugging is turned on, these two functions are
  20296. ** called via macros that record the current file and line number in the
  20297. ** ThreadData structure.
  20298. */
  20299. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  20300. char *zNew;
  20301. size_t n;
  20302. if( z==0 ){
  20303. return 0;
  20304. }
  20305. n = sqlite3Strlen30(z) + 1;
  20306. assert( (n&0x7fffffff)==n );
  20307. zNew = sqlite3DbMallocRaw(db, (int)n);
  20308. if( zNew ){
  20309. memcpy(zNew, z, n);
  20310. }
  20311. return zNew;
  20312. }
  20313. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  20314. char *zNew;
  20315. if( z==0 ){
  20316. return 0;
  20317. }
  20318. assert( (n&0x7fffffff)==n );
  20319. zNew = sqlite3DbMallocRaw(db, n+1);
  20320. if( zNew ){
  20321. memcpy(zNew, z, (size_t)n);
  20322. zNew[n] = 0;
  20323. }
  20324. return zNew;
  20325. }
  20326. /*
  20327. ** Free any prior content in *pz and replace it with a copy of zNew.
  20328. */
  20329. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
  20330. sqlite3DbFree(db, *pz);
  20331. *pz = sqlite3DbStrDup(db, zNew);
  20332. }
  20333. /*
  20334. ** Take actions at the end of an API call to indicate an OOM error
  20335. */
  20336. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  20337. db->mallocFailed = 0;
  20338. sqlite3Error(db, SQLITE_NOMEM);
  20339. return SQLITE_NOMEM;
  20340. }
  20341. /*
  20342. ** This function must be called before exiting any API function (i.e.
  20343. ** returning control to the user) that has called sqlite3_malloc or
  20344. ** sqlite3_realloc.
  20345. **
  20346. ** The returned value is normally a copy of the second argument to this
  20347. ** function. However, if a malloc() failure has occurred since the previous
  20348. ** invocation SQLITE_NOMEM is returned instead.
  20349. **
  20350. ** If an OOM as occurred, then the connection error-code (the value
  20351. ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
  20352. */
  20353. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  20354. /* If the db handle must hold the connection handle mutex here.
  20355. ** Otherwise the read (and possible write) of db->mallocFailed
  20356. ** is unsafe, as is the call to sqlite3Error().
  20357. */
  20358. assert( db!=0 );
  20359. assert( sqlite3_mutex_held(db->mutex) );
  20360. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  20361. return apiOomError(db);
  20362. }
  20363. return rc & db->errMask;
  20364. }
  20365. /************** End of malloc.c **********************************************/
  20366. /************** Begin file printf.c ******************************************/
  20367. /*
  20368. ** The "printf" code that follows dates from the 1980's. It is in
  20369. ** the public domain.
  20370. **
  20371. **************************************************************************
  20372. **
  20373. ** This file contains code for a set of "printf"-like routines. These
  20374. ** routines format strings much like the printf() from the standard C
  20375. ** library, though the implementation here has enhancements to support
  20376. ** SQLite.
  20377. */
  20378. /* #include "sqliteInt.h" */
  20379. /*
  20380. ** Conversion types fall into various categories as defined by the
  20381. ** following enumeration.
  20382. */
  20383. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  20384. #define etFLOAT 2 /* Floating point. %f */
  20385. #define etEXP 3 /* Exponentional notation. %e and %E */
  20386. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  20387. #define etSIZE 5 /* Return number of characters processed so far. %n */
  20388. #define etSTRING 6 /* Strings. %s */
  20389. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  20390. #define etPERCENT 8 /* Percent symbol. %% */
  20391. #define etCHARX 9 /* Characters. %c */
  20392. /* The rest are extensions, not normally found in printf() */
  20393. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  20394. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  20395. NULL pointers replaced by SQL NULL. %Q */
  20396. #define etTOKEN 12 /* a pointer to a Token structure */
  20397. #define etSRCLIST 13 /* a pointer to a SrcList */
  20398. #define etPOINTER 14 /* The %p conversion */
  20399. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  20400. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  20401. #define etINVALID 0 /* Any unrecognized conversion type */
  20402. /*
  20403. ** An "etByte" is an 8-bit unsigned value.
  20404. */
  20405. typedef unsigned char etByte;
  20406. /*
  20407. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  20408. ** by an instance of the following structure
  20409. */
  20410. typedef struct et_info { /* Information about each format field */
  20411. char fmttype; /* The format field code letter */
  20412. etByte base; /* The base for radix conversion */
  20413. etByte flags; /* One or more of FLAG_ constants below */
  20414. etByte type; /* Conversion paradigm */
  20415. etByte charset; /* Offset into aDigits[] of the digits string */
  20416. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  20417. } et_info;
  20418. /*
  20419. ** Allowed values for et_info.flags
  20420. */
  20421. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  20422. #define FLAG_INTERN 2 /* True if for internal use only */
  20423. #define FLAG_STRING 4 /* Allow infinity precision */
  20424. /*
  20425. ** The following table is searched linearly, so it is good to put the
  20426. ** most frequently used conversion types first.
  20427. */
  20428. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  20429. static const char aPrefix[] = "-x0\000X0";
  20430. static const et_info fmtinfo[] = {
  20431. { 'd', 10, 1, etRADIX, 0, 0 },
  20432. { 's', 0, 4, etSTRING, 0, 0 },
  20433. { 'g', 0, 1, etGENERIC, 30, 0 },
  20434. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  20435. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  20436. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  20437. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  20438. { 'c', 0, 0, etCHARX, 0, 0 },
  20439. { 'o', 8, 0, etRADIX, 0, 2 },
  20440. { 'u', 10, 0, etRADIX, 0, 0 },
  20441. { 'x', 16, 0, etRADIX, 16, 1 },
  20442. { 'X', 16, 0, etRADIX, 0, 4 },
  20443. #ifndef SQLITE_OMIT_FLOATING_POINT
  20444. { 'f', 0, 1, etFLOAT, 0, 0 },
  20445. { 'e', 0, 1, etEXP, 30, 0 },
  20446. { 'E', 0, 1, etEXP, 14, 0 },
  20447. { 'G', 0, 1, etGENERIC, 14, 0 },
  20448. #endif
  20449. { 'i', 10, 1, etRADIX, 0, 0 },
  20450. { 'n', 0, 0, etSIZE, 0, 0 },
  20451. { '%', 0, 0, etPERCENT, 0, 0 },
  20452. { 'p', 16, 0, etPOINTER, 0, 1 },
  20453. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  20454. ** use only */
  20455. { 'T', 0, 2, etTOKEN, 0, 0 },
  20456. { 'S', 0, 2, etSRCLIST, 0, 0 },
  20457. { 'r', 10, 3, etORDINAL, 0, 0 },
  20458. };
  20459. /*
  20460. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  20461. ** conversions will work.
  20462. */
  20463. #ifndef SQLITE_OMIT_FLOATING_POINT
  20464. /*
  20465. ** "*val" is a double such that 0.1 <= *val < 10.0
  20466. ** Return the ascii code for the leading digit of *val, then
  20467. ** multiply "*val" by 10.0 to renormalize.
  20468. **
  20469. ** Example:
  20470. ** input: *val = 3.14159
  20471. ** output: *val = 1.4159 function return = '3'
  20472. **
  20473. ** The counter *cnt is incremented each time. After counter exceeds
  20474. ** 16 (the number of significant digits in a 64-bit float) '0' is
  20475. ** always returned.
  20476. */
  20477. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  20478. int digit;
  20479. LONGDOUBLE_TYPE d;
  20480. if( (*cnt)<=0 ) return '0';
  20481. (*cnt)--;
  20482. digit = (int)*val;
  20483. d = digit;
  20484. digit += '0';
  20485. *val = (*val - d)*10.0;
  20486. return (char)digit;
  20487. }
  20488. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20489. /*
  20490. ** Set the StrAccum object to an error mode.
  20491. */
  20492. static void setStrAccumError(StrAccum *p, u8 eError){
  20493. assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
  20494. p->accError = eError;
  20495. p->nAlloc = 0;
  20496. }
  20497. /*
  20498. ** Extra argument values from a PrintfArguments object
  20499. */
  20500. static sqlite3_int64 getIntArg(PrintfArguments *p){
  20501. if( p->nArg<=p->nUsed ) return 0;
  20502. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  20503. }
  20504. static double getDoubleArg(PrintfArguments *p){
  20505. if( p->nArg<=p->nUsed ) return 0.0;
  20506. return sqlite3_value_double(p->apArg[p->nUsed++]);
  20507. }
  20508. static char *getTextArg(PrintfArguments *p){
  20509. if( p->nArg<=p->nUsed ) return 0;
  20510. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  20511. }
  20512. /*
  20513. ** On machines with a small stack size, you can redefine the
  20514. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  20515. */
  20516. #ifndef SQLITE_PRINT_BUF_SIZE
  20517. # define SQLITE_PRINT_BUF_SIZE 70
  20518. #endif
  20519. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  20520. /*
  20521. ** Render a string given by "fmt" into the StrAccum object.
  20522. */
  20523. SQLITE_PRIVATE void sqlite3VXPrintf(
  20524. StrAccum *pAccum, /* Accumulate results here */
  20525. u32 bFlags, /* SQLITE_PRINTF_* flags */
  20526. const char *fmt, /* Format string */
  20527. va_list ap /* arguments */
  20528. ){
  20529. int c; /* Next character in the format string */
  20530. char *bufpt; /* Pointer to the conversion buffer */
  20531. int precision; /* Precision of the current field */
  20532. int length; /* Length of the field */
  20533. int idx; /* A general purpose loop counter */
  20534. int width; /* Width of the current field */
  20535. etByte flag_leftjustify; /* True if "-" flag is present */
  20536. etByte flag_plussign; /* True if "+" flag is present */
  20537. etByte flag_blanksign; /* True if " " flag is present */
  20538. etByte flag_alternateform; /* True if "#" flag is present */
  20539. etByte flag_altform2; /* True if "!" flag is present */
  20540. etByte flag_zeropad; /* True if field width constant starts with zero */
  20541. etByte flag_long; /* True if "l" flag is present */
  20542. etByte flag_longlong; /* True if the "ll" flag is present */
  20543. etByte done; /* Loop termination flag */
  20544. etByte xtype = 0; /* Conversion paradigm */
  20545. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  20546. u8 useIntern; /* Ok to use internal conversions (ex: %T) */
  20547. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  20548. sqlite_uint64 longvalue; /* Value for integer types */
  20549. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  20550. const et_info *infop; /* Pointer to the appropriate info structure */
  20551. char *zOut; /* Rendering buffer */
  20552. int nOut; /* Size of the rendering buffer */
  20553. char *zExtra = 0; /* Malloced memory used by some conversion */
  20554. #ifndef SQLITE_OMIT_FLOATING_POINT
  20555. int exp, e2; /* exponent of real numbers */
  20556. int nsd; /* Number of significant digits returned */
  20557. double rounder; /* Used for rounding floating point values */
  20558. etByte flag_dp; /* True if decimal point should be shown */
  20559. etByte flag_rtz; /* True if trailing zeros should be removed */
  20560. #endif
  20561. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  20562. char buf[etBUFSIZE]; /* Conversion buffer */
  20563. bufpt = 0;
  20564. if( bFlags ){
  20565. if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
  20566. pArgList = va_arg(ap, PrintfArguments*);
  20567. }
  20568. useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
  20569. }else{
  20570. bArgList = useIntern = 0;
  20571. }
  20572. for(; (c=(*fmt))!=0; ++fmt){
  20573. if( c!='%' ){
  20574. bufpt = (char *)fmt;
  20575. #if HAVE_STRCHRNUL
  20576. fmt = strchrnul(fmt, '%');
  20577. #else
  20578. do{ fmt++; }while( *fmt && *fmt != '%' );
  20579. #endif
  20580. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  20581. if( *fmt==0 ) break;
  20582. }
  20583. if( (c=(*++fmt))==0 ){
  20584. sqlite3StrAccumAppend(pAccum, "%", 1);
  20585. break;
  20586. }
  20587. /* Find out what flags are present */
  20588. flag_leftjustify = flag_plussign = flag_blanksign =
  20589. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  20590. done = 0;
  20591. do{
  20592. switch( c ){
  20593. case '-': flag_leftjustify = 1; break;
  20594. case '+': flag_plussign = 1; break;
  20595. case ' ': flag_blanksign = 1; break;
  20596. case '#': flag_alternateform = 1; break;
  20597. case '!': flag_altform2 = 1; break;
  20598. case '0': flag_zeropad = 1; break;
  20599. default: done = 1; break;
  20600. }
  20601. }while( !done && (c=(*++fmt))!=0 );
  20602. /* Get the field width */
  20603. if( c=='*' ){
  20604. if( bArgList ){
  20605. width = (int)getIntArg(pArgList);
  20606. }else{
  20607. width = va_arg(ap,int);
  20608. }
  20609. if( width<0 ){
  20610. flag_leftjustify = 1;
  20611. width = width >= -2147483647 ? -width : 0;
  20612. }
  20613. c = *++fmt;
  20614. }else{
  20615. unsigned wx = 0;
  20616. while( c>='0' && c<='9' ){
  20617. wx = wx*10 + c - '0';
  20618. c = *++fmt;
  20619. }
  20620. testcase( wx>0x7fffffff );
  20621. width = wx & 0x7fffffff;
  20622. }
  20623. /* Get the precision */
  20624. if( c=='.' ){
  20625. c = *++fmt;
  20626. if( c=='*' ){
  20627. if( bArgList ){
  20628. precision = (int)getIntArg(pArgList);
  20629. }else{
  20630. precision = va_arg(ap,int);
  20631. }
  20632. c = *++fmt;
  20633. if( precision<0 ){
  20634. precision = precision >= -2147483647 ? -precision : -1;
  20635. }
  20636. }else{
  20637. unsigned px = 0;
  20638. while( c>='0' && c<='9' ){
  20639. px = px*10 + c - '0';
  20640. c = *++fmt;
  20641. }
  20642. testcase( px>0x7fffffff );
  20643. precision = px & 0x7fffffff;
  20644. }
  20645. }else{
  20646. precision = -1;
  20647. }
  20648. /* Get the conversion type modifier */
  20649. if( c=='l' ){
  20650. flag_long = 1;
  20651. c = *++fmt;
  20652. if( c=='l' ){
  20653. flag_longlong = 1;
  20654. c = *++fmt;
  20655. }else{
  20656. flag_longlong = 0;
  20657. }
  20658. }else{
  20659. flag_long = flag_longlong = 0;
  20660. }
  20661. /* Fetch the info entry for the field */
  20662. infop = &fmtinfo[0];
  20663. xtype = etINVALID;
  20664. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  20665. if( c==fmtinfo[idx].fmttype ){
  20666. infop = &fmtinfo[idx];
  20667. if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
  20668. xtype = infop->type;
  20669. }else{
  20670. return;
  20671. }
  20672. break;
  20673. }
  20674. }
  20675. /*
  20676. ** At this point, variables are initialized as follows:
  20677. **
  20678. ** flag_alternateform TRUE if a '#' is present.
  20679. ** flag_altform2 TRUE if a '!' is present.
  20680. ** flag_plussign TRUE if a '+' is present.
  20681. ** flag_leftjustify TRUE if a '-' is present or if the
  20682. ** field width was negative.
  20683. ** flag_zeropad TRUE if the width began with 0.
  20684. ** flag_long TRUE if the letter 'l' (ell) prefixed
  20685. ** the conversion character.
  20686. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  20687. ** the conversion character.
  20688. ** flag_blanksign TRUE if a ' ' is present.
  20689. ** width The specified field width. This is
  20690. ** always non-negative. Zero is the default.
  20691. ** precision The specified precision. The default
  20692. ** is -1.
  20693. ** xtype The class of the conversion.
  20694. ** infop Pointer to the appropriate info struct.
  20695. */
  20696. switch( xtype ){
  20697. case etPOINTER:
  20698. flag_longlong = sizeof(char*)==sizeof(i64);
  20699. flag_long = sizeof(char*)==sizeof(long int);
  20700. /* Fall through into the next case */
  20701. case etORDINAL:
  20702. case etRADIX:
  20703. if( infop->flags & FLAG_SIGNED ){
  20704. i64 v;
  20705. if( bArgList ){
  20706. v = getIntArg(pArgList);
  20707. }else if( flag_longlong ){
  20708. v = va_arg(ap,i64);
  20709. }else if( flag_long ){
  20710. v = va_arg(ap,long int);
  20711. }else{
  20712. v = va_arg(ap,int);
  20713. }
  20714. if( v<0 ){
  20715. if( v==SMALLEST_INT64 ){
  20716. longvalue = ((u64)1)<<63;
  20717. }else{
  20718. longvalue = -v;
  20719. }
  20720. prefix = '-';
  20721. }else{
  20722. longvalue = v;
  20723. if( flag_plussign ) prefix = '+';
  20724. else if( flag_blanksign ) prefix = ' ';
  20725. else prefix = 0;
  20726. }
  20727. }else{
  20728. if( bArgList ){
  20729. longvalue = (u64)getIntArg(pArgList);
  20730. }else if( flag_longlong ){
  20731. longvalue = va_arg(ap,u64);
  20732. }else if( flag_long ){
  20733. longvalue = va_arg(ap,unsigned long int);
  20734. }else{
  20735. longvalue = va_arg(ap,unsigned int);
  20736. }
  20737. prefix = 0;
  20738. }
  20739. if( longvalue==0 ) flag_alternateform = 0;
  20740. if( flag_zeropad && precision<width-(prefix!=0) ){
  20741. precision = width-(prefix!=0);
  20742. }
  20743. if( precision<etBUFSIZE-10 ){
  20744. nOut = etBUFSIZE;
  20745. zOut = buf;
  20746. }else{
  20747. nOut = precision + 10;
  20748. zOut = zExtra = sqlite3Malloc( nOut );
  20749. if( zOut==0 ){
  20750. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20751. return;
  20752. }
  20753. }
  20754. bufpt = &zOut[nOut-1];
  20755. if( xtype==etORDINAL ){
  20756. static const char zOrd[] = "thstndrd";
  20757. int x = (int)(longvalue % 10);
  20758. if( x>=4 || (longvalue/10)%10==1 ){
  20759. x = 0;
  20760. }
  20761. *(--bufpt) = zOrd[x*2+1];
  20762. *(--bufpt) = zOrd[x*2];
  20763. }
  20764. {
  20765. const char *cset = &aDigits[infop->charset];
  20766. u8 base = infop->base;
  20767. do{ /* Convert to ascii */
  20768. *(--bufpt) = cset[longvalue%base];
  20769. longvalue = longvalue/base;
  20770. }while( longvalue>0 );
  20771. }
  20772. length = (int)(&zOut[nOut-1]-bufpt);
  20773. for(idx=precision-length; idx>0; idx--){
  20774. *(--bufpt) = '0'; /* Zero pad */
  20775. }
  20776. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  20777. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  20778. const char *pre;
  20779. char x;
  20780. pre = &aPrefix[infop->prefix];
  20781. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  20782. }
  20783. length = (int)(&zOut[nOut-1]-bufpt);
  20784. break;
  20785. case etFLOAT:
  20786. case etEXP:
  20787. case etGENERIC:
  20788. if( bArgList ){
  20789. realvalue = getDoubleArg(pArgList);
  20790. }else{
  20791. realvalue = va_arg(ap,double);
  20792. }
  20793. #ifdef SQLITE_OMIT_FLOATING_POINT
  20794. length = 0;
  20795. #else
  20796. if( precision<0 ) precision = 6; /* Set default precision */
  20797. if( realvalue<0.0 ){
  20798. realvalue = -realvalue;
  20799. prefix = '-';
  20800. }else{
  20801. if( flag_plussign ) prefix = '+';
  20802. else if( flag_blanksign ) prefix = ' ';
  20803. else prefix = 0;
  20804. }
  20805. if( xtype==etGENERIC && precision>0 ) precision--;
  20806. testcase( precision>0xfff );
  20807. for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  20808. if( xtype==etFLOAT ) realvalue += rounder;
  20809. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  20810. exp = 0;
  20811. if( sqlite3IsNaN((double)realvalue) ){
  20812. bufpt = "NaN";
  20813. length = 3;
  20814. break;
  20815. }
  20816. if( realvalue>0.0 ){
  20817. LONGDOUBLE_TYPE scale = 1.0;
  20818. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  20819. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  20820. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  20821. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  20822. realvalue /= scale;
  20823. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  20824. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  20825. if( exp>350 ){
  20826. if( prefix=='-' ){
  20827. bufpt = "-Inf";
  20828. }else if( prefix=='+' ){
  20829. bufpt = "+Inf";
  20830. }else{
  20831. bufpt = "Inf";
  20832. }
  20833. length = sqlite3Strlen30(bufpt);
  20834. break;
  20835. }
  20836. }
  20837. bufpt = buf;
  20838. /*
  20839. ** If the field type is etGENERIC, then convert to either etEXP
  20840. ** or etFLOAT, as appropriate.
  20841. */
  20842. if( xtype!=etFLOAT ){
  20843. realvalue += rounder;
  20844. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  20845. }
  20846. if( xtype==etGENERIC ){
  20847. flag_rtz = !flag_alternateform;
  20848. if( exp<-4 || exp>precision ){
  20849. xtype = etEXP;
  20850. }else{
  20851. precision = precision - exp;
  20852. xtype = etFLOAT;
  20853. }
  20854. }else{
  20855. flag_rtz = flag_altform2;
  20856. }
  20857. if( xtype==etEXP ){
  20858. e2 = 0;
  20859. }else{
  20860. e2 = exp;
  20861. }
  20862. if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
  20863. bufpt = zExtra
  20864. = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
  20865. if( bufpt==0 ){
  20866. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20867. return;
  20868. }
  20869. }
  20870. zOut = bufpt;
  20871. nsd = 16 + flag_altform2*10;
  20872. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  20873. /* The sign in front of the number */
  20874. if( prefix ){
  20875. *(bufpt++) = prefix;
  20876. }
  20877. /* Digits prior to the decimal point */
  20878. if( e2<0 ){
  20879. *(bufpt++) = '0';
  20880. }else{
  20881. for(; e2>=0; e2--){
  20882. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20883. }
  20884. }
  20885. /* The decimal point */
  20886. if( flag_dp ){
  20887. *(bufpt++) = '.';
  20888. }
  20889. /* "0" digits after the decimal point but before the first
  20890. ** significant digit of the number */
  20891. for(e2++; e2<0; precision--, e2++){
  20892. assert( precision>0 );
  20893. *(bufpt++) = '0';
  20894. }
  20895. /* Significant digits after the decimal point */
  20896. while( (precision--)>0 ){
  20897. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20898. }
  20899. /* Remove trailing zeros and the "." if no digits follow the "." */
  20900. if( flag_rtz && flag_dp ){
  20901. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  20902. assert( bufpt>zOut );
  20903. if( bufpt[-1]=='.' ){
  20904. if( flag_altform2 ){
  20905. *(bufpt++) = '0';
  20906. }else{
  20907. *(--bufpt) = 0;
  20908. }
  20909. }
  20910. }
  20911. /* Add the "eNNN" suffix */
  20912. if( xtype==etEXP ){
  20913. *(bufpt++) = aDigits[infop->charset];
  20914. if( exp<0 ){
  20915. *(bufpt++) = '-'; exp = -exp;
  20916. }else{
  20917. *(bufpt++) = '+';
  20918. }
  20919. if( exp>=100 ){
  20920. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  20921. exp %= 100;
  20922. }
  20923. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  20924. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  20925. }
  20926. *bufpt = 0;
  20927. /* The converted number is in buf[] and zero terminated. Output it.
  20928. ** Note that the number is in the usual order, not reversed as with
  20929. ** integer conversions. */
  20930. length = (int)(bufpt-zOut);
  20931. bufpt = zOut;
  20932. /* Special case: Add leading zeros if the flag_zeropad flag is
  20933. ** set and we are not left justified */
  20934. if( flag_zeropad && !flag_leftjustify && length < width){
  20935. int i;
  20936. int nPad = width - length;
  20937. for(i=width; i>=nPad; i--){
  20938. bufpt[i] = bufpt[i-nPad];
  20939. }
  20940. i = prefix!=0;
  20941. while( nPad-- ) bufpt[i++] = '0';
  20942. length = width;
  20943. }
  20944. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  20945. break;
  20946. case etSIZE:
  20947. if( !bArgList ){
  20948. *(va_arg(ap,int*)) = pAccum->nChar;
  20949. }
  20950. length = width = 0;
  20951. break;
  20952. case etPERCENT:
  20953. buf[0] = '%';
  20954. bufpt = buf;
  20955. length = 1;
  20956. break;
  20957. case etCHARX:
  20958. if( bArgList ){
  20959. bufpt = getTextArg(pArgList);
  20960. c = bufpt ? bufpt[0] : 0;
  20961. }else{
  20962. c = va_arg(ap,int);
  20963. }
  20964. if( precision>1 ){
  20965. width -= precision-1;
  20966. if( width>1 && !flag_leftjustify ){
  20967. sqlite3AppendChar(pAccum, width-1, ' ');
  20968. width = 0;
  20969. }
  20970. sqlite3AppendChar(pAccum, precision-1, c);
  20971. }
  20972. length = 1;
  20973. buf[0] = c;
  20974. bufpt = buf;
  20975. break;
  20976. case etSTRING:
  20977. case etDYNSTRING:
  20978. if( bArgList ){
  20979. bufpt = getTextArg(pArgList);
  20980. }else{
  20981. bufpt = va_arg(ap,char*);
  20982. }
  20983. if( bufpt==0 ){
  20984. bufpt = "";
  20985. }else if( xtype==etDYNSTRING && !bArgList ){
  20986. zExtra = bufpt;
  20987. }
  20988. if( precision>=0 ){
  20989. for(length=0; length<precision && bufpt[length]; length++){}
  20990. }else{
  20991. length = sqlite3Strlen30(bufpt);
  20992. }
  20993. break;
  20994. case etSQLESCAPE:
  20995. case etSQLESCAPE2:
  20996. case etSQLESCAPE3: {
  20997. int i, j, k, n, isnull;
  20998. int needQuote;
  20999. char ch;
  21000. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  21001. char *escarg;
  21002. if( bArgList ){
  21003. escarg = getTextArg(pArgList);
  21004. }else{
  21005. escarg = va_arg(ap,char*);
  21006. }
  21007. isnull = escarg==0;
  21008. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  21009. k = precision;
  21010. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  21011. if( ch==q ) n++;
  21012. }
  21013. needQuote = !isnull && xtype==etSQLESCAPE2;
  21014. n += i + 1 + needQuote*2;
  21015. if( n>etBUFSIZE ){
  21016. bufpt = zExtra = sqlite3Malloc( n );
  21017. if( bufpt==0 ){
  21018. setStrAccumError(pAccum, STRACCUM_NOMEM);
  21019. return;
  21020. }
  21021. }else{
  21022. bufpt = buf;
  21023. }
  21024. j = 0;
  21025. if( needQuote ) bufpt[j++] = q;
  21026. k = i;
  21027. for(i=0; i<k; i++){
  21028. bufpt[j++] = ch = escarg[i];
  21029. if( ch==q ) bufpt[j++] = ch;
  21030. }
  21031. if( needQuote ) bufpt[j++] = q;
  21032. bufpt[j] = 0;
  21033. length = j;
  21034. /* The precision in %q and %Q means how many input characters to
  21035. ** consume, not the length of the output...
  21036. ** if( precision>=0 && precision<length ) length = precision; */
  21037. break;
  21038. }
  21039. case etTOKEN: {
  21040. Token *pToken = va_arg(ap, Token*);
  21041. assert( bArgList==0 );
  21042. if( pToken && pToken->n ){
  21043. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  21044. }
  21045. length = width = 0;
  21046. break;
  21047. }
  21048. case etSRCLIST: {
  21049. SrcList *pSrc = va_arg(ap, SrcList*);
  21050. int k = va_arg(ap, int);
  21051. struct SrcList_item *pItem = &pSrc->a[k];
  21052. assert( bArgList==0 );
  21053. assert( k>=0 && k<pSrc->nSrc );
  21054. if( pItem->zDatabase ){
  21055. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  21056. sqlite3StrAccumAppend(pAccum, ".", 1);
  21057. }
  21058. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  21059. length = width = 0;
  21060. break;
  21061. }
  21062. default: {
  21063. assert( xtype==etINVALID );
  21064. return;
  21065. }
  21066. }/* End switch over the format type */
  21067. /*
  21068. ** The text of the conversion is pointed to by "bufpt" and is
  21069. ** "length" characters long. The field width is "width". Do
  21070. ** the output.
  21071. */
  21072. width -= length;
  21073. if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  21074. sqlite3StrAccumAppend(pAccum, bufpt, length);
  21075. if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  21076. if( zExtra ){
  21077. sqlite3_free(zExtra);
  21078. zExtra = 0;
  21079. }
  21080. }/* End for loop over the format string */
  21081. } /* End of function */
  21082. /*
  21083. ** Enlarge the memory allocation on a StrAccum object so that it is
  21084. ** able to accept at least N more bytes of text.
  21085. **
  21086. ** Return the number of bytes of text that StrAccum is able to accept
  21087. ** after the attempted enlargement. The value returned might be zero.
  21088. */
  21089. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  21090. char *zNew;
  21091. assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
  21092. if( p->accError ){
  21093. testcase(p->accError==STRACCUM_TOOBIG);
  21094. testcase(p->accError==STRACCUM_NOMEM);
  21095. return 0;
  21096. }
  21097. if( p->mxAlloc==0 ){
  21098. N = p->nAlloc - p->nChar - 1;
  21099. setStrAccumError(p, STRACCUM_TOOBIG);
  21100. return N;
  21101. }else{
  21102. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  21103. i64 szNew = p->nChar;
  21104. szNew += N + 1;
  21105. if( szNew+p->nChar<=p->mxAlloc ){
  21106. /* Force exponential buffer size growth as long as it does not overflow,
  21107. ** to avoid having to call this routine too often */
  21108. szNew += p->nChar;
  21109. }
  21110. if( szNew > p->mxAlloc ){
  21111. sqlite3StrAccumReset(p);
  21112. setStrAccumError(p, STRACCUM_TOOBIG);
  21113. return 0;
  21114. }else{
  21115. p->nAlloc = (int)szNew;
  21116. }
  21117. if( p->db ){
  21118. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  21119. }else{
  21120. zNew = sqlite3_realloc64(zOld, p->nAlloc);
  21121. }
  21122. if( zNew ){
  21123. assert( p->zText!=0 || p->nChar==0 );
  21124. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  21125. p->zText = zNew;
  21126. p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
  21127. }else{
  21128. sqlite3StrAccumReset(p);
  21129. setStrAccumError(p, STRACCUM_NOMEM);
  21130. return 0;
  21131. }
  21132. }
  21133. return N;
  21134. }
  21135. /*
  21136. ** Append N copies of character c to the given string buffer.
  21137. */
  21138. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  21139. testcase( p->nChar + (i64)N > 0x7fffffff );
  21140. if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
  21141. return;
  21142. }
  21143. while( (N--)>0 ) p->zText[p->nChar++] = c;
  21144. }
  21145. /*
  21146. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  21147. ** So enlarge if first, then do the append.
  21148. **
  21149. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  21150. ** work (enlarging the buffer) using tail recursion, so that the
  21151. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  21152. */
  21153. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  21154. N = sqlite3StrAccumEnlarge(p, N);
  21155. if( N>0 ){
  21156. memcpy(&p->zText[p->nChar], z, N);
  21157. p->nChar += N;
  21158. }
  21159. }
  21160. /*
  21161. ** Append N bytes of text from z to the StrAccum object. Increase the
  21162. ** size of the memory allocation for StrAccum if necessary.
  21163. */
  21164. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  21165. assert( z!=0 || N==0 );
  21166. assert( p->zText!=0 || p->nChar==0 || p->accError );
  21167. assert( N>=0 );
  21168. assert( p->accError==0 || p->nAlloc==0 );
  21169. if( p->nChar+N >= p->nAlloc ){
  21170. enlargeAndAppend(p,z,N);
  21171. }else{
  21172. assert( p->zText );
  21173. p->nChar += N;
  21174. memcpy(&p->zText[p->nChar-N], z, N);
  21175. }
  21176. }
  21177. /*
  21178. ** Append the complete text of zero-terminated string z[] to the p string.
  21179. */
  21180. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  21181. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  21182. }
  21183. /*
  21184. ** Finish off a string by making sure it is zero-terminated.
  21185. ** Return a pointer to the resulting string. Return a NULL
  21186. ** pointer if any kind of error was encountered.
  21187. */
  21188. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  21189. if( p->zText ){
  21190. p->zText[p->nChar] = 0;
  21191. if( p->mxAlloc>0 && p->zText==p->zBase ){
  21192. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  21193. if( p->zText ){
  21194. memcpy(p->zText, p->zBase, p->nChar+1);
  21195. }else{
  21196. setStrAccumError(p, STRACCUM_NOMEM);
  21197. }
  21198. }
  21199. }
  21200. return p->zText;
  21201. }
  21202. /*
  21203. ** Reset an StrAccum string. Reclaim all malloced memory.
  21204. */
  21205. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  21206. if( p->zText!=p->zBase ){
  21207. sqlite3DbFree(p->db, p->zText);
  21208. }
  21209. p->zText = 0;
  21210. }
  21211. /*
  21212. ** Initialize a string accumulator.
  21213. **
  21214. ** p: The accumulator to be initialized.
  21215. ** db: Pointer to a database connection. May be NULL. Lookaside
  21216. ** memory is used if not NULL. db->mallocFailed is set appropriately
  21217. ** when not NULL.
  21218. ** zBase: An initial buffer. May be NULL in which case the initial buffer
  21219. ** is malloced.
  21220. ** n: Size of zBase in bytes. If total space requirements never exceed
  21221. ** n then no memory allocations ever occur.
  21222. ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
  21223. ** allocations will ever occur.
  21224. */
  21225. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
  21226. p->zText = p->zBase = zBase;
  21227. p->db = db;
  21228. p->nChar = 0;
  21229. p->nAlloc = n;
  21230. p->mxAlloc = mx;
  21231. p->accError = 0;
  21232. }
  21233. /*
  21234. ** Print into memory obtained from sqliteMalloc(). Use the internal
  21235. ** %-conversion extensions.
  21236. */
  21237. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  21238. char *z;
  21239. char zBase[SQLITE_PRINT_BUF_SIZE];
  21240. StrAccum acc;
  21241. assert( db!=0 );
  21242. sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
  21243. db->aLimit[SQLITE_LIMIT_LENGTH]);
  21244. sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
  21245. z = sqlite3StrAccumFinish(&acc);
  21246. if( acc.accError==STRACCUM_NOMEM ){
  21247. db->mallocFailed = 1;
  21248. }
  21249. return z;
  21250. }
  21251. /*
  21252. ** Print into memory obtained from sqliteMalloc(). Use the internal
  21253. ** %-conversion extensions.
  21254. */
  21255. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  21256. va_list ap;
  21257. char *z;
  21258. va_start(ap, zFormat);
  21259. z = sqlite3VMPrintf(db, zFormat, ap);
  21260. va_end(ap);
  21261. return z;
  21262. }
  21263. /*
  21264. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  21265. ** %-conversion extensions.
  21266. */
  21267. SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
  21268. char *z;
  21269. char zBase[SQLITE_PRINT_BUF_SIZE];
  21270. StrAccum acc;
  21271. #ifdef SQLITE_ENABLE_API_ARMOR
  21272. if( zFormat==0 ){
  21273. (void)SQLITE_MISUSE_BKPT;
  21274. return 0;
  21275. }
  21276. #endif
  21277. #ifndef SQLITE_OMIT_AUTOINIT
  21278. if( sqlite3_initialize() ) return 0;
  21279. #endif
  21280. sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  21281. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21282. z = sqlite3StrAccumFinish(&acc);
  21283. return z;
  21284. }
  21285. /*
  21286. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  21287. ** %-conversion extensions.
  21288. */
  21289. SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
  21290. va_list ap;
  21291. char *z;
  21292. #ifndef SQLITE_OMIT_AUTOINIT
  21293. if( sqlite3_initialize() ) return 0;
  21294. #endif
  21295. va_start(ap, zFormat);
  21296. z = sqlite3_vmprintf(zFormat, ap);
  21297. va_end(ap);
  21298. return z;
  21299. }
  21300. /*
  21301. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  21302. ** current locale settings. This is important for SQLite because we
  21303. ** are not able to use a "," as the decimal point in place of "." as
  21304. ** specified by some locales.
  21305. **
  21306. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  21307. ** from the snprintf() standard. Unfortunately, it is too late to change
  21308. ** this without breaking compatibility, so we just have to live with the
  21309. ** mistake.
  21310. **
  21311. ** sqlite3_vsnprintf() is the varargs version.
  21312. */
  21313. SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  21314. StrAccum acc;
  21315. if( n<=0 ) return zBuf;
  21316. #ifdef SQLITE_ENABLE_API_ARMOR
  21317. if( zBuf==0 || zFormat==0 ) {
  21318. (void)SQLITE_MISUSE_BKPT;
  21319. if( zBuf ) zBuf[0] = 0;
  21320. return zBuf;
  21321. }
  21322. #endif
  21323. sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
  21324. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21325. return sqlite3StrAccumFinish(&acc);
  21326. }
  21327. SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  21328. char *z;
  21329. va_list ap;
  21330. va_start(ap,zFormat);
  21331. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  21332. va_end(ap);
  21333. return z;
  21334. }
  21335. /*
  21336. ** This is the routine that actually formats the sqlite3_log() message.
  21337. ** We house it in a separate routine from sqlite3_log() to avoid using
  21338. ** stack space on small-stack systems when logging is disabled.
  21339. **
  21340. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  21341. ** allocate memory because it might be called while the memory allocator
  21342. ** mutex is held.
  21343. **
  21344. ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
  21345. ** certain format characters (%q) or for very large precisions or widths.
  21346. ** Care must be taken that any sqlite3_log() calls that occur while the
  21347. ** memory mutex is held do not use these mechanisms.
  21348. */
  21349. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  21350. StrAccum acc; /* String accumulator */
  21351. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  21352. sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
  21353. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21354. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  21355. sqlite3StrAccumFinish(&acc));
  21356. }
  21357. /*
  21358. ** Format and write a message to the log if logging is enabled.
  21359. */
  21360. SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
  21361. va_list ap; /* Vararg list */
  21362. if( sqlite3GlobalConfig.xLog ){
  21363. va_start(ap, zFormat);
  21364. renderLogMsg(iErrCode, zFormat, ap);
  21365. va_end(ap);
  21366. }
  21367. }
  21368. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  21369. /*
  21370. ** A version of printf() that understands %lld. Used for debugging.
  21371. ** The printf() built into some versions of windows does not understand %lld
  21372. ** and segfaults if you give it a long long int.
  21373. */
  21374. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  21375. va_list ap;
  21376. StrAccum acc;
  21377. char zBuf[500];
  21378. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  21379. va_start(ap,zFormat);
  21380. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21381. va_end(ap);
  21382. sqlite3StrAccumFinish(&acc);
  21383. fprintf(stdout,"%s", zBuf);
  21384. fflush(stdout);
  21385. }
  21386. #endif
  21387. /*
  21388. ** variable-argument wrapper around sqlite3VXPrintf().
  21389. */
  21390. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
  21391. va_list ap;
  21392. va_start(ap,zFormat);
  21393. sqlite3VXPrintf(p, bFlags, zFormat, ap);
  21394. va_end(ap);
  21395. }
  21396. /************** End of printf.c **********************************************/
  21397. /************** Begin file treeview.c ****************************************/
  21398. /*
  21399. ** 2015-06-08
  21400. **
  21401. ** The author disclaims copyright to this source code. In place of
  21402. ** a legal notice, here is a blessing:
  21403. **
  21404. ** May you do good and not evil.
  21405. ** May you find forgiveness for yourself and forgive others.
  21406. ** May you share freely, never taking more than you give.
  21407. **
  21408. *************************************************************************
  21409. **
  21410. ** This file contains C code to implement the TreeView debugging routines.
  21411. ** These routines print a parse tree to standard output for debugging and
  21412. ** analysis.
  21413. **
  21414. ** The interfaces in this file is only available when compiling
  21415. ** with SQLITE_DEBUG.
  21416. */
  21417. /* #include "sqliteInt.h" */
  21418. #ifdef SQLITE_DEBUG
  21419. /*
  21420. ** Add a new subitem to the tree. The moreToFollow flag indicates that this
  21421. ** is not the last item in the tree.
  21422. */
  21423. static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  21424. if( p==0 ){
  21425. p = sqlite3_malloc64( sizeof(*p) );
  21426. if( p==0 ) return 0;
  21427. memset(p, 0, sizeof(*p));
  21428. }else{
  21429. p->iLevel++;
  21430. }
  21431. assert( moreToFollow==0 || moreToFollow==1 );
  21432. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  21433. return p;
  21434. }
  21435. /*
  21436. ** Finished with one layer of the tree
  21437. */
  21438. static void sqlite3TreeViewPop(TreeView *p){
  21439. if( p==0 ) return;
  21440. p->iLevel--;
  21441. if( p->iLevel<0 ) sqlite3_free(p);
  21442. }
  21443. /*
  21444. ** Generate a single line of output for the tree, with a prefix that contains
  21445. ** all the appropriate tree lines
  21446. */
  21447. static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  21448. va_list ap;
  21449. int i;
  21450. StrAccum acc;
  21451. char zBuf[500];
  21452. sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
  21453. if( p ){
  21454. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  21455. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  21456. }
  21457. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  21458. }
  21459. va_start(ap, zFormat);
  21460. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  21461. va_end(ap);
  21462. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  21463. sqlite3StrAccumFinish(&acc);
  21464. fprintf(stdout,"%s", zBuf);
  21465. fflush(stdout);
  21466. }
  21467. /*
  21468. ** Shorthand for starting a new tree item that consists of a single label
  21469. */
  21470. static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
  21471. p = sqlite3TreeViewPush(p, moreFollows);
  21472. sqlite3TreeViewLine(p, "%s", zLabel);
  21473. }
  21474. /*
  21475. ** Generate a human-readable description of a the Select object.
  21476. */
  21477. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  21478. int n = 0;
  21479. pView = sqlite3TreeViewPush(pView, moreToFollow);
  21480. sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x",
  21481. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  21482. ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags
  21483. );
  21484. if( p->pSrc && p->pSrc->nSrc ) n++;
  21485. if( p->pWhere ) n++;
  21486. if( p->pGroupBy ) n++;
  21487. if( p->pHaving ) n++;
  21488. if( p->pOrderBy ) n++;
  21489. if( p->pLimit ) n++;
  21490. if( p->pOffset ) n++;
  21491. if( p->pPrior ) n++;
  21492. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  21493. if( p->pSrc && p->pSrc->nSrc ){
  21494. int i;
  21495. pView = sqlite3TreeViewPush(pView, (n--)>0);
  21496. sqlite3TreeViewLine(pView, "FROM");
  21497. for(i=0; i<p->pSrc->nSrc; i++){
  21498. struct SrcList_item *pItem = &p->pSrc->a[i];
  21499. StrAccum x;
  21500. char zLine[100];
  21501. sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
  21502. sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
  21503. if( pItem->zDatabase ){
  21504. sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
  21505. }else if( pItem->zName ){
  21506. sqlite3XPrintf(&x, 0, " %s", pItem->zName);
  21507. }
  21508. if( pItem->pTab ){
  21509. sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
  21510. }
  21511. if( pItem->zAlias ){
  21512. sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
  21513. }
  21514. if( pItem->jointype & JT_LEFT ){
  21515. sqlite3XPrintf(&x, 0, " LEFT-JOIN");
  21516. }
  21517. sqlite3StrAccumFinish(&x);
  21518. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  21519. if( pItem->pSelect ){
  21520. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  21521. }
  21522. sqlite3TreeViewPop(pView);
  21523. }
  21524. sqlite3TreeViewPop(pView);
  21525. }
  21526. if( p->pWhere ){
  21527. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  21528. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  21529. sqlite3TreeViewPop(pView);
  21530. }
  21531. if( p->pGroupBy ){
  21532. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  21533. }
  21534. if( p->pHaving ){
  21535. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  21536. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  21537. sqlite3TreeViewPop(pView);
  21538. }
  21539. if( p->pOrderBy ){
  21540. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  21541. }
  21542. if( p->pLimit ){
  21543. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  21544. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  21545. sqlite3TreeViewPop(pView);
  21546. }
  21547. if( p->pOffset ){
  21548. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  21549. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  21550. sqlite3TreeViewPop(pView);
  21551. }
  21552. if( p->pPrior ){
  21553. const char *zOp = "UNION";
  21554. switch( p->op ){
  21555. case TK_ALL: zOp = "UNION ALL"; break;
  21556. case TK_INTERSECT: zOp = "INTERSECT"; break;
  21557. case TK_EXCEPT: zOp = "EXCEPT"; break;
  21558. }
  21559. sqlite3TreeViewItem(pView, zOp, (n--)>0);
  21560. sqlite3TreeViewSelect(pView, p->pPrior, 0);
  21561. sqlite3TreeViewPop(pView);
  21562. }
  21563. sqlite3TreeViewPop(pView);
  21564. }
  21565. /*
  21566. ** Generate a human-readable explanation of an expression tree.
  21567. */
  21568. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  21569. const char *zBinOp = 0; /* Binary operator */
  21570. const char *zUniOp = 0; /* Unary operator */
  21571. char zFlgs[30];
  21572. pView = sqlite3TreeViewPush(pView, moreToFollow);
  21573. if( pExpr==0 ){
  21574. sqlite3TreeViewLine(pView, "nil");
  21575. sqlite3TreeViewPop(pView);
  21576. return;
  21577. }
  21578. if( pExpr->flags ){
  21579. sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
  21580. }else{
  21581. zFlgs[0] = 0;
  21582. }
  21583. switch( pExpr->op ){
  21584. case TK_AGG_COLUMN: {
  21585. sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
  21586. pExpr->iTable, pExpr->iColumn, zFlgs);
  21587. break;
  21588. }
  21589. case TK_COLUMN: {
  21590. if( pExpr->iTable<0 ){
  21591. /* This only happens when coding check constraints */
  21592. sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
  21593. }else{
  21594. sqlite3TreeViewLine(pView, "{%d:%d}%s",
  21595. pExpr->iTable, pExpr->iColumn, zFlgs);
  21596. }
  21597. break;
  21598. }
  21599. case TK_INTEGER: {
  21600. if( pExpr->flags & EP_IntValue ){
  21601. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  21602. }else{
  21603. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  21604. }
  21605. break;
  21606. }
  21607. #ifndef SQLITE_OMIT_FLOATING_POINT
  21608. case TK_FLOAT: {
  21609. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  21610. break;
  21611. }
  21612. #endif
  21613. case TK_STRING: {
  21614. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  21615. break;
  21616. }
  21617. case TK_NULL: {
  21618. sqlite3TreeViewLine(pView,"NULL");
  21619. break;
  21620. }
  21621. #ifndef SQLITE_OMIT_BLOB_LITERAL
  21622. case TK_BLOB: {
  21623. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  21624. break;
  21625. }
  21626. #endif
  21627. case TK_VARIABLE: {
  21628. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  21629. pExpr->u.zToken, pExpr->iColumn);
  21630. break;
  21631. }
  21632. case TK_REGISTER: {
  21633. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  21634. break;
  21635. }
  21636. case TK_AS: {
  21637. sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
  21638. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  21639. break;
  21640. }
  21641. case TK_ID: {
  21642. sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
  21643. break;
  21644. }
  21645. #ifndef SQLITE_OMIT_CAST
  21646. case TK_CAST: {
  21647. /* Expressions of the form: CAST(pLeft AS token) */
  21648. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  21649. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  21650. break;
  21651. }
  21652. #endif /* SQLITE_OMIT_CAST */
  21653. case TK_LT: zBinOp = "LT"; break;
  21654. case TK_LE: zBinOp = "LE"; break;
  21655. case TK_GT: zBinOp = "GT"; break;
  21656. case TK_GE: zBinOp = "GE"; break;
  21657. case TK_NE: zBinOp = "NE"; break;
  21658. case TK_EQ: zBinOp = "EQ"; break;
  21659. case TK_IS: zBinOp = "IS"; break;
  21660. case TK_ISNOT: zBinOp = "ISNOT"; break;
  21661. case TK_AND: zBinOp = "AND"; break;
  21662. case TK_OR: zBinOp = "OR"; break;
  21663. case TK_PLUS: zBinOp = "ADD"; break;
  21664. case TK_STAR: zBinOp = "MUL"; break;
  21665. case TK_MINUS: zBinOp = "SUB"; break;
  21666. case TK_REM: zBinOp = "REM"; break;
  21667. case TK_BITAND: zBinOp = "BITAND"; break;
  21668. case TK_BITOR: zBinOp = "BITOR"; break;
  21669. case TK_SLASH: zBinOp = "DIV"; break;
  21670. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  21671. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  21672. case TK_CONCAT: zBinOp = "CONCAT"; break;
  21673. case TK_DOT: zBinOp = "DOT"; break;
  21674. case TK_UMINUS: zUniOp = "UMINUS"; break;
  21675. case TK_UPLUS: zUniOp = "UPLUS"; break;
  21676. case TK_BITNOT: zUniOp = "BITNOT"; break;
  21677. case TK_NOT: zUniOp = "NOT"; break;
  21678. case TK_ISNULL: zUniOp = "ISNULL"; break;
  21679. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  21680. case TK_COLLATE: {
  21681. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  21682. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  21683. break;
  21684. }
  21685. case TK_AGG_FUNCTION:
  21686. case TK_FUNCTION: {
  21687. ExprList *pFarg; /* List of function arguments */
  21688. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  21689. pFarg = 0;
  21690. }else{
  21691. pFarg = pExpr->x.pList;
  21692. }
  21693. if( pExpr->op==TK_AGG_FUNCTION ){
  21694. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  21695. pExpr->op2, pExpr->u.zToken);
  21696. }else{
  21697. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  21698. }
  21699. if( pFarg ){
  21700. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  21701. }
  21702. break;
  21703. }
  21704. #ifndef SQLITE_OMIT_SUBQUERY
  21705. case TK_EXISTS: {
  21706. sqlite3TreeViewLine(pView, "EXISTS-expr");
  21707. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  21708. break;
  21709. }
  21710. case TK_SELECT: {
  21711. sqlite3TreeViewLine(pView, "SELECT-expr");
  21712. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  21713. break;
  21714. }
  21715. case TK_IN: {
  21716. sqlite3TreeViewLine(pView, "IN");
  21717. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  21718. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  21719. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  21720. }else{
  21721. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  21722. }
  21723. break;
  21724. }
  21725. #endif /* SQLITE_OMIT_SUBQUERY */
  21726. /*
  21727. ** x BETWEEN y AND z
  21728. **
  21729. ** This is equivalent to
  21730. **
  21731. ** x>=y AND x<=z
  21732. **
  21733. ** X is stored in pExpr->pLeft.
  21734. ** Y is stored in pExpr->pList->a[0].pExpr.
  21735. ** Z is stored in pExpr->pList->a[1].pExpr.
  21736. */
  21737. case TK_BETWEEN: {
  21738. Expr *pX = pExpr->pLeft;
  21739. Expr *pY = pExpr->x.pList->a[0].pExpr;
  21740. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  21741. sqlite3TreeViewLine(pView, "BETWEEN");
  21742. sqlite3TreeViewExpr(pView, pX, 1);
  21743. sqlite3TreeViewExpr(pView, pY, 1);
  21744. sqlite3TreeViewExpr(pView, pZ, 0);
  21745. break;
  21746. }
  21747. case TK_TRIGGER: {
  21748. /* If the opcode is TK_TRIGGER, then the expression is a reference
  21749. ** to a column in the new.* or old.* pseudo-tables available to
  21750. ** trigger programs. In this case Expr.iTable is set to 1 for the
  21751. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  21752. ** is set to the column of the pseudo-table to read, or to -1 to
  21753. ** read the rowid field.
  21754. */
  21755. sqlite3TreeViewLine(pView, "%s(%d)",
  21756. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  21757. break;
  21758. }
  21759. case TK_CASE: {
  21760. sqlite3TreeViewLine(pView, "CASE");
  21761. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  21762. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  21763. break;
  21764. }
  21765. #ifndef SQLITE_OMIT_TRIGGER
  21766. case TK_RAISE: {
  21767. const char *zType = "unk";
  21768. switch( pExpr->affinity ){
  21769. case OE_Rollback: zType = "rollback"; break;
  21770. case OE_Abort: zType = "abort"; break;
  21771. case OE_Fail: zType = "fail"; break;
  21772. case OE_Ignore: zType = "ignore"; break;
  21773. }
  21774. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  21775. break;
  21776. }
  21777. #endif
  21778. default: {
  21779. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  21780. break;
  21781. }
  21782. }
  21783. if( zBinOp ){
  21784. sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
  21785. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  21786. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  21787. }else if( zUniOp ){
  21788. sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
  21789. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  21790. }
  21791. sqlite3TreeViewPop(pView);
  21792. }
  21793. /*
  21794. ** Generate a human-readable explanation of an expression list.
  21795. */
  21796. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  21797. TreeView *pView,
  21798. const ExprList *pList,
  21799. u8 moreToFollow,
  21800. const char *zLabel
  21801. ){
  21802. int i;
  21803. pView = sqlite3TreeViewPush(pView, moreToFollow);
  21804. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  21805. if( pList==0 ){
  21806. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  21807. }else{
  21808. sqlite3TreeViewLine(pView, "%s", zLabel);
  21809. for(i=0; i<pList->nExpr; i++){
  21810. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  21811. }
  21812. }
  21813. sqlite3TreeViewPop(pView);
  21814. }
  21815. #endif /* SQLITE_DEBUG */
  21816. /************** End of treeview.c ********************************************/
  21817. /************** Begin file random.c ******************************************/
  21818. /*
  21819. ** 2001 September 15
  21820. **
  21821. ** The author disclaims copyright to this source code. In place of
  21822. ** a legal notice, here is a blessing:
  21823. **
  21824. ** May you do good and not evil.
  21825. ** May you find forgiveness for yourself and forgive others.
  21826. ** May you share freely, never taking more than you give.
  21827. **
  21828. *************************************************************************
  21829. ** This file contains code to implement a pseudo-random number
  21830. ** generator (PRNG) for SQLite.
  21831. **
  21832. ** Random numbers are used by some of the database backends in order
  21833. ** to generate random integer keys for tables or random filenames.
  21834. */
  21835. /* #include "sqliteInt.h" */
  21836. /* All threads share a single random number generator.
  21837. ** This structure is the current state of the generator.
  21838. */
  21839. static SQLITE_WSD struct sqlite3PrngType {
  21840. unsigned char isInit; /* True if initialized */
  21841. unsigned char i, j; /* State variables */
  21842. unsigned char s[256]; /* State variables */
  21843. } sqlite3Prng;
  21844. /*
  21845. ** Return N random bytes.
  21846. */
  21847. SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
  21848. unsigned char t;
  21849. unsigned char *zBuf = pBuf;
  21850. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  21851. ** state vector. If writable static data is unsupported on the target,
  21852. ** we have to locate the state vector at run-time. In the more common
  21853. ** case where writable static data is supported, wsdPrng can refer directly
  21854. ** to the "sqlite3Prng" state vector declared above.
  21855. */
  21856. #ifdef SQLITE_OMIT_WSD
  21857. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  21858. # define wsdPrng p[0]
  21859. #else
  21860. # define wsdPrng sqlite3Prng
  21861. #endif
  21862. #if SQLITE_THREADSAFE
  21863. sqlite3_mutex *mutex;
  21864. #endif
  21865. #ifndef SQLITE_OMIT_AUTOINIT
  21866. if( sqlite3_initialize() ) return;
  21867. #endif
  21868. #if SQLITE_THREADSAFE
  21869. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  21870. #endif
  21871. sqlite3_mutex_enter(mutex);
  21872. if( N<=0 || pBuf==0 ){
  21873. wsdPrng.isInit = 0;
  21874. sqlite3_mutex_leave(mutex);
  21875. return;
  21876. }
  21877. /* Initialize the state of the random number generator once,
  21878. ** the first time this routine is called. The seed value does
  21879. ** not need to contain a lot of randomness since we are not
  21880. ** trying to do secure encryption or anything like that...
  21881. **
  21882. ** Nothing in this file or anywhere else in SQLite does any kind of
  21883. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  21884. ** number generator) not as an encryption device.
  21885. */
  21886. if( !wsdPrng.isInit ){
  21887. int i;
  21888. char k[256];
  21889. wsdPrng.j = 0;
  21890. wsdPrng.i = 0;
  21891. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  21892. for(i=0; i<256; i++){
  21893. wsdPrng.s[i] = (u8)i;
  21894. }
  21895. for(i=0; i<256; i++){
  21896. wsdPrng.j += wsdPrng.s[i] + k[i];
  21897. t = wsdPrng.s[wsdPrng.j];
  21898. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  21899. wsdPrng.s[i] = t;
  21900. }
  21901. wsdPrng.isInit = 1;
  21902. }
  21903. assert( N>0 );
  21904. do{
  21905. wsdPrng.i++;
  21906. t = wsdPrng.s[wsdPrng.i];
  21907. wsdPrng.j += t;
  21908. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  21909. wsdPrng.s[wsdPrng.j] = t;
  21910. t += wsdPrng.s[wsdPrng.i];
  21911. *(zBuf++) = wsdPrng.s[t];
  21912. }while( --N );
  21913. sqlite3_mutex_leave(mutex);
  21914. }
  21915. #ifndef SQLITE_OMIT_BUILTIN_TEST
  21916. /*
  21917. ** For testing purposes, we sometimes want to preserve the state of
  21918. ** PRNG and restore the PRNG to its saved state at a later time, or
  21919. ** to reset the PRNG to its initial state. These routines accomplish
  21920. ** those tasks.
  21921. **
  21922. ** The sqlite3_test_control() interface calls these routines to
  21923. ** control the PRNG.
  21924. */
  21925. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  21926. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  21927. memcpy(
  21928. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  21929. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  21930. sizeof(sqlite3Prng)
  21931. );
  21932. }
  21933. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  21934. memcpy(
  21935. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  21936. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  21937. sizeof(sqlite3Prng)
  21938. );
  21939. }
  21940. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  21941. /************** End of random.c **********************************************/
  21942. /************** Begin file threads.c *****************************************/
  21943. /*
  21944. ** 2012 July 21
  21945. **
  21946. ** The author disclaims copyright to this source code. In place of
  21947. ** a legal notice, here is a blessing:
  21948. **
  21949. ** May you do good and not evil.
  21950. ** May you find forgiveness for yourself and forgive others.
  21951. ** May you share freely, never taking more than you give.
  21952. **
  21953. ******************************************************************************
  21954. **
  21955. ** This file presents a simple cross-platform threading interface for
  21956. ** use internally by SQLite.
  21957. **
  21958. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  21959. ** runs independently of its creator until it is joined using
  21960. ** sqlite3ThreadJoin(), at which point it terminates.
  21961. **
  21962. ** Threads do not have to be real. It could be that the work of the
  21963. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  21964. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  21965. ** single threaded systems. Nothing in SQLite requires multiple threads.
  21966. ** This interface exists so that applications that want to take advantage
  21967. ** of multiple cores can do so, while also allowing applications to stay
  21968. ** single-threaded if desired.
  21969. */
  21970. /* #include "sqliteInt.h" */
  21971. #if SQLITE_OS_WIN
  21972. /* # include "os_win.h" */
  21973. #endif
  21974. #if SQLITE_MAX_WORKER_THREADS>0
  21975. /********************************* Unix Pthreads ****************************/
  21976. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  21977. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  21978. /* #include <pthread.h> */
  21979. /* A running thread */
  21980. struct SQLiteThread {
  21981. pthread_t tid; /* Thread ID */
  21982. int done; /* Set to true when thread finishes */
  21983. void *pOut; /* Result returned by the thread */
  21984. void *(*xTask)(void*); /* The thread routine */
  21985. void *pIn; /* Argument to the thread */
  21986. };
  21987. /* Create a new thread */
  21988. SQLITE_PRIVATE int sqlite3ThreadCreate(
  21989. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  21990. void *(*xTask)(void*), /* Routine to run in a separate thread */
  21991. void *pIn /* Argument passed into xTask() */
  21992. ){
  21993. SQLiteThread *p;
  21994. int rc;
  21995. assert( ppThread!=0 );
  21996. assert( xTask!=0 );
  21997. /* This routine is never used in single-threaded mode */
  21998. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  21999. *ppThread = 0;
  22000. p = sqlite3Malloc(sizeof(*p));
  22001. if( p==0 ) return SQLITE_NOMEM;
  22002. memset(p, 0, sizeof(*p));
  22003. p->xTask = xTask;
  22004. p->pIn = pIn;
  22005. if( sqlite3FaultSim(200) ){
  22006. rc = 1;
  22007. }else{
  22008. rc = pthread_create(&p->tid, 0, xTask, pIn);
  22009. }
  22010. if( rc ){
  22011. p->done = 1;
  22012. p->pOut = xTask(pIn);
  22013. }
  22014. *ppThread = p;
  22015. return SQLITE_OK;
  22016. }
  22017. /* Get the results of the thread */
  22018. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  22019. int rc;
  22020. assert( ppOut!=0 );
  22021. if( NEVER(p==0) ) return SQLITE_NOMEM;
  22022. if( p->done ){
  22023. *ppOut = p->pOut;
  22024. rc = SQLITE_OK;
  22025. }else{
  22026. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  22027. }
  22028. sqlite3_free(p);
  22029. return rc;
  22030. }
  22031. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  22032. /******************************** End Unix Pthreads *************************/
  22033. /********************************* Win32 Threads ****************************/
  22034. #if SQLITE_OS_WIN_THREADS
  22035. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  22036. #include <process.h>
  22037. /* A running thread */
  22038. struct SQLiteThread {
  22039. void *tid; /* The thread handle */
  22040. unsigned id; /* The thread identifier */
  22041. void *(*xTask)(void*); /* The routine to run as a thread */
  22042. void *pIn; /* Argument to xTask */
  22043. void *pResult; /* Result of xTask */
  22044. };
  22045. /* Thread procedure Win32 compatibility shim */
  22046. static unsigned __stdcall sqlite3ThreadProc(
  22047. void *pArg /* IN: Pointer to the SQLiteThread structure */
  22048. ){
  22049. SQLiteThread *p = (SQLiteThread *)pArg;
  22050. assert( p!=0 );
  22051. #if 0
  22052. /*
  22053. ** This assert appears to trigger spuriously on certain
  22054. ** versions of Windows, possibly due to _beginthreadex()
  22055. ** and/or CreateThread() not fully setting their thread
  22056. ** ID parameter before starting the thread.
  22057. */
  22058. assert( p->id==GetCurrentThreadId() );
  22059. #endif
  22060. assert( p->xTask!=0 );
  22061. p->pResult = p->xTask(p->pIn);
  22062. _endthreadex(0);
  22063. return 0; /* NOT REACHED */
  22064. }
  22065. /* Create a new thread */
  22066. SQLITE_PRIVATE int sqlite3ThreadCreate(
  22067. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  22068. void *(*xTask)(void*), /* Routine to run in a separate thread */
  22069. void *pIn /* Argument passed into xTask() */
  22070. ){
  22071. SQLiteThread *p;
  22072. assert( ppThread!=0 );
  22073. assert( xTask!=0 );
  22074. *ppThread = 0;
  22075. p = sqlite3Malloc(sizeof(*p));
  22076. if( p==0 ) return SQLITE_NOMEM;
  22077. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  22078. memset(p, 0, sizeof(*p));
  22079. }else{
  22080. p->xTask = xTask;
  22081. p->pIn = pIn;
  22082. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  22083. if( p->tid==0 ){
  22084. memset(p, 0, sizeof(*p));
  22085. }
  22086. }
  22087. if( p->xTask==0 ){
  22088. p->id = GetCurrentThreadId();
  22089. p->pResult = xTask(pIn);
  22090. }
  22091. *ppThread = p;
  22092. return SQLITE_OK;
  22093. }
  22094. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  22095. /* Get the results of the thread */
  22096. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  22097. DWORD rc;
  22098. BOOL bRc;
  22099. assert( ppOut!=0 );
  22100. if( NEVER(p==0) ) return SQLITE_NOMEM;
  22101. if( p->xTask==0 ){
  22102. assert( p->id==GetCurrentThreadId() );
  22103. rc = WAIT_OBJECT_0;
  22104. assert( p->tid==0 );
  22105. }else{
  22106. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  22107. rc = sqlite3Win32Wait((HANDLE)p->tid);
  22108. assert( rc!=WAIT_IO_COMPLETION );
  22109. bRc = CloseHandle((HANDLE)p->tid);
  22110. assert( bRc );
  22111. }
  22112. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  22113. sqlite3_free(p);
  22114. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  22115. }
  22116. #endif /* SQLITE_OS_WIN_THREADS */
  22117. /******************************** End Win32 Threads *************************/
  22118. /********************************* Single-Threaded **************************/
  22119. #ifndef SQLITE_THREADS_IMPLEMENTED
  22120. /*
  22121. ** This implementation does not actually create a new thread. It does the
  22122. ** work of the thread in the main thread, when either the thread is created
  22123. ** or when it is joined
  22124. */
  22125. /* A running thread */
  22126. struct SQLiteThread {
  22127. void *(*xTask)(void*); /* The routine to run as a thread */
  22128. void *pIn; /* Argument to xTask */
  22129. void *pResult; /* Result of xTask */
  22130. };
  22131. /* Create a new thread */
  22132. SQLITE_PRIVATE int sqlite3ThreadCreate(
  22133. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  22134. void *(*xTask)(void*), /* Routine to run in a separate thread */
  22135. void *pIn /* Argument passed into xTask() */
  22136. ){
  22137. SQLiteThread *p;
  22138. assert( ppThread!=0 );
  22139. assert( xTask!=0 );
  22140. *ppThread = 0;
  22141. p = sqlite3Malloc(sizeof(*p));
  22142. if( p==0 ) return SQLITE_NOMEM;
  22143. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  22144. p->xTask = xTask;
  22145. p->pIn = pIn;
  22146. }else{
  22147. p->xTask = 0;
  22148. p->pResult = xTask(pIn);
  22149. }
  22150. *ppThread = p;
  22151. return SQLITE_OK;
  22152. }
  22153. /* Get the results of the thread */
  22154. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  22155. assert( ppOut!=0 );
  22156. if( NEVER(p==0) ) return SQLITE_NOMEM;
  22157. if( p->xTask ){
  22158. *ppOut = p->xTask(p->pIn);
  22159. }else{
  22160. *ppOut = p->pResult;
  22161. }
  22162. sqlite3_free(p);
  22163. #if defined(SQLITE_TEST)
  22164. {
  22165. void *pTstAlloc = sqlite3Malloc(10);
  22166. if (!pTstAlloc) return SQLITE_NOMEM;
  22167. sqlite3_free(pTstAlloc);
  22168. }
  22169. #endif
  22170. return SQLITE_OK;
  22171. }
  22172. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  22173. /****************************** End Single-Threaded *************************/
  22174. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  22175. /************** End of threads.c *********************************************/
  22176. /************** Begin file utf.c *********************************************/
  22177. /*
  22178. ** 2004 April 13
  22179. **
  22180. ** The author disclaims copyright to this source code. In place of
  22181. ** a legal notice, here is a blessing:
  22182. **
  22183. ** May you do good and not evil.
  22184. ** May you find forgiveness for yourself and forgive others.
  22185. ** May you share freely, never taking more than you give.
  22186. **
  22187. *************************************************************************
  22188. ** This file contains routines used to translate between UTF-8,
  22189. ** UTF-16, UTF-16BE, and UTF-16LE.
  22190. **
  22191. ** Notes on UTF-8:
  22192. **
  22193. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  22194. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  22195. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  22196. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  22197. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  22198. **
  22199. **
  22200. ** Notes on UTF-16: (with wwww+1==uuuuu)
  22201. **
  22202. ** Word-0 Word-1 Value
  22203. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  22204. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  22205. **
  22206. **
  22207. ** BOM or Byte Order Mark:
  22208. ** 0xff 0xfe little-endian utf-16 follows
  22209. ** 0xfe 0xff big-endian utf-16 follows
  22210. **
  22211. */
  22212. /* #include "sqliteInt.h" */
  22213. /* #include <assert.h> */
  22214. /* #include "vdbeInt.h" */
  22215. #ifndef SQLITE_AMALGAMATION
  22216. /*
  22217. ** The following constant value is used by the SQLITE_BIGENDIAN and
  22218. ** SQLITE_LITTLEENDIAN macros.
  22219. */
  22220. SQLITE_PRIVATE const int sqlite3one = 1;
  22221. #endif /* SQLITE_AMALGAMATION */
  22222. /*
  22223. ** This lookup table is used to help decode the first byte of
  22224. ** a multi-byte UTF8 character.
  22225. */
  22226. static const unsigned char sqlite3Utf8Trans1[] = {
  22227. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  22228. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  22229. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  22230. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  22231. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  22232. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  22233. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  22234. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  22235. };
  22236. #define WRITE_UTF8(zOut, c) { \
  22237. if( c<0x00080 ){ \
  22238. *zOut++ = (u8)(c&0xFF); \
  22239. } \
  22240. else if( c<0x00800 ){ \
  22241. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  22242. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  22243. } \
  22244. else if( c<0x10000 ){ \
  22245. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  22246. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  22247. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  22248. }else{ \
  22249. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  22250. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  22251. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  22252. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  22253. } \
  22254. }
  22255. #define WRITE_UTF16LE(zOut, c) { \
  22256. if( c<=0xFFFF ){ \
  22257. *zOut++ = (u8)(c&0x00FF); \
  22258. *zOut++ = (u8)((c>>8)&0x00FF); \
  22259. }else{ \
  22260. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  22261. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  22262. *zOut++ = (u8)(c&0x00FF); \
  22263. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  22264. } \
  22265. }
  22266. #define WRITE_UTF16BE(zOut, c) { \
  22267. if( c<=0xFFFF ){ \
  22268. *zOut++ = (u8)((c>>8)&0x00FF); \
  22269. *zOut++ = (u8)(c&0x00FF); \
  22270. }else{ \
  22271. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  22272. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  22273. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  22274. *zOut++ = (u8)(c&0x00FF); \
  22275. } \
  22276. }
  22277. #define READ_UTF16LE(zIn, TERM, c){ \
  22278. c = (*zIn++); \
  22279. c += ((*zIn++)<<8); \
  22280. if( c>=0xD800 && c<0xE000 && TERM ){ \
  22281. int c2 = (*zIn++); \
  22282. c2 += ((*zIn++)<<8); \
  22283. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  22284. } \
  22285. }
  22286. #define READ_UTF16BE(zIn, TERM, c){ \
  22287. c = ((*zIn++)<<8); \
  22288. c += (*zIn++); \
  22289. if( c>=0xD800 && c<0xE000 && TERM ){ \
  22290. int c2 = ((*zIn++)<<8); \
  22291. c2 += (*zIn++); \
  22292. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  22293. } \
  22294. }
  22295. /*
  22296. ** Translate a single UTF-8 character. Return the unicode value.
  22297. **
  22298. ** During translation, assume that the byte that zTerm points
  22299. ** is a 0x00.
  22300. **
  22301. ** Write a pointer to the next unread byte back into *pzNext.
  22302. **
  22303. ** Notes On Invalid UTF-8:
  22304. **
  22305. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  22306. ** be encoded as a multi-byte character. Any multi-byte character that
  22307. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  22308. **
  22309. ** * This routine never allows a UTF16 surrogate value to be encoded.
  22310. ** If a multi-byte character attempts to encode a value between
  22311. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  22312. **
  22313. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  22314. ** byte of a character are interpreted as single-byte characters
  22315. ** and rendered as themselves even though they are technically
  22316. ** invalid characters.
  22317. **
  22318. ** * This routine accepts over-length UTF8 encodings
  22319. ** for unicode values 0x80 and greater. It does not change over-length
  22320. ** encodings to 0xfffd as some systems recommend.
  22321. */
  22322. #define READ_UTF8(zIn, zTerm, c) \
  22323. c = *(zIn++); \
  22324. if( c>=0xc0 ){ \
  22325. c = sqlite3Utf8Trans1[c-0xc0]; \
  22326. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  22327. c = (c<<6) + (0x3f & *(zIn++)); \
  22328. } \
  22329. if( c<0x80 \
  22330. || (c&0xFFFFF800)==0xD800 \
  22331. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  22332. }
  22333. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  22334. const unsigned char **pz /* Pointer to string from which to read char */
  22335. ){
  22336. unsigned int c;
  22337. /* Same as READ_UTF8() above but without the zTerm parameter.
  22338. ** For this routine, we assume the UTF8 string is always zero-terminated.
  22339. */
  22340. c = *((*pz)++);
  22341. if( c>=0xc0 ){
  22342. c = sqlite3Utf8Trans1[c-0xc0];
  22343. while( (*(*pz) & 0xc0)==0x80 ){
  22344. c = (c<<6) + (0x3f & *((*pz)++));
  22345. }
  22346. if( c<0x80
  22347. || (c&0xFFFFF800)==0xD800
  22348. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  22349. }
  22350. return c;
  22351. }
  22352. /*
  22353. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  22354. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  22355. */
  22356. /* #define TRANSLATE_TRACE 1 */
  22357. #ifndef SQLITE_OMIT_UTF16
  22358. /*
  22359. ** This routine transforms the internal text encoding used by pMem to
  22360. ** desiredEnc. It is an error if the string is already of the desired
  22361. ** encoding, or if *pMem does not contain a string value.
  22362. */
  22363. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  22364. int len; /* Maximum length of output string in bytes */
  22365. unsigned char *zOut; /* Output buffer */
  22366. unsigned char *zIn; /* Input iterator */
  22367. unsigned char *zTerm; /* End of input */
  22368. unsigned char *z; /* Output iterator */
  22369. unsigned int c;
  22370. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  22371. assert( pMem->flags&MEM_Str );
  22372. assert( pMem->enc!=desiredEnc );
  22373. assert( pMem->enc!=0 );
  22374. assert( pMem->n>=0 );
  22375. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  22376. {
  22377. char zBuf[100];
  22378. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  22379. fprintf(stderr, "INPUT: %s\n", zBuf);
  22380. }
  22381. #endif
  22382. /* If the translation is between UTF-16 little and big endian, then
  22383. ** all that is required is to swap the byte order. This case is handled
  22384. ** differently from the others.
  22385. */
  22386. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  22387. u8 temp;
  22388. int rc;
  22389. rc = sqlite3VdbeMemMakeWriteable(pMem);
  22390. if( rc!=SQLITE_OK ){
  22391. assert( rc==SQLITE_NOMEM );
  22392. return SQLITE_NOMEM;
  22393. }
  22394. zIn = (u8*)pMem->z;
  22395. zTerm = &zIn[pMem->n&~1];
  22396. while( zIn<zTerm ){
  22397. temp = *zIn;
  22398. *zIn = *(zIn+1);
  22399. zIn++;
  22400. *zIn++ = temp;
  22401. }
  22402. pMem->enc = desiredEnc;
  22403. goto translate_out;
  22404. }
  22405. /* Set len to the maximum number of bytes required in the output buffer. */
  22406. if( desiredEnc==SQLITE_UTF8 ){
  22407. /* When converting from UTF-16, the maximum growth results from
  22408. ** translating a 2-byte character to a 4-byte UTF-8 character.
  22409. ** A single byte is required for the output string
  22410. ** nul-terminator.
  22411. */
  22412. pMem->n &= ~1;
  22413. len = pMem->n * 2 + 1;
  22414. }else{
  22415. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  22416. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  22417. ** character. Two bytes are required in the output buffer for the
  22418. ** nul-terminator.
  22419. */
  22420. len = pMem->n * 2 + 2;
  22421. }
  22422. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  22423. ** byte past the end.
  22424. **
  22425. ** Variable zOut is set to point at the output buffer, space obtained
  22426. ** from sqlite3_malloc().
  22427. */
  22428. zIn = (u8*)pMem->z;
  22429. zTerm = &zIn[pMem->n];
  22430. zOut = sqlite3DbMallocRaw(pMem->db, len);
  22431. if( !zOut ){
  22432. return SQLITE_NOMEM;
  22433. }
  22434. z = zOut;
  22435. if( pMem->enc==SQLITE_UTF8 ){
  22436. if( desiredEnc==SQLITE_UTF16LE ){
  22437. /* UTF-8 -> UTF-16 Little-endian */
  22438. while( zIn<zTerm ){
  22439. READ_UTF8(zIn, zTerm, c);
  22440. WRITE_UTF16LE(z, c);
  22441. }
  22442. }else{
  22443. assert( desiredEnc==SQLITE_UTF16BE );
  22444. /* UTF-8 -> UTF-16 Big-endian */
  22445. while( zIn<zTerm ){
  22446. READ_UTF8(zIn, zTerm, c);
  22447. WRITE_UTF16BE(z, c);
  22448. }
  22449. }
  22450. pMem->n = (int)(z - zOut);
  22451. *z++ = 0;
  22452. }else{
  22453. assert( desiredEnc==SQLITE_UTF8 );
  22454. if( pMem->enc==SQLITE_UTF16LE ){
  22455. /* UTF-16 Little-endian -> UTF-8 */
  22456. while( zIn<zTerm ){
  22457. READ_UTF16LE(zIn, zIn<zTerm, c);
  22458. WRITE_UTF8(z, c);
  22459. }
  22460. }else{
  22461. /* UTF-16 Big-endian -> UTF-8 */
  22462. while( zIn<zTerm ){
  22463. READ_UTF16BE(zIn, zIn<zTerm, c);
  22464. WRITE_UTF8(z, c);
  22465. }
  22466. }
  22467. pMem->n = (int)(z - zOut);
  22468. }
  22469. *z = 0;
  22470. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  22471. c = pMem->flags;
  22472. sqlite3VdbeMemRelease(pMem);
  22473. pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
  22474. pMem->enc = desiredEnc;
  22475. pMem->z = (char*)zOut;
  22476. pMem->zMalloc = pMem->z;
  22477. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  22478. translate_out:
  22479. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  22480. {
  22481. char zBuf[100];
  22482. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  22483. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  22484. }
  22485. #endif
  22486. return SQLITE_OK;
  22487. }
  22488. /*
  22489. ** This routine checks for a byte-order mark at the beginning of the
  22490. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  22491. ** the encoding of the Mem adjusted. This routine does not do any
  22492. ** byte-swapping, it just sets Mem.enc appropriately.
  22493. **
  22494. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  22495. ** changed by this function.
  22496. */
  22497. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  22498. int rc = SQLITE_OK;
  22499. u8 bom = 0;
  22500. assert( pMem->n>=0 );
  22501. if( pMem->n>1 ){
  22502. u8 b1 = *(u8 *)pMem->z;
  22503. u8 b2 = *(((u8 *)pMem->z) + 1);
  22504. if( b1==0xFE && b2==0xFF ){
  22505. bom = SQLITE_UTF16BE;
  22506. }
  22507. if( b1==0xFF && b2==0xFE ){
  22508. bom = SQLITE_UTF16LE;
  22509. }
  22510. }
  22511. if( bom ){
  22512. rc = sqlite3VdbeMemMakeWriteable(pMem);
  22513. if( rc==SQLITE_OK ){
  22514. pMem->n -= 2;
  22515. memmove(pMem->z, &pMem->z[2], pMem->n);
  22516. pMem->z[pMem->n] = '\0';
  22517. pMem->z[pMem->n+1] = '\0';
  22518. pMem->flags |= MEM_Term;
  22519. pMem->enc = bom;
  22520. }
  22521. }
  22522. return rc;
  22523. }
  22524. #endif /* SQLITE_OMIT_UTF16 */
  22525. /*
  22526. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  22527. ** return the number of unicode characters in pZ up to (but not including)
  22528. ** the first 0x00 byte. If nByte is not less than zero, return the
  22529. ** number of unicode characters in the first nByte of pZ (or up to
  22530. ** the first 0x00, whichever comes first).
  22531. */
  22532. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  22533. int r = 0;
  22534. const u8 *z = (const u8*)zIn;
  22535. const u8 *zTerm;
  22536. if( nByte>=0 ){
  22537. zTerm = &z[nByte];
  22538. }else{
  22539. zTerm = (const u8*)(-1);
  22540. }
  22541. assert( z<=zTerm );
  22542. while( *z!=0 && z<zTerm ){
  22543. SQLITE_SKIP_UTF8(z);
  22544. r++;
  22545. }
  22546. return r;
  22547. }
  22548. /* This test function is not currently used by the automated test-suite.
  22549. ** Hence it is only available in debug builds.
  22550. */
  22551. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22552. /*
  22553. ** Translate UTF-8 to UTF-8.
  22554. **
  22555. ** This has the effect of making sure that the string is well-formed
  22556. ** UTF-8. Miscoded characters are removed.
  22557. **
  22558. ** The translation is done in-place and aborted if the output
  22559. ** overruns the input.
  22560. */
  22561. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  22562. unsigned char *zOut = zIn;
  22563. unsigned char *zStart = zIn;
  22564. u32 c;
  22565. while( zIn[0] && zOut<=zIn ){
  22566. c = sqlite3Utf8Read((const u8**)&zIn);
  22567. if( c!=0xfffd ){
  22568. WRITE_UTF8(zOut, c);
  22569. }
  22570. }
  22571. *zOut = 0;
  22572. return (int)(zOut - zStart);
  22573. }
  22574. #endif
  22575. #ifndef SQLITE_OMIT_UTF16
  22576. /*
  22577. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  22578. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  22579. ** be freed by the calling function.
  22580. **
  22581. ** NULL is returned if there is an allocation error.
  22582. */
  22583. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  22584. Mem m;
  22585. memset(&m, 0, sizeof(m));
  22586. m.db = db;
  22587. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  22588. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  22589. if( db->mallocFailed ){
  22590. sqlite3VdbeMemRelease(&m);
  22591. m.z = 0;
  22592. }
  22593. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  22594. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  22595. assert( m.z || db->mallocFailed );
  22596. return m.z;
  22597. }
  22598. /*
  22599. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  22600. ** Return the number of bytes in the first nChar unicode characters
  22601. ** in pZ. nChar must be non-negative.
  22602. */
  22603. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  22604. int c;
  22605. unsigned char const *z = zIn;
  22606. int n = 0;
  22607. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  22608. while( n<nChar ){
  22609. READ_UTF16BE(z, 1, c);
  22610. n++;
  22611. }
  22612. }else{
  22613. while( n<nChar ){
  22614. READ_UTF16LE(z, 1, c);
  22615. n++;
  22616. }
  22617. }
  22618. return (int)(z-(unsigned char const *)zIn);
  22619. }
  22620. #if defined(SQLITE_TEST)
  22621. /*
  22622. ** This routine is called from the TCL test function "translate_selftest".
  22623. ** It checks that the primitives for serializing and deserializing
  22624. ** characters in each encoding are inverses of each other.
  22625. */
  22626. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  22627. unsigned int i, t;
  22628. unsigned char zBuf[20];
  22629. unsigned char *z;
  22630. int n;
  22631. unsigned int c;
  22632. for(i=0; i<0x00110000; i++){
  22633. z = zBuf;
  22634. WRITE_UTF8(z, i);
  22635. n = (int)(z-zBuf);
  22636. assert( n>0 && n<=4 );
  22637. z[0] = 0;
  22638. z = zBuf;
  22639. c = sqlite3Utf8Read((const u8**)&z);
  22640. t = i;
  22641. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  22642. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  22643. assert( c==t );
  22644. assert( (z-zBuf)==n );
  22645. }
  22646. for(i=0; i<0x00110000; i++){
  22647. if( i>=0xD800 && i<0xE000 ) continue;
  22648. z = zBuf;
  22649. WRITE_UTF16LE(z, i);
  22650. n = (int)(z-zBuf);
  22651. assert( n>0 && n<=4 );
  22652. z[0] = 0;
  22653. z = zBuf;
  22654. READ_UTF16LE(z, 1, c);
  22655. assert( c==i );
  22656. assert( (z-zBuf)==n );
  22657. }
  22658. for(i=0; i<0x00110000; i++){
  22659. if( i>=0xD800 && i<0xE000 ) continue;
  22660. z = zBuf;
  22661. WRITE_UTF16BE(z, i);
  22662. n = (int)(z-zBuf);
  22663. assert( n>0 && n<=4 );
  22664. z[0] = 0;
  22665. z = zBuf;
  22666. READ_UTF16BE(z, 1, c);
  22667. assert( c==i );
  22668. assert( (z-zBuf)==n );
  22669. }
  22670. }
  22671. #endif /* SQLITE_TEST */
  22672. #endif /* SQLITE_OMIT_UTF16 */
  22673. /************** End of utf.c *************************************************/
  22674. /************** Begin file util.c ********************************************/
  22675. /*
  22676. ** 2001 September 15
  22677. **
  22678. ** The author disclaims copyright to this source code. In place of
  22679. ** a legal notice, here is a blessing:
  22680. **
  22681. ** May you do good and not evil.
  22682. ** May you find forgiveness for yourself and forgive others.
  22683. ** May you share freely, never taking more than you give.
  22684. **
  22685. *************************************************************************
  22686. ** Utility functions used throughout sqlite.
  22687. **
  22688. ** This file contains functions for allocating memory, comparing
  22689. ** strings, and stuff like that.
  22690. **
  22691. */
  22692. /* #include "sqliteInt.h" */
  22693. /* #include <stdarg.h> */
  22694. #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
  22695. # include <math.h>
  22696. #endif
  22697. /*
  22698. ** Routine needed to support the testcase() macro.
  22699. */
  22700. #ifdef SQLITE_COVERAGE_TEST
  22701. SQLITE_PRIVATE void sqlite3Coverage(int x){
  22702. static unsigned dummy = 0;
  22703. dummy += (unsigned)x;
  22704. }
  22705. #endif
  22706. /*
  22707. ** Give a callback to the test harness that can be used to simulate faults
  22708. ** in places where it is difficult or expensive to do so purely by means
  22709. ** of inputs.
  22710. **
  22711. ** The intent of the integer argument is to let the fault simulator know
  22712. ** which of multiple sqlite3FaultSim() calls has been hit.
  22713. **
  22714. ** Return whatever integer value the test callback returns, or return
  22715. ** SQLITE_OK if no test callback is installed.
  22716. */
  22717. #ifndef SQLITE_OMIT_BUILTIN_TEST
  22718. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  22719. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  22720. return xCallback ? xCallback(iTest) : SQLITE_OK;
  22721. }
  22722. #endif
  22723. #ifndef SQLITE_OMIT_FLOATING_POINT
  22724. /*
  22725. ** Return true if the floating point value is Not a Number (NaN).
  22726. **
  22727. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  22728. ** Otherwise, we have our own implementation that works on most systems.
  22729. */
  22730. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  22731. int rc; /* The value return */
  22732. #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
  22733. /*
  22734. ** Systems that support the isnan() library function should probably
  22735. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  22736. ** found that many systems do not have a working isnan() function so
  22737. ** this implementation is provided as an alternative.
  22738. **
  22739. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  22740. ** On the other hand, the use of -ffast-math comes with the following
  22741. ** warning:
  22742. **
  22743. ** This option [-ffast-math] should never be turned on by any
  22744. ** -O option since it can result in incorrect output for programs
  22745. ** which depend on an exact implementation of IEEE or ISO
  22746. ** rules/specifications for math functions.
  22747. **
  22748. ** Under MSVC, this NaN test may fail if compiled with a floating-
  22749. ** point precision mode other than /fp:precise. From the MSDN
  22750. ** documentation:
  22751. **
  22752. ** The compiler [with /fp:precise] will properly handle comparisons
  22753. ** involving NaN. For example, x != x evaluates to true if x is NaN
  22754. ** ...
  22755. */
  22756. #ifdef __FAST_MATH__
  22757. # error SQLite will not work correctly with the -ffast-math option of GCC.
  22758. #endif
  22759. volatile double y = x;
  22760. volatile double z = y;
  22761. rc = (y!=z);
  22762. #else /* if HAVE_ISNAN */
  22763. rc = isnan(x);
  22764. #endif /* HAVE_ISNAN */
  22765. testcase( rc );
  22766. return rc;
  22767. }
  22768. #endif /* SQLITE_OMIT_FLOATING_POINT */
  22769. /*
  22770. ** Compute a string length that is limited to what can be stored in
  22771. ** lower 30 bits of a 32-bit signed integer.
  22772. **
  22773. ** The value returned will never be negative. Nor will it ever be greater
  22774. ** than the actual length of the string. For very long strings (greater
  22775. ** than 1GiB) the value returned might be less than the true string length.
  22776. */
  22777. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  22778. if( z==0 ) return 0;
  22779. return 0x3fffffff & (int)strlen(z);
  22780. }
  22781. /*
  22782. ** Set the current error code to err_code and clear any prior error message.
  22783. */
  22784. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  22785. assert( db!=0 );
  22786. db->errCode = err_code;
  22787. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  22788. }
  22789. /*
  22790. ** Set the most recent error code and error string for the sqlite
  22791. ** handle "db". The error code is set to "err_code".
  22792. **
  22793. ** If it is not NULL, string zFormat specifies the format of the
  22794. ** error string in the style of the printf functions: The following
  22795. ** format characters are allowed:
  22796. **
  22797. ** %s Insert a string
  22798. ** %z A string that should be freed after use
  22799. ** %d Insert an integer
  22800. ** %T Insert a token
  22801. ** %S Insert the first element of a SrcList
  22802. **
  22803. ** zFormat and any string tokens that follow it are assumed to be
  22804. ** encoded in UTF-8.
  22805. **
  22806. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  22807. ** should be called with err_code set to SQLITE_OK and zFormat set
  22808. ** to NULL.
  22809. */
  22810. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  22811. assert( db!=0 );
  22812. db->errCode = err_code;
  22813. if( zFormat==0 ){
  22814. sqlite3Error(db, err_code);
  22815. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  22816. char *z;
  22817. va_list ap;
  22818. va_start(ap, zFormat);
  22819. z = sqlite3VMPrintf(db, zFormat, ap);
  22820. va_end(ap);
  22821. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  22822. }
  22823. }
  22824. /*
  22825. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  22826. ** The following formatting characters are allowed:
  22827. **
  22828. ** %s Insert a string
  22829. ** %z A string that should be freed after use
  22830. ** %d Insert an integer
  22831. ** %T Insert a token
  22832. ** %S Insert the first element of a SrcList
  22833. **
  22834. ** This function should be used to report any error that occurs while
  22835. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  22836. ** last thing the sqlite3_prepare() function does is copy the error
  22837. ** stored by this function into the database handle using sqlite3Error().
  22838. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  22839. ** during statement execution (sqlite3_step() etc.).
  22840. */
  22841. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  22842. char *zMsg;
  22843. va_list ap;
  22844. sqlite3 *db = pParse->db;
  22845. va_start(ap, zFormat);
  22846. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  22847. va_end(ap);
  22848. if( db->suppressErr ){
  22849. sqlite3DbFree(db, zMsg);
  22850. }else{
  22851. pParse->nErr++;
  22852. sqlite3DbFree(db, pParse->zErrMsg);
  22853. pParse->zErrMsg = zMsg;
  22854. pParse->rc = SQLITE_ERROR;
  22855. }
  22856. }
  22857. /*
  22858. ** Convert an SQL-style quoted string into a normal string by removing
  22859. ** the quote characters. The conversion is done in-place. If the
  22860. ** input does not begin with a quote character, then this routine
  22861. ** is a no-op.
  22862. **
  22863. ** The input string must be zero-terminated. A new zero-terminator
  22864. ** is added to the dequoted string.
  22865. **
  22866. ** The return value is -1 if no dequoting occurs or the length of the
  22867. ** dequoted string, exclusive of the zero terminator, if dequoting does
  22868. ** occur.
  22869. **
  22870. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  22871. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  22872. ** "a-b-c".
  22873. */
  22874. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  22875. char quote;
  22876. int i, j;
  22877. if( z==0 ) return -1;
  22878. quote = z[0];
  22879. switch( quote ){
  22880. case '\'': break;
  22881. case '"': break;
  22882. case '`': break; /* For MySQL compatibility */
  22883. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  22884. default: return -1;
  22885. }
  22886. for(i=1, j=0;; i++){
  22887. assert( z[i] );
  22888. if( z[i]==quote ){
  22889. if( z[i+1]==quote ){
  22890. z[j++] = quote;
  22891. i++;
  22892. }else{
  22893. break;
  22894. }
  22895. }else{
  22896. z[j++] = z[i];
  22897. }
  22898. }
  22899. z[j] = 0;
  22900. return j;
  22901. }
  22902. /* Convenient short-hand */
  22903. #define UpperToLower sqlite3UpperToLower
  22904. /*
  22905. ** Some systems have stricmp(). Others have strcasecmp(). Because
  22906. ** there is no consistency, we will define our own.
  22907. **
  22908. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  22909. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  22910. ** the contents of two buffers containing UTF-8 strings in a
  22911. ** case-independent fashion, using the same definition of "case
  22912. ** independence" that SQLite uses internally when comparing identifiers.
  22913. */
  22914. SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
  22915. register unsigned char *a, *b;
  22916. if( zLeft==0 ){
  22917. return zRight ? -1 : 0;
  22918. }else if( zRight==0 ){
  22919. return 1;
  22920. }
  22921. a = (unsigned char *)zLeft;
  22922. b = (unsigned char *)zRight;
  22923. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  22924. return UpperToLower[*a] - UpperToLower[*b];
  22925. }
  22926. SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  22927. register unsigned char *a, *b;
  22928. if( zLeft==0 ){
  22929. return zRight ? -1 : 0;
  22930. }else if( zRight==0 ){
  22931. return 1;
  22932. }
  22933. a = (unsigned char *)zLeft;
  22934. b = (unsigned char *)zRight;
  22935. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  22936. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  22937. }
  22938. /*
  22939. ** The string z[] is an text representation of a real number.
  22940. ** Convert this string to a double and write it into *pResult.
  22941. **
  22942. ** The string z[] is length bytes in length (bytes, not characters) and
  22943. ** uses the encoding enc. The string is not necessarily zero-terminated.
  22944. **
  22945. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  22946. ** if the string is empty or contains extraneous text. Valid numbers
  22947. ** are in one of these formats:
  22948. **
  22949. ** [+-]digits[E[+-]digits]
  22950. ** [+-]digits.[digits][E[+-]digits]
  22951. ** [+-].digits[E[+-]digits]
  22952. **
  22953. ** Leading and trailing whitespace is ignored for the purpose of determining
  22954. ** validity.
  22955. **
  22956. ** If some prefix of the input string is a valid number, this routine
  22957. ** returns FALSE but it still converts the prefix and writes the result
  22958. ** into *pResult.
  22959. */
  22960. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  22961. #ifndef SQLITE_OMIT_FLOATING_POINT
  22962. int incr;
  22963. const char *zEnd = z + length;
  22964. /* sign * significand * (10 ^ (esign * exponent)) */
  22965. int sign = 1; /* sign of significand */
  22966. i64 s = 0; /* significand */
  22967. int d = 0; /* adjust exponent for shifting decimal point */
  22968. int esign = 1; /* sign of exponent */
  22969. int e = 0; /* exponent */
  22970. int eValid = 1; /* True exponent is either not used or is well-formed */
  22971. double result;
  22972. int nDigits = 0;
  22973. int nonNum = 0;
  22974. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  22975. *pResult = 0.0; /* Default return value, in case of an error */
  22976. if( enc==SQLITE_UTF8 ){
  22977. incr = 1;
  22978. }else{
  22979. int i;
  22980. incr = 2;
  22981. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  22982. for(i=3-enc; i<length && z[i]==0; i+=2){}
  22983. nonNum = i<length;
  22984. zEnd = z+i+enc-3;
  22985. z += (enc&1);
  22986. }
  22987. /* skip leading spaces */
  22988. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  22989. if( z>=zEnd ) return 0;
  22990. /* get sign of significand */
  22991. if( *z=='-' ){
  22992. sign = -1;
  22993. z+=incr;
  22994. }else if( *z=='+' ){
  22995. z+=incr;
  22996. }
  22997. /* skip leading zeroes */
  22998. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  22999. /* copy max significant digits to significand */
  23000. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  23001. s = s*10 + (*z - '0');
  23002. z+=incr, nDigits++;
  23003. }
  23004. /* skip non-significant significand digits
  23005. ** (increase exponent by d to shift decimal left) */
  23006. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  23007. if( z>=zEnd ) goto do_atof_calc;
  23008. /* if decimal point is present */
  23009. if( *z=='.' ){
  23010. z+=incr;
  23011. /* copy digits from after decimal to significand
  23012. ** (decrease exponent by d to shift decimal right) */
  23013. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  23014. s = s*10 + (*z - '0');
  23015. z+=incr, nDigits++, d--;
  23016. }
  23017. /* skip non-significant digits */
  23018. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  23019. }
  23020. if( z>=zEnd ) goto do_atof_calc;
  23021. /* if exponent is present */
  23022. if( *z=='e' || *z=='E' ){
  23023. z+=incr;
  23024. eValid = 0;
  23025. if( z>=zEnd ) goto do_atof_calc;
  23026. /* get sign of exponent */
  23027. if( *z=='-' ){
  23028. esign = -1;
  23029. z+=incr;
  23030. }else if( *z=='+' ){
  23031. z+=incr;
  23032. }
  23033. /* copy digits to exponent */
  23034. while( z<zEnd && sqlite3Isdigit(*z) ){
  23035. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  23036. z+=incr;
  23037. eValid = 1;
  23038. }
  23039. }
  23040. /* skip trailing spaces */
  23041. if( nDigits && eValid ){
  23042. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  23043. }
  23044. do_atof_calc:
  23045. /* adjust exponent by d, and update sign */
  23046. e = (e*esign) + d;
  23047. if( e<0 ) {
  23048. esign = -1;
  23049. e *= -1;
  23050. } else {
  23051. esign = 1;
  23052. }
  23053. /* if 0 significand */
  23054. if( !s ) {
  23055. /* In the IEEE 754 standard, zero is signed.
  23056. ** Add the sign if we've seen at least one digit */
  23057. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  23058. } else {
  23059. /* attempt to reduce exponent */
  23060. if( esign>0 ){
  23061. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  23062. }else{
  23063. while( !(s%10) && e>0 ) e--,s/=10;
  23064. }
  23065. /* adjust the sign of significand */
  23066. s = sign<0 ? -s : s;
  23067. /* if exponent, scale significand as appropriate
  23068. ** and store in result. */
  23069. if( e ){
  23070. LONGDOUBLE_TYPE scale = 1.0;
  23071. /* attempt to handle extremely small/large numbers better */
  23072. if( e>307 && e<342 ){
  23073. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  23074. if( esign<0 ){
  23075. result = s / scale;
  23076. result /= 1.0e+308;
  23077. }else{
  23078. result = s * scale;
  23079. result *= 1.0e+308;
  23080. }
  23081. }else if( e>=342 ){
  23082. if( esign<0 ){
  23083. result = 0.0*s;
  23084. }else{
  23085. result = 1e308*1e308*s; /* Infinity */
  23086. }
  23087. }else{
  23088. /* 1.0e+22 is the largest power of 10 than can be
  23089. ** represented exactly. */
  23090. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  23091. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  23092. if( esign<0 ){
  23093. result = s / scale;
  23094. }else{
  23095. result = s * scale;
  23096. }
  23097. }
  23098. } else {
  23099. result = (double)s;
  23100. }
  23101. }
  23102. /* store the result */
  23103. *pResult = result;
  23104. /* return true if number and no extra non-whitespace chracters after */
  23105. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  23106. #else
  23107. return !sqlite3Atoi64(z, pResult, length, enc);
  23108. #endif /* SQLITE_OMIT_FLOATING_POINT */
  23109. }
  23110. /*
  23111. ** Compare the 19-character string zNum against the text representation
  23112. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  23113. ** if zNum is less than, equal to, or greater than the string.
  23114. ** Note that zNum must contain exactly 19 characters.
  23115. **
  23116. ** Unlike memcmp() this routine is guaranteed to return the difference
  23117. ** in the values of the last digit if the only difference is in the
  23118. ** last digit. So, for example,
  23119. **
  23120. ** compare2pow63("9223372036854775800", 1)
  23121. **
  23122. ** will return -8.
  23123. */
  23124. static int compare2pow63(const char *zNum, int incr){
  23125. int c = 0;
  23126. int i;
  23127. /* 012345678901234567 */
  23128. const char *pow63 = "922337203685477580";
  23129. for(i=0; c==0 && i<18; i++){
  23130. c = (zNum[i*incr]-pow63[i])*10;
  23131. }
  23132. if( c==0 ){
  23133. c = zNum[18*incr] - '8';
  23134. testcase( c==(-1) );
  23135. testcase( c==0 );
  23136. testcase( c==(+1) );
  23137. }
  23138. return c;
  23139. }
  23140. /*
  23141. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  23142. ** routine does *not* accept hexadecimal notation.
  23143. **
  23144. ** If the zNum value is representable as a 64-bit twos-complement
  23145. ** integer, then write that value into *pNum and return 0.
  23146. **
  23147. ** If zNum is exactly 9223372036854775808, return 2. This special
  23148. ** case is broken out because while 9223372036854775808 cannot be a
  23149. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  23150. **
  23151. ** If zNum is too big for a 64-bit integer and is not
  23152. ** 9223372036854775808 or if zNum contains any non-numeric text,
  23153. ** then return 1.
  23154. **
  23155. ** length is the number of bytes in the string (bytes, not characters).
  23156. ** The string is not necessarily zero-terminated. The encoding is
  23157. ** given by enc.
  23158. */
  23159. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  23160. int incr;
  23161. u64 u = 0;
  23162. int neg = 0; /* assume positive */
  23163. int i;
  23164. int c = 0;
  23165. int nonNum = 0;
  23166. const char *zStart;
  23167. const char *zEnd = zNum + length;
  23168. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  23169. if( enc==SQLITE_UTF8 ){
  23170. incr = 1;
  23171. }else{
  23172. incr = 2;
  23173. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  23174. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  23175. nonNum = i<length;
  23176. zEnd = zNum+i+enc-3;
  23177. zNum += (enc&1);
  23178. }
  23179. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  23180. if( zNum<zEnd ){
  23181. if( *zNum=='-' ){
  23182. neg = 1;
  23183. zNum+=incr;
  23184. }else if( *zNum=='+' ){
  23185. zNum+=incr;
  23186. }
  23187. }
  23188. zStart = zNum;
  23189. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  23190. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  23191. u = u*10 + c - '0';
  23192. }
  23193. if( u>LARGEST_INT64 ){
  23194. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  23195. }else if( neg ){
  23196. *pNum = -(i64)u;
  23197. }else{
  23198. *pNum = (i64)u;
  23199. }
  23200. testcase( i==18 );
  23201. testcase( i==19 );
  23202. testcase( i==20 );
  23203. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  23204. /* zNum is empty or contains non-numeric text or is longer
  23205. ** than 19 digits (thus guaranteeing that it is too large) */
  23206. return 1;
  23207. }else if( i<19*incr ){
  23208. /* Less than 19 digits, so we know that it fits in 64 bits */
  23209. assert( u<=LARGEST_INT64 );
  23210. return 0;
  23211. }else{
  23212. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  23213. c = compare2pow63(zNum, incr);
  23214. if( c<0 ){
  23215. /* zNum is less than 9223372036854775808 so it fits */
  23216. assert( u<=LARGEST_INT64 );
  23217. return 0;
  23218. }else if( c>0 ){
  23219. /* zNum is greater than 9223372036854775808 so it overflows */
  23220. return 1;
  23221. }else{
  23222. /* zNum is exactly 9223372036854775808. Fits if negative. The
  23223. ** special case 2 overflow if positive */
  23224. assert( u-1==LARGEST_INT64 );
  23225. return neg ? 0 : 2;
  23226. }
  23227. }
  23228. }
  23229. /*
  23230. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  23231. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  23232. ** whereas sqlite3Atoi64() does not.
  23233. **
  23234. ** Returns:
  23235. **
  23236. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  23237. ** 1 Integer too large for a 64-bit signed integer or is malformed
  23238. ** 2 Special case of 9223372036854775808
  23239. */
  23240. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  23241. #ifndef SQLITE_OMIT_HEX_INTEGER
  23242. if( z[0]=='0'
  23243. && (z[1]=='x' || z[1]=='X')
  23244. && sqlite3Isxdigit(z[2])
  23245. ){
  23246. u64 u = 0;
  23247. int i, k;
  23248. for(i=2; z[i]=='0'; i++){}
  23249. for(k=i; sqlite3Isxdigit(z[k]); k++){
  23250. u = u*16 + sqlite3HexToInt(z[k]);
  23251. }
  23252. memcpy(pOut, &u, 8);
  23253. return (z[k]==0 && k-i<=16) ? 0 : 1;
  23254. }else
  23255. #endif /* SQLITE_OMIT_HEX_INTEGER */
  23256. {
  23257. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  23258. }
  23259. }
  23260. /*
  23261. ** If zNum represents an integer that will fit in 32-bits, then set
  23262. ** *pValue to that integer and return true. Otherwise return false.
  23263. **
  23264. ** This routine accepts both decimal and hexadecimal notation for integers.
  23265. **
  23266. ** Any non-numeric characters that following zNum are ignored.
  23267. ** This is different from sqlite3Atoi64() which requires the
  23268. ** input number to be zero-terminated.
  23269. */
  23270. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  23271. sqlite_int64 v = 0;
  23272. int i, c;
  23273. int neg = 0;
  23274. if( zNum[0]=='-' ){
  23275. neg = 1;
  23276. zNum++;
  23277. }else if( zNum[0]=='+' ){
  23278. zNum++;
  23279. }
  23280. #ifndef SQLITE_OMIT_HEX_INTEGER
  23281. else if( zNum[0]=='0'
  23282. && (zNum[1]=='x' || zNum[1]=='X')
  23283. && sqlite3Isxdigit(zNum[2])
  23284. ){
  23285. u32 u = 0;
  23286. zNum += 2;
  23287. while( zNum[0]=='0' ) zNum++;
  23288. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  23289. u = u*16 + sqlite3HexToInt(zNum[i]);
  23290. }
  23291. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  23292. memcpy(pValue, &u, 4);
  23293. return 1;
  23294. }else{
  23295. return 0;
  23296. }
  23297. }
  23298. #endif
  23299. while( zNum[0]=='0' ) zNum++;
  23300. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  23301. v = v*10 + c;
  23302. }
  23303. /* The longest decimal representation of a 32 bit integer is 10 digits:
  23304. **
  23305. ** 1234567890
  23306. ** 2^31 -> 2147483648
  23307. */
  23308. testcase( i==10 );
  23309. if( i>10 ){
  23310. return 0;
  23311. }
  23312. testcase( v-neg==2147483647 );
  23313. if( v-neg>2147483647 ){
  23314. return 0;
  23315. }
  23316. if( neg ){
  23317. v = -v;
  23318. }
  23319. *pValue = (int)v;
  23320. return 1;
  23321. }
  23322. /*
  23323. ** Return a 32-bit integer value extracted from a string. If the
  23324. ** string is not an integer, just return 0.
  23325. */
  23326. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  23327. int x = 0;
  23328. if( z ) sqlite3GetInt32(z, &x);
  23329. return x;
  23330. }
  23331. /*
  23332. ** The variable-length integer encoding is as follows:
  23333. **
  23334. ** KEY:
  23335. ** A = 0xxxxxxx 7 bits of data and one flag bit
  23336. ** B = 1xxxxxxx 7 bits of data and one flag bit
  23337. ** C = xxxxxxxx 8 bits of data
  23338. **
  23339. ** 7 bits - A
  23340. ** 14 bits - BA
  23341. ** 21 bits - BBA
  23342. ** 28 bits - BBBA
  23343. ** 35 bits - BBBBA
  23344. ** 42 bits - BBBBBA
  23345. ** 49 bits - BBBBBBA
  23346. ** 56 bits - BBBBBBBA
  23347. ** 64 bits - BBBBBBBBC
  23348. */
  23349. /*
  23350. ** Write a 64-bit variable-length integer to memory starting at p[0].
  23351. ** The length of data write will be between 1 and 9 bytes. The number
  23352. ** of bytes written is returned.
  23353. **
  23354. ** A variable-length integer consists of the lower 7 bits of each byte
  23355. ** for all bytes that have the 8th bit set and one byte with the 8th
  23356. ** bit clear. Except, if we get to the 9th byte, it stores the full
  23357. ** 8 bits and is the last byte.
  23358. */
  23359. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  23360. int i, j, n;
  23361. u8 buf[10];
  23362. if( v & (((u64)0xff000000)<<32) ){
  23363. p[8] = (u8)v;
  23364. v >>= 8;
  23365. for(i=7; i>=0; i--){
  23366. p[i] = (u8)((v & 0x7f) | 0x80);
  23367. v >>= 7;
  23368. }
  23369. return 9;
  23370. }
  23371. n = 0;
  23372. do{
  23373. buf[n++] = (u8)((v & 0x7f) | 0x80);
  23374. v >>= 7;
  23375. }while( v!=0 );
  23376. buf[0] &= 0x7f;
  23377. assert( n<=9 );
  23378. for(i=0, j=n-1; j>=0; j--, i++){
  23379. p[i] = buf[j];
  23380. }
  23381. return n;
  23382. }
  23383. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  23384. if( v<=0x7f ){
  23385. p[0] = v&0x7f;
  23386. return 1;
  23387. }
  23388. if( v<=0x3fff ){
  23389. p[0] = ((v>>7)&0x7f)|0x80;
  23390. p[1] = v&0x7f;
  23391. return 2;
  23392. }
  23393. return putVarint64(p,v);
  23394. }
  23395. /*
  23396. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  23397. ** are defined here rather than simply putting the constant expressions
  23398. ** inline in order to work around bugs in the RVT compiler.
  23399. **
  23400. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  23401. **
  23402. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  23403. */
  23404. #define SLOT_2_0 0x001fc07f
  23405. #define SLOT_4_2_0 0xf01fc07f
  23406. /*
  23407. ** Read a 64-bit variable-length integer from memory starting at p[0].
  23408. ** Return the number of bytes read. The value is stored in *v.
  23409. */
  23410. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  23411. u32 a,b,s;
  23412. a = *p;
  23413. /* a: p0 (unmasked) */
  23414. if (!(a&0x80))
  23415. {
  23416. *v = a;
  23417. return 1;
  23418. }
  23419. p++;
  23420. b = *p;
  23421. /* b: p1 (unmasked) */
  23422. if (!(b&0x80))
  23423. {
  23424. a &= 0x7f;
  23425. a = a<<7;
  23426. a |= b;
  23427. *v = a;
  23428. return 2;
  23429. }
  23430. /* Verify that constants are precomputed correctly */
  23431. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  23432. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  23433. p++;
  23434. a = a<<14;
  23435. a |= *p;
  23436. /* a: p0<<14 | p2 (unmasked) */
  23437. if (!(a&0x80))
  23438. {
  23439. a &= SLOT_2_0;
  23440. b &= 0x7f;
  23441. b = b<<7;
  23442. a |= b;
  23443. *v = a;
  23444. return 3;
  23445. }
  23446. /* CSE1 from below */
  23447. a &= SLOT_2_0;
  23448. p++;
  23449. b = b<<14;
  23450. b |= *p;
  23451. /* b: p1<<14 | p3 (unmasked) */
  23452. if (!(b&0x80))
  23453. {
  23454. b &= SLOT_2_0;
  23455. /* moved CSE1 up */
  23456. /* a &= (0x7f<<14)|(0x7f); */
  23457. a = a<<7;
  23458. a |= b;
  23459. *v = a;
  23460. return 4;
  23461. }
  23462. /* a: p0<<14 | p2 (masked) */
  23463. /* b: p1<<14 | p3 (unmasked) */
  23464. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  23465. /* moved CSE1 up */
  23466. /* a &= (0x7f<<14)|(0x7f); */
  23467. b &= SLOT_2_0;
  23468. s = a;
  23469. /* s: p0<<14 | p2 (masked) */
  23470. p++;
  23471. a = a<<14;
  23472. a |= *p;
  23473. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  23474. if (!(a&0x80))
  23475. {
  23476. /* we can skip these cause they were (effectively) done above in calc'ing s */
  23477. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  23478. /* b &= (0x7f<<14)|(0x7f); */
  23479. b = b<<7;
  23480. a |= b;
  23481. s = s>>18;
  23482. *v = ((u64)s)<<32 | a;
  23483. return 5;
  23484. }
  23485. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  23486. s = s<<7;
  23487. s |= b;
  23488. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  23489. p++;
  23490. b = b<<14;
  23491. b |= *p;
  23492. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  23493. if (!(b&0x80))
  23494. {
  23495. /* we can skip this cause it was (effectively) done above in calc'ing s */
  23496. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  23497. a &= SLOT_2_0;
  23498. a = a<<7;
  23499. a |= b;
  23500. s = s>>18;
  23501. *v = ((u64)s)<<32 | a;
  23502. return 6;
  23503. }
  23504. p++;
  23505. a = a<<14;
  23506. a |= *p;
  23507. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  23508. if (!(a&0x80))
  23509. {
  23510. a &= SLOT_4_2_0;
  23511. b &= SLOT_2_0;
  23512. b = b<<7;
  23513. a |= b;
  23514. s = s>>11;
  23515. *v = ((u64)s)<<32 | a;
  23516. return 7;
  23517. }
  23518. /* CSE2 from below */
  23519. a &= SLOT_2_0;
  23520. p++;
  23521. b = b<<14;
  23522. b |= *p;
  23523. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  23524. if (!(b&0x80))
  23525. {
  23526. b &= SLOT_4_2_0;
  23527. /* moved CSE2 up */
  23528. /* a &= (0x7f<<14)|(0x7f); */
  23529. a = a<<7;
  23530. a |= b;
  23531. s = s>>4;
  23532. *v = ((u64)s)<<32 | a;
  23533. return 8;
  23534. }
  23535. p++;
  23536. a = a<<15;
  23537. a |= *p;
  23538. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  23539. /* moved CSE2 up */
  23540. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  23541. b &= SLOT_2_0;
  23542. b = b<<8;
  23543. a |= b;
  23544. s = s<<4;
  23545. b = p[-4];
  23546. b &= 0x7f;
  23547. b = b>>3;
  23548. s |= b;
  23549. *v = ((u64)s)<<32 | a;
  23550. return 9;
  23551. }
  23552. /*
  23553. ** Read a 32-bit variable-length integer from memory starting at p[0].
  23554. ** Return the number of bytes read. The value is stored in *v.
  23555. **
  23556. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  23557. ** integer, then set *v to 0xffffffff.
  23558. **
  23559. ** A MACRO version, getVarint32, is provided which inlines the
  23560. ** single-byte case. All code should use the MACRO version as
  23561. ** this function assumes the single-byte case has already been handled.
  23562. */
  23563. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  23564. u32 a,b;
  23565. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  23566. ** by the getVarin32() macro */
  23567. a = *p;
  23568. /* a: p0 (unmasked) */
  23569. #ifndef getVarint32
  23570. if (!(a&0x80))
  23571. {
  23572. /* Values between 0 and 127 */
  23573. *v = a;
  23574. return 1;
  23575. }
  23576. #endif
  23577. /* The 2-byte case */
  23578. p++;
  23579. b = *p;
  23580. /* b: p1 (unmasked) */
  23581. if (!(b&0x80))
  23582. {
  23583. /* Values between 128 and 16383 */
  23584. a &= 0x7f;
  23585. a = a<<7;
  23586. *v = a | b;
  23587. return 2;
  23588. }
  23589. /* The 3-byte case */
  23590. p++;
  23591. a = a<<14;
  23592. a |= *p;
  23593. /* a: p0<<14 | p2 (unmasked) */
  23594. if (!(a&0x80))
  23595. {
  23596. /* Values between 16384 and 2097151 */
  23597. a &= (0x7f<<14)|(0x7f);
  23598. b &= 0x7f;
  23599. b = b<<7;
  23600. *v = a | b;
  23601. return 3;
  23602. }
  23603. /* A 32-bit varint is used to store size information in btrees.
  23604. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  23605. ** A 3-byte varint is sufficient, for example, to record the size
  23606. ** of a 1048569-byte BLOB or string.
  23607. **
  23608. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  23609. ** rare larger cases can be handled by the slower 64-bit varint
  23610. ** routine.
  23611. */
  23612. #if 1
  23613. {
  23614. u64 v64;
  23615. u8 n;
  23616. p -= 2;
  23617. n = sqlite3GetVarint(p, &v64);
  23618. assert( n>3 && n<=9 );
  23619. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  23620. *v = 0xffffffff;
  23621. }else{
  23622. *v = (u32)v64;
  23623. }
  23624. return n;
  23625. }
  23626. #else
  23627. /* For following code (kept for historical record only) shows an
  23628. ** unrolling for the 3- and 4-byte varint cases. This code is
  23629. ** slightly faster, but it is also larger and much harder to test.
  23630. */
  23631. p++;
  23632. b = b<<14;
  23633. b |= *p;
  23634. /* b: p1<<14 | p3 (unmasked) */
  23635. if (!(b&0x80))
  23636. {
  23637. /* Values between 2097152 and 268435455 */
  23638. b &= (0x7f<<14)|(0x7f);
  23639. a &= (0x7f<<14)|(0x7f);
  23640. a = a<<7;
  23641. *v = a | b;
  23642. return 4;
  23643. }
  23644. p++;
  23645. a = a<<14;
  23646. a |= *p;
  23647. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  23648. if (!(a&0x80))
  23649. {
  23650. /* Values between 268435456 and 34359738367 */
  23651. a &= SLOT_4_2_0;
  23652. b &= SLOT_4_2_0;
  23653. b = b<<7;
  23654. *v = a | b;
  23655. return 5;
  23656. }
  23657. /* We can only reach this point when reading a corrupt database
  23658. ** file. In that case we are not in any hurry. Use the (relatively
  23659. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  23660. ** value. */
  23661. {
  23662. u64 v64;
  23663. u8 n;
  23664. p -= 4;
  23665. n = sqlite3GetVarint(p, &v64);
  23666. assert( n>5 && n<=9 );
  23667. *v = (u32)v64;
  23668. return n;
  23669. }
  23670. #endif
  23671. }
  23672. /*
  23673. ** Return the number of bytes that will be needed to store the given
  23674. ** 64-bit integer.
  23675. */
  23676. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  23677. int i = 0;
  23678. do{
  23679. i++;
  23680. v >>= 7;
  23681. }while( v!=0 && ALWAYS(i<9) );
  23682. return i;
  23683. }
  23684. /*
  23685. ** Read or write a four-byte big-endian integer value.
  23686. */
  23687. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  23688. #if SQLITE_BYTEORDER==4321
  23689. u32 x;
  23690. memcpy(&x,p,4);
  23691. return x;
  23692. #elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
  23693. u32 x;
  23694. memcpy(&x,p,4);
  23695. return __builtin_bswap32(x);
  23696. #elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
  23697. u32 x;
  23698. memcpy(&x,p,4);
  23699. return _byteswap_ulong(x);
  23700. #else
  23701. testcase( p[0]&0x80 );
  23702. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  23703. #endif
  23704. }
  23705. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  23706. #if SQLITE_BYTEORDER==4321
  23707. memcpy(p,&v,4);
  23708. #elif SQLITE_BYTEORDER==1234 && defined(__GNUC__) && GCC_VERSION>=4003000
  23709. u32 x = __builtin_bswap32(v);
  23710. memcpy(p,&x,4);
  23711. #elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
  23712. u32 x = _byteswap_ulong(v);
  23713. memcpy(p,&x,4);
  23714. #else
  23715. p[0] = (u8)(v>>24);
  23716. p[1] = (u8)(v>>16);
  23717. p[2] = (u8)(v>>8);
  23718. p[3] = (u8)v;
  23719. #endif
  23720. }
  23721. /*
  23722. ** Translate a single byte of Hex into an integer.
  23723. ** This routine only works if h really is a valid hexadecimal
  23724. ** character: 0..9a..fA..F
  23725. */
  23726. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  23727. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  23728. #ifdef SQLITE_ASCII
  23729. h += 9*(1&(h>>6));
  23730. #endif
  23731. #ifdef SQLITE_EBCDIC
  23732. h += 9*(1&~(h>>4));
  23733. #endif
  23734. return (u8)(h & 0xf);
  23735. }
  23736. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  23737. /*
  23738. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  23739. ** value. Return a pointer to its binary value. Space to hold the
  23740. ** binary value has been obtained from malloc and must be freed by
  23741. ** the calling routine.
  23742. */
  23743. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  23744. char *zBlob;
  23745. int i;
  23746. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  23747. n--;
  23748. if( zBlob ){
  23749. for(i=0; i<n; i+=2){
  23750. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  23751. }
  23752. zBlob[i/2] = 0;
  23753. }
  23754. return zBlob;
  23755. }
  23756. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  23757. /*
  23758. ** Log an error that is an API call on a connection pointer that should
  23759. ** not have been used. The "type" of connection pointer is given as the
  23760. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  23761. */
  23762. static void logBadConnection(const char *zType){
  23763. sqlite3_log(SQLITE_MISUSE,
  23764. "API call with %s database connection pointer",
  23765. zType
  23766. );
  23767. }
  23768. /*
  23769. ** Check to make sure we have a valid db pointer. This test is not
  23770. ** foolproof but it does provide some measure of protection against
  23771. ** misuse of the interface such as passing in db pointers that are
  23772. ** NULL or which have been previously closed. If this routine returns
  23773. ** 1 it means that the db pointer is valid and 0 if it should not be
  23774. ** dereferenced for any reason. The calling function should invoke
  23775. ** SQLITE_MISUSE immediately.
  23776. **
  23777. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  23778. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  23779. ** open properly and is not fit for general use but which can be
  23780. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  23781. */
  23782. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  23783. u32 magic;
  23784. if( db==0 ){
  23785. logBadConnection("NULL");
  23786. return 0;
  23787. }
  23788. magic = db->magic;
  23789. if( magic!=SQLITE_MAGIC_OPEN ){
  23790. if( sqlite3SafetyCheckSickOrOk(db) ){
  23791. testcase( sqlite3GlobalConfig.xLog!=0 );
  23792. logBadConnection("unopened");
  23793. }
  23794. return 0;
  23795. }else{
  23796. return 1;
  23797. }
  23798. }
  23799. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  23800. u32 magic;
  23801. magic = db->magic;
  23802. if( magic!=SQLITE_MAGIC_SICK &&
  23803. magic!=SQLITE_MAGIC_OPEN &&
  23804. magic!=SQLITE_MAGIC_BUSY ){
  23805. testcase( sqlite3GlobalConfig.xLog!=0 );
  23806. logBadConnection("invalid");
  23807. return 0;
  23808. }else{
  23809. return 1;
  23810. }
  23811. }
  23812. /*
  23813. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  23814. ** the other 64-bit signed integer at *pA and store the result in *pA.
  23815. ** Return 0 on success. Or if the operation would have resulted in an
  23816. ** overflow, leave *pA unchanged and return 1.
  23817. */
  23818. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  23819. i64 iA = *pA;
  23820. testcase( iA==0 ); testcase( iA==1 );
  23821. testcase( iB==-1 ); testcase( iB==0 );
  23822. if( iB>=0 ){
  23823. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  23824. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  23825. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  23826. }else{
  23827. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  23828. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  23829. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  23830. }
  23831. *pA += iB;
  23832. return 0;
  23833. }
  23834. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  23835. testcase( iB==SMALLEST_INT64+1 );
  23836. if( iB==SMALLEST_INT64 ){
  23837. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  23838. if( (*pA)>=0 ) return 1;
  23839. *pA -= iB;
  23840. return 0;
  23841. }else{
  23842. return sqlite3AddInt64(pA, -iB);
  23843. }
  23844. }
  23845. #define TWOPOWER32 (((i64)1)<<32)
  23846. #define TWOPOWER31 (((i64)1)<<31)
  23847. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  23848. i64 iA = *pA;
  23849. i64 iA1, iA0, iB1, iB0, r;
  23850. iA1 = iA/TWOPOWER32;
  23851. iA0 = iA % TWOPOWER32;
  23852. iB1 = iB/TWOPOWER32;
  23853. iB0 = iB % TWOPOWER32;
  23854. if( iA1==0 ){
  23855. if( iB1==0 ){
  23856. *pA *= iB;
  23857. return 0;
  23858. }
  23859. r = iA0*iB1;
  23860. }else if( iB1==0 ){
  23861. r = iA1*iB0;
  23862. }else{
  23863. /* If both iA1 and iB1 are non-zero, overflow will result */
  23864. return 1;
  23865. }
  23866. testcase( r==(-TWOPOWER31)-1 );
  23867. testcase( r==(-TWOPOWER31) );
  23868. testcase( r==TWOPOWER31 );
  23869. testcase( r==TWOPOWER31-1 );
  23870. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  23871. r *= TWOPOWER32;
  23872. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  23873. *pA = r;
  23874. return 0;
  23875. }
  23876. /*
  23877. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  23878. ** if the integer has a value of -2147483648, return +2147483647
  23879. */
  23880. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  23881. if( x>=0 ) return x;
  23882. if( x==(int)0x80000000 ) return 0x7fffffff;
  23883. return -x;
  23884. }
  23885. #ifdef SQLITE_ENABLE_8_3_NAMES
  23886. /*
  23887. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  23888. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  23889. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  23890. ** three characters, then shorten the suffix on z[] to be the last three
  23891. ** characters of the original suffix.
  23892. **
  23893. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  23894. ** do the suffix shortening regardless of URI parameter.
  23895. **
  23896. ** Examples:
  23897. **
  23898. ** test.db-journal => test.nal
  23899. ** test.db-wal => test.wal
  23900. ** test.db-shm => test.shm
  23901. ** test.db-mj7f3319fa => test.9fa
  23902. */
  23903. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  23904. #if SQLITE_ENABLE_8_3_NAMES<2
  23905. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  23906. #endif
  23907. {
  23908. int i, sz;
  23909. sz = sqlite3Strlen30(z);
  23910. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  23911. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  23912. }
  23913. }
  23914. #endif
  23915. /*
  23916. ** Find (an approximate) sum of two LogEst values. This computation is
  23917. ** not a simple "+" operator because LogEst is stored as a logarithmic
  23918. ** value.
  23919. **
  23920. */
  23921. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  23922. static const unsigned char x[] = {
  23923. 10, 10, /* 0,1 */
  23924. 9, 9, /* 2,3 */
  23925. 8, 8, /* 4,5 */
  23926. 7, 7, 7, /* 6,7,8 */
  23927. 6, 6, 6, /* 9,10,11 */
  23928. 5, 5, 5, /* 12-14 */
  23929. 4, 4, 4, 4, /* 15-18 */
  23930. 3, 3, 3, 3, 3, 3, /* 19-24 */
  23931. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  23932. };
  23933. if( a>=b ){
  23934. if( a>b+49 ) return a;
  23935. if( a>b+31 ) return a+1;
  23936. return a+x[a-b];
  23937. }else{
  23938. if( b>a+49 ) return b;
  23939. if( b>a+31 ) return b+1;
  23940. return b+x[b-a];
  23941. }
  23942. }
  23943. /*
  23944. ** Convert an integer into a LogEst. In other words, compute an
  23945. ** approximation for 10*log2(x).
  23946. */
  23947. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  23948. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  23949. LogEst y = 40;
  23950. if( x<8 ){
  23951. if( x<2 ) return 0;
  23952. while( x<8 ){ y -= 10; x <<= 1; }
  23953. }else{
  23954. while( x>255 ){ y += 40; x >>= 4; }
  23955. while( x>15 ){ y += 10; x >>= 1; }
  23956. }
  23957. return a[x&7] + y - 10;
  23958. }
  23959. #ifndef SQLITE_OMIT_VIRTUALTABLE
  23960. /*
  23961. ** Convert a double into a LogEst
  23962. ** In other words, compute an approximation for 10*log2(x).
  23963. */
  23964. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  23965. u64 a;
  23966. LogEst e;
  23967. assert( sizeof(x)==8 && sizeof(a)==8 );
  23968. if( x<=1 ) return 0;
  23969. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  23970. memcpy(&a, &x, 8);
  23971. e = (a>>52) - 1022;
  23972. return e*10;
  23973. }
  23974. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  23975. /*
  23976. ** Convert a LogEst into an integer.
  23977. */
  23978. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  23979. u64 n;
  23980. if( x<10 ) return 1;
  23981. n = x%10;
  23982. x /= 10;
  23983. if( n>=5 ) n -= 2;
  23984. else if( n>=1 ) n -= 1;
  23985. if( x>=3 ){
  23986. return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
  23987. }
  23988. return (n+8)>>(3-x);
  23989. }
  23990. /************** End of util.c ************************************************/
  23991. /************** Begin file hash.c ********************************************/
  23992. /*
  23993. ** 2001 September 22
  23994. **
  23995. ** The author disclaims copyright to this source code. In place of
  23996. ** a legal notice, here is a blessing:
  23997. **
  23998. ** May you do good and not evil.
  23999. ** May you find forgiveness for yourself and forgive others.
  24000. ** May you share freely, never taking more than you give.
  24001. **
  24002. *************************************************************************
  24003. ** This is the implementation of generic hash-tables
  24004. ** used in SQLite.
  24005. */
  24006. /* #include "sqliteInt.h" */
  24007. /* #include <assert.h> */
  24008. /* Turn bulk memory into a hash table object by initializing the
  24009. ** fields of the Hash structure.
  24010. **
  24011. ** "pNew" is a pointer to the hash table that is to be initialized.
  24012. */
  24013. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  24014. assert( pNew!=0 );
  24015. pNew->first = 0;
  24016. pNew->count = 0;
  24017. pNew->htsize = 0;
  24018. pNew->ht = 0;
  24019. }
  24020. /* Remove all entries from a hash table. Reclaim all memory.
  24021. ** Call this routine to delete a hash table or to reset a hash table
  24022. ** to the empty state.
  24023. */
  24024. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  24025. HashElem *elem; /* For looping over all elements of the table */
  24026. assert( pH!=0 );
  24027. elem = pH->first;
  24028. pH->first = 0;
  24029. sqlite3_free(pH->ht);
  24030. pH->ht = 0;
  24031. pH->htsize = 0;
  24032. while( elem ){
  24033. HashElem *next_elem = elem->next;
  24034. sqlite3_free(elem);
  24035. elem = next_elem;
  24036. }
  24037. pH->count = 0;
  24038. }
  24039. /*
  24040. ** The hashing function.
  24041. */
  24042. static unsigned int strHash(const char *z){
  24043. unsigned int h = 0;
  24044. unsigned char c;
  24045. while( (c = (unsigned char)*z++)!=0 ){
  24046. h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
  24047. }
  24048. return h;
  24049. }
  24050. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  24051. ** insert pNew into the pEntry hash bucket.
  24052. */
  24053. static void insertElement(
  24054. Hash *pH, /* The complete hash table */
  24055. struct _ht *pEntry, /* The entry into which pNew is inserted */
  24056. HashElem *pNew /* The element to be inserted */
  24057. ){
  24058. HashElem *pHead; /* First element already in pEntry */
  24059. if( pEntry ){
  24060. pHead = pEntry->count ? pEntry->chain : 0;
  24061. pEntry->count++;
  24062. pEntry->chain = pNew;
  24063. }else{
  24064. pHead = 0;
  24065. }
  24066. if( pHead ){
  24067. pNew->next = pHead;
  24068. pNew->prev = pHead->prev;
  24069. if( pHead->prev ){ pHead->prev->next = pNew; }
  24070. else { pH->first = pNew; }
  24071. pHead->prev = pNew;
  24072. }else{
  24073. pNew->next = pH->first;
  24074. if( pH->first ){ pH->first->prev = pNew; }
  24075. pNew->prev = 0;
  24076. pH->first = pNew;
  24077. }
  24078. }
  24079. /* Resize the hash table so that it cantains "new_size" buckets.
  24080. **
  24081. ** The hash table might fail to resize if sqlite3_malloc() fails or
  24082. ** if the new size is the same as the prior size.
  24083. ** Return TRUE if the resize occurs and false if not.
  24084. */
  24085. static int rehash(Hash *pH, unsigned int new_size){
  24086. struct _ht *new_ht; /* The new hash table */
  24087. HashElem *elem, *next_elem; /* For looping over existing elements */
  24088. #if SQLITE_MALLOC_SOFT_LIMIT>0
  24089. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  24090. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  24091. }
  24092. if( new_size==pH->htsize ) return 0;
  24093. #endif
  24094. /* The inability to allocates space for a larger hash table is
  24095. ** a performance hit but it is not a fatal error. So mark the
  24096. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  24097. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  24098. ** only zeroes the requested number of bytes whereas this module will
  24099. ** use the actual amount of space allocated for the hash table (which
  24100. ** may be larger than the requested amount).
  24101. */
  24102. sqlite3BeginBenignMalloc();
  24103. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  24104. sqlite3EndBenignMalloc();
  24105. if( new_ht==0 ) return 0;
  24106. sqlite3_free(pH->ht);
  24107. pH->ht = new_ht;
  24108. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  24109. memset(new_ht, 0, new_size*sizeof(struct _ht));
  24110. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  24111. unsigned int h = strHash(elem->pKey) % new_size;
  24112. next_elem = elem->next;
  24113. insertElement(pH, &new_ht[h], elem);
  24114. }
  24115. return 1;
  24116. }
  24117. /* This function (for internal use only) locates an element in an
  24118. ** hash table that matches the given key. The hash for this key is
  24119. ** also computed and returned in the *pH parameter.
  24120. */
  24121. static HashElem *findElementWithHash(
  24122. const Hash *pH, /* The pH to be searched */
  24123. const char *pKey, /* The key we are searching for */
  24124. unsigned int *pHash /* Write the hash value here */
  24125. ){
  24126. HashElem *elem; /* Used to loop thru the element list */
  24127. int count; /* Number of elements left to test */
  24128. unsigned int h; /* The computed hash */
  24129. if( pH->ht ){
  24130. struct _ht *pEntry;
  24131. h = strHash(pKey) % pH->htsize;
  24132. pEntry = &pH->ht[h];
  24133. elem = pEntry->chain;
  24134. count = pEntry->count;
  24135. }else{
  24136. h = 0;
  24137. elem = pH->first;
  24138. count = pH->count;
  24139. }
  24140. *pHash = h;
  24141. while( count-- ){
  24142. assert( elem!=0 );
  24143. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  24144. return elem;
  24145. }
  24146. elem = elem->next;
  24147. }
  24148. return 0;
  24149. }
  24150. /* Remove a single entry from the hash table given a pointer to that
  24151. ** element and a hash on the element's key.
  24152. */
  24153. static void removeElementGivenHash(
  24154. Hash *pH, /* The pH containing "elem" */
  24155. HashElem* elem, /* The element to be removed from the pH */
  24156. unsigned int h /* Hash value for the element */
  24157. ){
  24158. struct _ht *pEntry;
  24159. if( elem->prev ){
  24160. elem->prev->next = elem->next;
  24161. }else{
  24162. pH->first = elem->next;
  24163. }
  24164. if( elem->next ){
  24165. elem->next->prev = elem->prev;
  24166. }
  24167. if( pH->ht ){
  24168. pEntry = &pH->ht[h];
  24169. if( pEntry->chain==elem ){
  24170. pEntry->chain = elem->next;
  24171. }
  24172. pEntry->count--;
  24173. assert( pEntry->count>=0 );
  24174. }
  24175. sqlite3_free( elem );
  24176. pH->count--;
  24177. if( pH->count==0 ){
  24178. assert( pH->first==0 );
  24179. assert( pH->count==0 );
  24180. sqlite3HashClear(pH);
  24181. }
  24182. }
  24183. /* Attempt to locate an element of the hash table pH with a key
  24184. ** that matches pKey. Return the data for this element if it is
  24185. ** found, or NULL if there is no match.
  24186. */
  24187. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  24188. HashElem *elem; /* The element that matches key */
  24189. unsigned int h; /* A hash on key */
  24190. assert( pH!=0 );
  24191. assert( pKey!=0 );
  24192. elem = findElementWithHash(pH, pKey, &h);
  24193. return elem ? elem->data : 0;
  24194. }
  24195. /* Insert an element into the hash table pH. The key is pKey
  24196. ** and the data is "data".
  24197. **
  24198. ** If no element exists with a matching key, then a new
  24199. ** element is created and NULL is returned.
  24200. **
  24201. ** If another element already exists with the same key, then the
  24202. ** new data replaces the old data and the old data is returned.
  24203. ** The key is not copied in this instance. If a malloc fails, then
  24204. ** the new data is returned and the hash table is unchanged.
  24205. **
  24206. ** If the "data" parameter to this function is NULL, then the
  24207. ** element corresponding to "key" is removed from the hash table.
  24208. */
  24209. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  24210. unsigned int h; /* the hash of the key modulo hash table size */
  24211. HashElem *elem; /* Used to loop thru the element list */
  24212. HashElem *new_elem; /* New element added to the pH */
  24213. assert( pH!=0 );
  24214. assert( pKey!=0 );
  24215. elem = findElementWithHash(pH,pKey,&h);
  24216. if( elem ){
  24217. void *old_data = elem->data;
  24218. if( data==0 ){
  24219. removeElementGivenHash(pH,elem,h);
  24220. }else{
  24221. elem->data = data;
  24222. elem->pKey = pKey;
  24223. }
  24224. return old_data;
  24225. }
  24226. if( data==0 ) return 0;
  24227. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  24228. if( new_elem==0 ) return data;
  24229. new_elem->pKey = pKey;
  24230. new_elem->data = data;
  24231. pH->count++;
  24232. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  24233. if( rehash(pH, pH->count*2) ){
  24234. assert( pH->htsize>0 );
  24235. h = strHash(pKey) % pH->htsize;
  24236. }
  24237. }
  24238. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  24239. return 0;
  24240. }
  24241. /************** End of hash.c ************************************************/
  24242. /************** Begin file opcodes.c *****************************************/
  24243. /* Automatically generated. Do not edit */
  24244. /* See the mkopcodec.awk script for details. */
  24245. #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  24246. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  24247. # define OpHelp(X) "\0" X
  24248. #else
  24249. # define OpHelp(X)
  24250. #endif
  24251. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  24252. static const char *const azName[] = { "?",
  24253. /* 1 */ "Savepoint" OpHelp(""),
  24254. /* 2 */ "AutoCommit" OpHelp(""),
  24255. /* 3 */ "Transaction" OpHelp(""),
  24256. /* 4 */ "SorterNext" OpHelp(""),
  24257. /* 5 */ "PrevIfOpen" OpHelp(""),
  24258. /* 6 */ "NextIfOpen" OpHelp(""),
  24259. /* 7 */ "Prev" OpHelp(""),
  24260. /* 8 */ "Next" OpHelp(""),
  24261. /* 9 */ "Checkpoint" OpHelp(""),
  24262. /* 10 */ "JournalMode" OpHelp(""),
  24263. /* 11 */ "Vacuum" OpHelp(""),
  24264. /* 12 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  24265. /* 13 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  24266. /* 14 */ "Goto" OpHelp(""),
  24267. /* 15 */ "Gosub" OpHelp(""),
  24268. /* 16 */ "Return" OpHelp(""),
  24269. /* 17 */ "InitCoroutine" OpHelp(""),
  24270. /* 18 */ "EndCoroutine" OpHelp(""),
  24271. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  24272. /* 20 */ "Yield" OpHelp(""),
  24273. /* 21 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  24274. /* 22 */ "Halt" OpHelp(""),
  24275. /* 23 */ "Integer" OpHelp("r[P2]=P1"),
  24276. /* 24 */ "Int64" OpHelp("r[P2]=P4"),
  24277. /* 25 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  24278. /* 26 */ "Null" OpHelp("r[P2..P3]=NULL"),
  24279. /* 27 */ "SoftNull" OpHelp("r[P1]=NULL"),
  24280. /* 28 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  24281. /* 29 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  24282. /* 30 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  24283. /* 31 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  24284. /* 32 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  24285. /* 33 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  24286. /* 34 */ "CollSeq" OpHelp(""),
  24287. /* 35 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
  24288. /* 36 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  24289. /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  24290. /* 38 */ "MustBeInt" OpHelp(""),
  24291. /* 39 */ "RealAffinity" OpHelp(""),
  24292. /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
  24293. /* 41 */ "Permutation" OpHelp(""),
  24294. /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  24295. /* 43 */ "Jump" OpHelp(""),
  24296. /* 44 */ "Once" OpHelp(""),
  24297. /* 45 */ "If" OpHelp(""),
  24298. /* 46 */ "IfNot" OpHelp(""),
  24299. /* 47 */ "Column" OpHelp("r[P3]=PX"),
  24300. /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  24301. /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  24302. /* 50 */ "Count" OpHelp("r[P2]=count()"),
  24303. /* 51 */ "ReadCookie" OpHelp(""),
  24304. /* 52 */ "SetCookie" OpHelp(""),
  24305. /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  24306. /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  24307. /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  24308. /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  24309. /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  24310. /* 58 */ "SorterOpen" OpHelp(""),
  24311. /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  24312. /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  24313. /* 61 */ "Close" OpHelp(""),
  24314. /* 62 */ "ColumnsUsed" OpHelp(""),
  24315. /* 63 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  24316. /* 64 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  24317. /* 65 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  24318. /* 66 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  24319. /* 67 */ "Seek" OpHelp("intkey=r[P2]"),
  24320. /* 68 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  24321. /* 69 */ "NotFound" OpHelp("key=r[P3@P4]"),
  24322. /* 70 */ "Found" OpHelp("key=r[P3@P4]"),
  24323. /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  24324. /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  24325. /* 73 */ "NotExists" OpHelp("intkey=r[P3]"),
  24326. /* 74 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  24327. /* 75 */ "NewRowid" OpHelp("r[P2]=rowid"),
  24328. /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  24329. /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  24330. /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
  24331. /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
  24332. /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
  24333. /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
  24334. /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
  24335. /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
  24336. /* 84 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  24337. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  24338. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  24339. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  24340. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  24341. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  24342. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  24343. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  24344. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  24345. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  24346. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  24347. /* 95 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  24348. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  24349. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  24350. /* 98 */ "Delete" OpHelp(""),
  24351. /* 99 */ "ResetCount" OpHelp(""),
  24352. /* 100 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  24353. /* 101 */ "SorterData" OpHelp("r[P2]=data"),
  24354. /* 102 */ "RowKey" OpHelp("r[P2]=key"),
  24355. /* 103 */ "RowData" OpHelp("r[P2]=data"),
  24356. /* 104 */ "Rowid" OpHelp("r[P2]=rowid"),
  24357. /* 105 */ "NullRow" OpHelp(""),
  24358. /* 106 */ "Last" OpHelp(""),
  24359. /* 107 */ "SorterSort" OpHelp(""),
  24360. /* 108 */ "Sort" OpHelp(""),
  24361. /* 109 */ "Rewind" OpHelp(""),
  24362. /* 110 */ "SorterInsert" OpHelp(""),
  24363. /* 111 */ "IdxInsert" OpHelp("key=r[P2]"),
  24364. /* 112 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  24365. /* 113 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  24366. /* 114 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  24367. /* 115 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  24368. /* 116 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  24369. /* 117 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  24370. /* 118 */ "Destroy" OpHelp(""),
  24371. /* 119 */ "Clear" OpHelp(""),
  24372. /* 120 */ "ResetSorter" OpHelp(""),
  24373. /* 121 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  24374. /* 122 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  24375. /* 123 */ "ParseSchema" OpHelp(""),
  24376. /* 124 */ "LoadAnalysis" OpHelp(""),
  24377. /* 125 */ "DropTable" OpHelp(""),
  24378. /* 126 */ "DropIndex" OpHelp(""),
  24379. /* 127 */ "DropTrigger" OpHelp(""),
  24380. /* 128 */ "IntegrityCk" OpHelp(""),
  24381. /* 129 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  24382. /* 130 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  24383. /* 131 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  24384. /* 132 */ "Program" OpHelp(""),
  24385. /* 133 */ "Real" OpHelp("r[P2]=P4"),
  24386. /* 134 */ "Param" OpHelp(""),
  24387. /* 135 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  24388. /* 136 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  24389. /* 137 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  24390. /* 138 */ "IfPos" OpHelp("if r[P1]>0 goto P2"),
  24391. /* 139 */ "IfNeg" OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
  24392. /* 140 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]+=P3, goto P2"),
  24393. /* 141 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
  24394. /* 142 */ "JumpZeroIncr" OpHelp("if (r[P1]++)==0 ) goto P2"),
  24395. /* 143 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
  24396. /* 144 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  24397. /* 145 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  24398. /* 146 */ "IncrVacuum" OpHelp(""),
  24399. /* 147 */ "Expire" OpHelp(""),
  24400. /* 148 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  24401. /* 149 */ "VBegin" OpHelp(""),
  24402. /* 150 */ "VCreate" OpHelp(""),
  24403. /* 151 */ "VDestroy" OpHelp(""),
  24404. /* 152 */ "VOpen" OpHelp(""),
  24405. /* 153 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  24406. /* 154 */ "VNext" OpHelp(""),
  24407. /* 155 */ "VRename" OpHelp(""),
  24408. /* 156 */ "Pagecount" OpHelp(""),
  24409. /* 157 */ "MaxPgcnt" OpHelp(""),
  24410. /* 158 */ "Init" OpHelp("Start at P2"),
  24411. /* 159 */ "Noop" OpHelp(""),
  24412. /* 160 */ "Explain" OpHelp(""),
  24413. };
  24414. return azName[i];
  24415. }
  24416. #endif
  24417. /************** End of opcodes.c *********************************************/
  24418. /************** Begin file os_unix.c *****************************************/
  24419. /*
  24420. ** 2004 May 22
  24421. **
  24422. ** The author disclaims copyright to this source code. In place of
  24423. ** a legal notice, here is a blessing:
  24424. **
  24425. ** May you do good and not evil.
  24426. ** May you find forgiveness for yourself and forgive others.
  24427. ** May you share freely, never taking more than you give.
  24428. **
  24429. ******************************************************************************
  24430. **
  24431. ** This file contains the VFS implementation for unix-like operating systems
  24432. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  24433. **
  24434. ** There are actually several different VFS implementations in this file.
  24435. ** The differences are in the way that file locking is done. The default
  24436. ** implementation uses Posix Advisory Locks. Alternative implementations
  24437. ** use flock(), dot-files, various proprietary locking schemas, or simply
  24438. ** skip locking all together.
  24439. **
  24440. ** This source file is organized into divisions where the logic for various
  24441. ** subfunctions is contained within the appropriate division. PLEASE
  24442. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  24443. ** in the correct division and should be clearly labeled.
  24444. **
  24445. ** The layout of divisions is as follows:
  24446. **
  24447. ** * General-purpose declarations and utility functions.
  24448. ** * Unique file ID logic used by VxWorks.
  24449. ** * Various locking primitive implementations (all except proxy locking):
  24450. ** + for Posix Advisory Locks
  24451. ** + for no-op locks
  24452. ** + for dot-file locks
  24453. ** + for flock() locking
  24454. ** + for named semaphore locks (VxWorks only)
  24455. ** + for AFP filesystem locks (MacOSX only)
  24456. ** * sqlite3_file methods not associated with locking.
  24457. ** * Definitions of sqlite3_io_methods objects for all locking
  24458. ** methods plus "finder" functions for each locking method.
  24459. ** * sqlite3_vfs method implementations.
  24460. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  24461. ** * Definitions of sqlite3_vfs objects for all locking methods
  24462. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  24463. */
  24464. /* #include "sqliteInt.h" */
  24465. #if SQLITE_OS_UNIX /* This file is used on unix only */
  24466. /*
  24467. ** There are various methods for file locking used for concurrency
  24468. ** control:
  24469. **
  24470. ** 1. POSIX locking (the default),
  24471. ** 2. No locking,
  24472. ** 3. Dot-file locking,
  24473. ** 4. flock() locking,
  24474. ** 5. AFP locking (OSX only),
  24475. ** 6. Named POSIX semaphores (VXWorks only),
  24476. ** 7. proxy locking. (OSX only)
  24477. **
  24478. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  24479. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  24480. ** selection of the appropriate locking style based on the filesystem
  24481. ** where the database is located.
  24482. */
  24483. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  24484. # if defined(__APPLE__)
  24485. # define SQLITE_ENABLE_LOCKING_STYLE 1
  24486. # else
  24487. # define SQLITE_ENABLE_LOCKING_STYLE 0
  24488. # endif
  24489. #endif
  24490. /*
  24491. ** standard include files.
  24492. */
  24493. #include <sys/types.h>
  24494. #include <sys/stat.h>
  24495. #include <fcntl.h>
  24496. #include <unistd.h>
  24497. /* #include <time.h> */
  24498. #include <sys/time.h>
  24499. #include <errno.h>
  24500. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  24501. # include <sys/mman.h>
  24502. #endif
  24503. #if SQLITE_ENABLE_LOCKING_STYLE
  24504. # include <sys/ioctl.h>
  24505. # include <sys/file.h>
  24506. # include <sys/param.h>
  24507. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  24508. #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
  24509. (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
  24510. # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
  24511. && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
  24512. # define HAVE_GETHOSTUUID 1
  24513. # else
  24514. # warning "gethostuuid() is disabled."
  24515. # endif
  24516. #endif
  24517. #if OS_VXWORKS
  24518. /* # include <sys/ioctl.h> */
  24519. # include <semaphore.h>
  24520. # include <limits.h>
  24521. #endif /* OS_VXWORKS */
  24522. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  24523. # include <sys/mount.h>
  24524. #endif
  24525. #ifdef HAVE_UTIME
  24526. # include <utime.h>
  24527. #endif
  24528. /*
  24529. ** Allowed values of unixFile.fsFlags
  24530. */
  24531. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  24532. /*
  24533. ** If we are to be thread-safe, include the pthreads header and define
  24534. ** the SQLITE_UNIX_THREADS macro.
  24535. */
  24536. #if SQLITE_THREADSAFE
  24537. /* # include <pthread.h> */
  24538. # define SQLITE_UNIX_THREADS 1
  24539. #endif
  24540. /*
  24541. ** Default permissions when creating a new file
  24542. */
  24543. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  24544. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  24545. #endif
  24546. /*
  24547. ** Default permissions when creating auto proxy dir
  24548. */
  24549. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  24550. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  24551. #endif
  24552. /*
  24553. ** Maximum supported path-length.
  24554. */
  24555. #define MAX_PATHNAME 512
  24556. /* Always cast the getpid() return type for compatibility with
  24557. ** kernel modules in VxWorks. */
  24558. #define osGetpid(X) (pid_t)getpid()
  24559. /*
  24560. ** Only set the lastErrno if the error code is a real error and not
  24561. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  24562. */
  24563. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  24564. /* Forward references */
  24565. typedef struct unixShm unixShm; /* Connection shared memory */
  24566. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  24567. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  24568. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  24569. /*
  24570. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  24571. ** cannot be closed immediately. In these cases, instances of the following
  24572. ** structure are used to store the file descriptor while waiting for an
  24573. ** opportunity to either close or reuse it.
  24574. */
  24575. struct UnixUnusedFd {
  24576. int fd; /* File descriptor to close */
  24577. int flags; /* Flags this file descriptor was opened with */
  24578. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  24579. };
  24580. /*
  24581. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  24582. ** VFS implementations.
  24583. */
  24584. typedef struct unixFile unixFile;
  24585. struct unixFile {
  24586. sqlite3_io_methods const *pMethod; /* Always the first entry */
  24587. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  24588. unixInodeInfo *pInode; /* Info about locks on this inode */
  24589. int h; /* The file descriptor */
  24590. unsigned char eFileLock; /* The type of lock held on this fd */
  24591. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  24592. int lastErrno; /* The unix errno from last I/O error */
  24593. void *lockingContext; /* Locking style specific state */
  24594. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  24595. const char *zPath; /* Name of the file */
  24596. unixShm *pShm; /* Shared memory segment information */
  24597. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  24598. #if SQLITE_MAX_MMAP_SIZE>0
  24599. int nFetchOut; /* Number of outstanding xFetch refs */
  24600. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  24601. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  24602. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  24603. void *pMapRegion; /* Memory mapped region */
  24604. #endif
  24605. #ifdef __QNXNTO__
  24606. int sectorSize; /* Device sector size */
  24607. int deviceCharacteristics; /* Precomputed device characteristics */
  24608. #endif
  24609. #if SQLITE_ENABLE_LOCKING_STYLE
  24610. int openFlags; /* The flags specified at open() */
  24611. #endif
  24612. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  24613. unsigned fsFlags; /* cached details from statfs() */
  24614. #endif
  24615. #if OS_VXWORKS
  24616. struct vxworksFileId *pId; /* Unique file ID */
  24617. #endif
  24618. #ifdef SQLITE_DEBUG
  24619. /* The next group of variables are used to track whether or not the
  24620. ** transaction counter in bytes 24-27 of database files are updated
  24621. ** whenever any part of the database changes. An assertion fault will
  24622. ** occur if a file is updated without also updating the transaction
  24623. ** counter. This test is made to avoid new problems similar to the
  24624. ** one described by ticket #3584.
  24625. */
  24626. unsigned char transCntrChng; /* True if the transaction counter changed */
  24627. unsigned char dbUpdate; /* True if any part of database file changed */
  24628. unsigned char inNormalWrite; /* True if in a normal write operation */
  24629. #endif
  24630. #ifdef SQLITE_TEST
  24631. /* In test mode, increase the size of this structure a bit so that
  24632. ** it is larger than the struct CrashFile defined in test6.c.
  24633. */
  24634. char aPadding[32];
  24635. #endif
  24636. };
  24637. /* This variable holds the process id (pid) from when the xRandomness()
  24638. ** method was called. If xOpen() is called from a different process id,
  24639. ** indicating that a fork() has occurred, the PRNG will be reset.
  24640. */
  24641. static pid_t randomnessPid = 0;
  24642. /*
  24643. ** Allowed values for the unixFile.ctrlFlags bitmask:
  24644. */
  24645. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  24646. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  24647. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  24648. #ifndef SQLITE_DISABLE_DIRSYNC
  24649. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  24650. #else
  24651. # define UNIXFILE_DIRSYNC 0x00
  24652. #endif
  24653. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  24654. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  24655. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  24656. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  24657. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings issued */
  24658. #define UNIXFILE_BLOCK 0x0200 /* Next SHM lock might block */
  24659. /*
  24660. ** Include code that is common to all os_*.c files
  24661. */
  24662. /************** Include os_common.h in the middle of os_unix.c ***************/
  24663. /************** Begin file os_common.h ***************************************/
  24664. /*
  24665. ** 2004 May 22
  24666. **
  24667. ** The author disclaims copyright to this source code. In place of
  24668. ** a legal notice, here is a blessing:
  24669. **
  24670. ** May you do good and not evil.
  24671. ** May you find forgiveness for yourself and forgive others.
  24672. ** May you share freely, never taking more than you give.
  24673. **
  24674. ******************************************************************************
  24675. **
  24676. ** This file contains macros and a little bit of code that is common to
  24677. ** all of the platform-specific files (os_*.c) and is #included into those
  24678. ** files.
  24679. **
  24680. ** This file should be #included by the os_*.c files only. It is not a
  24681. ** general purpose header file.
  24682. */
  24683. #ifndef _OS_COMMON_H_
  24684. #define _OS_COMMON_H_
  24685. /*
  24686. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  24687. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  24688. ** switch. The following code should catch this problem at compile-time.
  24689. */
  24690. #ifdef MEMORY_DEBUG
  24691. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  24692. #endif
  24693. /*
  24694. ** Macros for performance tracing. Normally turned off. Only works
  24695. ** on i486 hardware.
  24696. */
  24697. #ifdef SQLITE_PERFORMANCE_TRACE
  24698. /*
  24699. ** hwtime.h contains inline assembler code for implementing
  24700. ** high-performance timing routines.
  24701. */
  24702. /************** Include hwtime.h in the middle of os_common.h ****************/
  24703. /************** Begin file hwtime.h ******************************************/
  24704. /*
  24705. ** 2008 May 27
  24706. **
  24707. ** The author disclaims copyright to this source code. In place of
  24708. ** a legal notice, here is a blessing:
  24709. **
  24710. ** May you do good and not evil.
  24711. ** May you find forgiveness for yourself and forgive others.
  24712. ** May you share freely, never taking more than you give.
  24713. **
  24714. ******************************************************************************
  24715. **
  24716. ** This file contains inline asm code for retrieving "high-performance"
  24717. ** counters for x86 class CPUs.
  24718. */
  24719. #ifndef _HWTIME_H_
  24720. #define _HWTIME_H_
  24721. /*
  24722. ** The following routine only works on pentium-class (or newer) processors.
  24723. ** It uses the RDTSC opcode to read the cycle count value out of the
  24724. ** processor and returns that value. This can be used for high-res
  24725. ** profiling.
  24726. */
  24727. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  24728. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  24729. #if defined(__GNUC__)
  24730. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24731. unsigned int lo, hi;
  24732. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  24733. return (sqlite_uint64)hi << 32 | lo;
  24734. }
  24735. #elif defined(_MSC_VER)
  24736. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  24737. __asm {
  24738. rdtsc
  24739. ret ; return value at EDX:EAX
  24740. }
  24741. }
  24742. #endif
  24743. #elif (defined(__GNUC__) && defined(__x86_64__))
  24744. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24745. unsigned long val;
  24746. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  24747. return val;
  24748. }
  24749. #elif (defined(__GNUC__) && defined(__ppc__))
  24750. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  24751. unsigned long long retval;
  24752. unsigned long junk;
  24753. __asm__ __volatile__ ("\n\
  24754. 1: mftbu %1\n\
  24755. mftb %L0\n\
  24756. mftbu %0\n\
  24757. cmpw %0,%1\n\
  24758. bne 1b"
  24759. : "=r" (retval), "=r" (junk));
  24760. return retval;
  24761. }
  24762. #else
  24763. #error Need implementation of sqlite3Hwtime() for your platform.
  24764. /*
  24765. ** To compile without implementing sqlite3Hwtime() for your platform,
  24766. ** you can remove the above #error and use the following
  24767. ** stub function. You will lose timing support for many
  24768. ** of the debugging and testing utilities, but it should at
  24769. ** least compile and run.
  24770. */
  24771. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  24772. #endif
  24773. #endif /* !defined(_HWTIME_H_) */
  24774. /************** End of hwtime.h **********************************************/
  24775. /************** Continuing where we left off in os_common.h ******************/
  24776. static sqlite_uint64 g_start;
  24777. static sqlite_uint64 g_elapsed;
  24778. #define TIMER_START g_start=sqlite3Hwtime()
  24779. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  24780. #define TIMER_ELAPSED g_elapsed
  24781. #else
  24782. #define TIMER_START
  24783. #define TIMER_END
  24784. #define TIMER_ELAPSED ((sqlite_uint64)0)
  24785. #endif
  24786. /*
  24787. ** If we compile with the SQLITE_TEST macro set, then the following block
  24788. ** of code will give us the ability to simulate a disk I/O error. This
  24789. ** is used for testing the I/O recovery logic.
  24790. */
  24791. #ifdef SQLITE_TEST
  24792. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  24793. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  24794. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  24795. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  24796. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  24797. SQLITE_API int sqlite3_diskfull_pending = 0;
  24798. SQLITE_API int sqlite3_diskfull = 0;
  24799. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  24800. #define SimulateIOError(CODE) \
  24801. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  24802. || sqlite3_io_error_pending-- == 1 ) \
  24803. { local_ioerr(); CODE; }
  24804. static void local_ioerr(){
  24805. IOTRACE(("IOERR\n"));
  24806. sqlite3_io_error_hit++;
  24807. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  24808. }
  24809. #define SimulateDiskfullError(CODE) \
  24810. if( sqlite3_diskfull_pending ){ \
  24811. if( sqlite3_diskfull_pending == 1 ){ \
  24812. local_ioerr(); \
  24813. sqlite3_diskfull = 1; \
  24814. sqlite3_io_error_hit = 1; \
  24815. CODE; \
  24816. }else{ \
  24817. sqlite3_diskfull_pending--; \
  24818. } \
  24819. }
  24820. #else
  24821. #define SimulateIOErrorBenign(X)
  24822. #define SimulateIOError(A)
  24823. #define SimulateDiskfullError(A)
  24824. #endif
  24825. /*
  24826. ** When testing, keep a count of the number of open files.
  24827. */
  24828. #ifdef SQLITE_TEST
  24829. SQLITE_API int sqlite3_open_file_count = 0;
  24830. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  24831. #else
  24832. #define OpenCounter(X)
  24833. #endif
  24834. #endif /* !defined(_OS_COMMON_H_) */
  24835. /************** End of os_common.h *******************************************/
  24836. /************** Continuing where we left off in os_unix.c ********************/
  24837. /*
  24838. ** Define various macros that are missing from some systems.
  24839. */
  24840. #ifndef O_LARGEFILE
  24841. # define O_LARGEFILE 0
  24842. #endif
  24843. #ifdef SQLITE_DISABLE_LFS
  24844. # undef O_LARGEFILE
  24845. # define O_LARGEFILE 0
  24846. #endif
  24847. #ifndef O_NOFOLLOW
  24848. # define O_NOFOLLOW 0
  24849. #endif
  24850. #ifndef O_BINARY
  24851. # define O_BINARY 0
  24852. #endif
  24853. /*
  24854. ** The threadid macro resolves to the thread-id or to 0. Used for
  24855. ** testing and debugging only.
  24856. */
  24857. #if SQLITE_THREADSAFE
  24858. #define threadid pthread_self()
  24859. #else
  24860. #define threadid 0
  24861. #endif
  24862. /*
  24863. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  24864. */
  24865. #if !defined(HAVE_MREMAP)
  24866. # if defined(__linux__) && defined(_GNU_SOURCE)
  24867. # define HAVE_MREMAP 1
  24868. # else
  24869. # define HAVE_MREMAP 0
  24870. # endif
  24871. #endif
  24872. /*
  24873. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  24874. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  24875. */
  24876. #ifdef __ANDROID__
  24877. # define lseek lseek64
  24878. #endif
  24879. /*
  24880. ** Different Unix systems declare open() in different ways. Same use
  24881. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  24882. ** The difference is important when using a pointer to the function.
  24883. **
  24884. ** The safest way to deal with the problem is to always use this wrapper
  24885. ** which always has the same well-defined interface.
  24886. */
  24887. static int posixOpen(const char *zFile, int flags, int mode){
  24888. return open(zFile, flags, mode);
  24889. }
  24890. /*
  24891. ** On some systems, calls to fchown() will trigger a message in a security
  24892. ** log if they come from non-root processes. So avoid calling fchown() if
  24893. ** we are not running as root.
  24894. */
  24895. static int posixFchown(int fd, uid_t uid, gid_t gid){
  24896. #if OS_VXWORKS
  24897. return 0;
  24898. #else
  24899. return geteuid() ? 0 : fchown(fd,uid,gid);
  24900. #endif
  24901. }
  24902. /* Forward reference */
  24903. static int openDirectory(const char*, int*);
  24904. static int unixGetpagesize(void);
  24905. /*
  24906. ** Many system calls are accessed through pointer-to-functions so that
  24907. ** they may be overridden at runtime to facilitate fault injection during
  24908. ** testing and sandboxing. The following array holds the names and pointers
  24909. ** to all overrideable system calls.
  24910. */
  24911. static struct unix_syscall {
  24912. const char *zName; /* Name of the system call */
  24913. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  24914. sqlite3_syscall_ptr pDefault; /* Default value */
  24915. } aSyscall[] = {
  24916. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  24917. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  24918. { "close", (sqlite3_syscall_ptr)close, 0 },
  24919. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  24920. { "access", (sqlite3_syscall_ptr)access, 0 },
  24921. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  24922. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  24923. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  24924. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  24925. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  24926. /*
  24927. ** The DJGPP compiler environment looks mostly like Unix, but it
  24928. ** lacks the fcntl() system call. So redefine fcntl() to be something
  24929. ** that always succeeds. This means that locking does not occur under
  24930. ** DJGPP. But it is DOS - what did you expect?
  24931. */
  24932. #ifdef __DJGPP__
  24933. { "fstat", 0, 0 },
  24934. #define osFstat(a,b,c) 0
  24935. #else
  24936. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  24937. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  24938. #endif
  24939. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  24940. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  24941. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  24942. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  24943. { "read", (sqlite3_syscall_ptr)read, 0 },
  24944. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  24945. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  24946. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  24947. #else
  24948. { "pread", (sqlite3_syscall_ptr)0, 0 },
  24949. #endif
  24950. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  24951. #if defined(USE_PREAD64)
  24952. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  24953. #else
  24954. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  24955. #endif
  24956. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  24957. { "write", (sqlite3_syscall_ptr)write, 0 },
  24958. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  24959. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  24960. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  24961. #else
  24962. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  24963. #endif
  24964. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  24965. aSyscall[12].pCurrent)
  24966. #if defined(USE_PREAD64)
  24967. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  24968. #else
  24969. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  24970. #endif
  24971. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  24972. aSyscall[13].pCurrent)
  24973. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  24974. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  24975. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  24976. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  24977. #else
  24978. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  24979. #endif
  24980. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  24981. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  24982. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  24983. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  24984. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  24985. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  24986. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  24987. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  24988. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  24989. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  24990. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  24991. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  24992. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  24993. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  24994. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  24995. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  24996. #if HAVE_MREMAP
  24997. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  24998. #else
  24999. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  25000. #endif
  25001. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  25002. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  25003. #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
  25004. #endif
  25005. }; /* End of the overrideable system calls */
  25006. /*
  25007. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  25008. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  25009. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  25010. ** system call named zName.
  25011. */
  25012. static int unixSetSystemCall(
  25013. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  25014. const char *zName, /* Name of system call to override */
  25015. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  25016. ){
  25017. unsigned int i;
  25018. int rc = SQLITE_NOTFOUND;
  25019. UNUSED_PARAMETER(pNotUsed);
  25020. if( zName==0 ){
  25021. /* If no zName is given, restore all system calls to their default
  25022. ** settings and return NULL
  25023. */
  25024. rc = SQLITE_OK;
  25025. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  25026. if( aSyscall[i].pDefault ){
  25027. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  25028. }
  25029. }
  25030. }else{
  25031. /* If zName is specified, operate on only the one system call
  25032. ** specified.
  25033. */
  25034. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  25035. if( strcmp(zName, aSyscall[i].zName)==0 ){
  25036. if( aSyscall[i].pDefault==0 ){
  25037. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  25038. }
  25039. rc = SQLITE_OK;
  25040. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  25041. aSyscall[i].pCurrent = pNewFunc;
  25042. break;
  25043. }
  25044. }
  25045. }
  25046. return rc;
  25047. }
  25048. /*
  25049. ** Return the value of a system call. Return NULL if zName is not a
  25050. ** recognized system call name. NULL is also returned if the system call
  25051. ** is currently undefined.
  25052. */
  25053. static sqlite3_syscall_ptr unixGetSystemCall(
  25054. sqlite3_vfs *pNotUsed,
  25055. const char *zName
  25056. ){
  25057. unsigned int i;
  25058. UNUSED_PARAMETER(pNotUsed);
  25059. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  25060. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  25061. }
  25062. return 0;
  25063. }
  25064. /*
  25065. ** Return the name of the first system call after zName. If zName==NULL
  25066. ** then return the name of the first system call. Return NULL if zName
  25067. ** is the last system call or if zName is not the name of a valid
  25068. ** system call.
  25069. */
  25070. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  25071. int i = -1;
  25072. UNUSED_PARAMETER(p);
  25073. if( zName ){
  25074. for(i=0; i<ArraySize(aSyscall)-1; i++){
  25075. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  25076. }
  25077. }
  25078. for(i++; i<ArraySize(aSyscall); i++){
  25079. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  25080. }
  25081. return 0;
  25082. }
  25083. /*
  25084. ** Do not accept any file descriptor less than this value, in order to avoid
  25085. ** opening database file using file descriptors that are commonly used for
  25086. ** standard input, output, and error.
  25087. */
  25088. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  25089. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  25090. #endif
  25091. /*
  25092. ** Invoke open(). Do so multiple times, until it either succeeds or
  25093. ** fails for some reason other than EINTR.
  25094. **
  25095. ** If the file creation mode "m" is 0 then set it to the default for
  25096. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  25097. ** 0644) as modified by the system umask. If m is not 0, then
  25098. ** make the file creation mode be exactly m ignoring the umask.
  25099. **
  25100. ** The m parameter will be non-zero only when creating -wal, -journal,
  25101. ** and -shm files. We want those files to have *exactly* the same
  25102. ** permissions as their original database, unadulterated by the umask.
  25103. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  25104. ** transaction crashes and leaves behind hot journals, then any
  25105. ** process that is able to write to the database will also be able to
  25106. ** recover the hot journals.
  25107. */
  25108. static int robust_open(const char *z, int f, mode_t m){
  25109. int fd;
  25110. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  25111. while(1){
  25112. #if defined(O_CLOEXEC)
  25113. fd = osOpen(z,f|O_CLOEXEC,m2);
  25114. #else
  25115. fd = osOpen(z,f,m2);
  25116. #endif
  25117. if( fd<0 ){
  25118. if( errno==EINTR ) continue;
  25119. break;
  25120. }
  25121. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  25122. osClose(fd);
  25123. sqlite3_log(SQLITE_WARNING,
  25124. "attempt to open \"%s\" as file descriptor %d", z, fd);
  25125. fd = -1;
  25126. if( osOpen("/dev/null", f, m)<0 ) break;
  25127. }
  25128. if( fd>=0 ){
  25129. if( m!=0 ){
  25130. struct stat statbuf;
  25131. if( osFstat(fd, &statbuf)==0
  25132. && statbuf.st_size==0
  25133. && (statbuf.st_mode&0777)!=m
  25134. ){
  25135. osFchmod(fd, m);
  25136. }
  25137. }
  25138. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  25139. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  25140. #endif
  25141. }
  25142. return fd;
  25143. }
  25144. /*
  25145. ** Helper functions to obtain and relinquish the global mutex. The
  25146. ** global mutex is used to protect the unixInodeInfo and
  25147. ** vxworksFileId objects used by this file, all of which may be
  25148. ** shared by multiple threads.
  25149. **
  25150. ** Function unixMutexHeld() is used to assert() that the global mutex
  25151. ** is held when required. This function is only used as part of assert()
  25152. ** statements. e.g.
  25153. **
  25154. ** unixEnterMutex()
  25155. ** assert( unixMutexHeld() );
  25156. ** unixEnterLeave()
  25157. */
  25158. static void unixEnterMutex(void){
  25159. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  25160. }
  25161. static void unixLeaveMutex(void){
  25162. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  25163. }
  25164. #ifdef SQLITE_DEBUG
  25165. static int unixMutexHeld(void) {
  25166. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  25167. }
  25168. #endif
  25169. #ifdef SQLITE_HAVE_OS_TRACE
  25170. /*
  25171. ** Helper function for printing out trace information from debugging
  25172. ** binaries. This returns the string representation of the supplied
  25173. ** integer lock-type.
  25174. */
  25175. static const char *azFileLock(int eFileLock){
  25176. switch( eFileLock ){
  25177. case NO_LOCK: return "NONE";
  25178. case SHARED_LOCK: return "SHARED";
  25179. case RESERVED_LOCK: return "RESERVED";
  25180. case PENDING_LOCK: return "PENDING";
  25181. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  25182. }
  25183. return "ERROR";
  25184. }
  25185. #endif
  25186. #ifdef SQLITE_LOCK_TRACE
  25187. /*
  25188. ** Print out information about all locking operations.
  25189. **
  25190. ** This routine is used for troubleshooting locks on multithreaded
  25191. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  25192. ** command-line option on the compiler. This code is normally
  25193. ** turned off.
  25194. */
  25195. static int lockTrace(int fd, int op, struct flock *p){
  25196. char *zOpName, *zType;
  25197. int s;
  25198. int savedErrno;
  25199. if( op==F_GETLK ){
  25200. zOpName = "GETLK";
  25201. }else if( op==F_SETLK ){
  25202. zOpName = "SETLK";
  25203. }else{
  25204. s = osFcntl(fd, op, p);
  25205. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  25206. return s;
  25207. }
  25208. if( p->l_type==F_RDLCK ){
  25209. zType = "RDLCK";
  25210. }else if( p->l_type==F_WRLCK ){
  25211. zType = "WRLCK";
  25212. }else if( p->l_type==F_UNLCK ){
  25213. zType = "UNLCK";
  25214. }else{
  25215. assert( 0 );
  25216. }
  25217. assert( p->l_whence==SEEK_SET );
  25218. s = osFcntl(fd, op, p);
  25219. savedErrno = errno;
  25220. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  25221. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  25222. (int)p->l_pid, s);
  25223. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  25224. struct flock l2;
  25225. l2 = *p;
  25226. osFcntl(fd, F_GETLK, &l2);
  25227. if( l2.l_type==F_RDLCK ){
  25228. zType = "RDLCK";
  25229. }else if( l2.l_type==F_WRLCK ){
  25230. zType = "WRLCK";
  25231. }else if( l2.l_type==F_UNLCK ){
  25232. zType = "UNLCK";
  25233. }else{
  25234. assert( 0 );
  25235. }
  25236. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  25237. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  25238. }
  25239. errno = savedErrno;
  25240. return s;
  25241. }
  25242. #undef osFcntl
  25243. #define osFcntl lockTrace
  25244. #endif /* SQLITE_LOCK_TRACE */
  25245. /*
  25246. ** Retry ftruncate() calls that fail due to EINTR
  25247. **
  25248. ** All calls to ftruncate() within this file should be made through
  25249. ** this wrapper. On the Android platform, bypassing the logic below
  25250. ** could lead to a corrupt database.
  25251. */
  25252. static int robust_ftruncate(int h, sqlite3_int64 sz){
  25253. int rc;
  25254. #ifdef __ANDROID__
  25255. /* On Android, ftruncate() always uses 32-bit offsets, even if
  25256. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  25257. ** truncate a file to any size larger than 2GiB. Silently ignore any
  25258. ** such attempts. */
  25259. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  25260. rc = SQLITE_OK;
  25261. }else
  25262. #endif
  25263. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  25264. return rc;
  25265. }
  25266. /*
  25267. ** This routine translates a standard POSIX errno code into something
  25268. ** useful to the clients of the sqlite3 functions. Specifically, it is
  25269. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  25270. ** and a variety of "please close the file descriptor NOW" errors into
  25271. ** SQLITE_IOERR
  25272. **
  25273. ** Errors during initialization of locks, or file system support for locks,
  25274. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  25275. */
  25276. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  25277. switch (posixError) {
  25278. #if 0
  25279. /* At one point this code was not commented out. In theory, this branch
  25280. ** should never be hit, as this function should only be called after
  25281. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  25282. ** the value of errno as the first argument. Since a system call has failed,
  25283. ** errno should be non-zero.
  25284. **
  25285. ** Despite this, if errno really is zero, we still don't want to return
  25286. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  25287. ** propagated back to the caller. Commenting this branch out means errno==0
  25288. ** will be handled by the "default:" case below.
  25289. */
  25290. case 0:
  25291. return SQLITE_OK;
  25292. #endif
  25293. case EAGAIN:
  25294. case ETIMEDOUT:
  25295. case EBUSY:
  25296. case EINTR:
  25297. case ENOLCK:
  25298. /* random NFS retry error, unless during file system support
  25299. * introspection, in which it actually means what it says */
  25300. return SQLITE_BUSY;
  25301. case EACCES:
  25302. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  25303. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  25304. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  25305. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  25306. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  25307. return SQLITE_BUSY;
  25308. }
  25309. /* else fall through */
  25310. case EPERM:
  25311. return SQLITE_PERM;
  25312. #if EOPNOTSUPP!=ENOTSUP
  25313. case EOPNOTSUPP:
  25314. /* something went terribly awry, unless during file system support
  25315. * introspection, in which it actually means what it says */
  25316. #endif
  25317. #ifdef ENOTSUP
  25318. case ENOTSUP:
  25319. /* invalid fd, unless during file system support introspection, in which
  25320. * it actually means what it says */
  25321. #endif
  25322. case EIO:
  25323. case EBADF:
  25324. case EINVAL:
  25325. case ENOTCONN:
  25326. case ENODEV:
  25327. case ENXIO:
  25328. case ENOENT:
  25329. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  25330. case ESTALE:
  25331. #endif
  25332. case ENOSYS:
  25333. /* these should force the client to close the file and reconnect */
  25334. default:
  25335. return sqliteIOErr;
  25336. }
  25337. }
  25338. /******************************************************************************
  25339. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  25340. **
  25341. ** On most versions of unix, we can get a unique ID for a file by concatenating
  25342. ** the device number and the inode number. But this does not work on VxWorks.
  25343. ** On VxWorks, a unique file id must be based on the canonical filename.
  25344. **
  25345. ** A pointer to an instance of the following structure can be used as a
  25346. ** unique file ID in VxWorks. Each instance of this structure contains
  25347. ** a copy of the canonical filename. There is also a reference count.
  25348. ** The structure is reclaimed when the number of pointers to it drops to
  25349. ** zero.
  25350. **
  25351. ** There are never very many files open at one time and lookups are not
  25352. ** a performance-critical path, so it is sufficient to put these
  25353. ** structures on a linked list.
  25354. */
  25355. struct vxworksFileId {
  25356. struct vxworksFileId *pNext; /* Next in a list of them all */
  25357. int nRef; /* Number of references to this one */
  25358. int nName; /* Length of the zCanonicalName[] string */
  25359. char *zCanonicalName; /* Canonical filename */
  25360. };
  25361. #if OS_VXWORKS
  25362. /*
  25363. ** All unique filenames are held on a linked list headed by this
  25364. ** variable:
  25365. */
  25366. static struct vxworksFileId *vxworksFileList = 0;
  25367. /*
  25368. ** Simplify a filename into its canonical form
  25369. ** by making the following changes:
  25370. **
  25371. ** * removing any trailing and duplicate /
  25372. ** * convert /./ into just /
  25373. ** * convert /A/../ where A is any simple name into just /
  25374. **
  25375. ** Changes are made in-place. Return the new name length.
  25376. **
  25377. ** The original filename is in z[0..n-1]. Return the number of
  25378. ** characters in the simplified name.
  25379. */
  25380. static int vxworksSimplifyName(char *z, int n){
  25381. int i, j;
  25382. while( n>1 && z[n-1]=='/' ){ n--; }
  25383. for(i=j=0; i<n; i++){
  25384. if( z[i]=='/' ){
  25385. if( z[i+1]=='/' ) continue;
  25386. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  25387. i += 1;
  25388. continue;
  25389. }
  25390. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  25391. while( j>0 && z[j-1]!='/' ){ j--; }
  25392. if( j>0 ){ j--; }
  25393. i += 2;
  25394. continue;
  25395. }
  25396. }
  25397. z[j++] = z[i];
  25398. }
  25399. z[j] = 0;
  25400. return j;
  25401. }
  25402. /*
  25403. ** Find a unique file ID for the given absolute pathname. Return
  25404. ** a pointer to the vxworksFileId object. This pointer is the unique
  25405. ** file ID.
  25406. **
  25407. ** The nRef field of the vxworksFileId object is incremented before
  25408. ** the object is returned. A new vxworksFileId object is created
  25409. ** and added to the global list if necessary.
  25410. **
  25411. ** If a memory allocation error occurs, return NULL.
  25412. */
  25413. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  25414. struct vxworksFileId *pNew; /* search key and new file ID */
  25415. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  25416. int n; /* Length of zAbsoluteName string */
  25417. assert( zAbsoluteName[0]=='/' );
  25418. n = (int)strlen(zAbsoluteName);
  25419. pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
  25420. if( pNew==0 ) return 0;
  25421. pNew->zCanonicalName = (char*)&pNew[1];
  25422. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  25423. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  25424. /* Search for an existing entry that matching the canonical name.
  25425. ** If found, increment the reference count and return a pointer to
  25426. ** the existing file ID.
  25427. */
  25428. unixEnterMutex();
  25429. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  25430. if( pCandidate->nName==n
  25431. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  25432. ){
  25433. sqlite3_free(pNew);
  25434. pCandidate->nRef++;
  25435. unixLeaveMutex();
  25436. return pCandidate;
  25437. }
  25438. }
  25439. /* No match was found. We will make a new file ID */
  25440. pNew->nRef = 1;
  25441. pNew->nName = n;
  25442. pNew->pNext = vxworksFileList;
  25443. vxworksFileList = pNew;
  25444. unixLeaveMutex();
  25445. return pNew;
  25446. }
  25447. /*
  25448. ** Decrement the reference count on a vxworksFileId object. Free
  25449. ** the object when the reference count reaches zero.
  25450. */
  25451. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  25452. unixEnterMutex();
  25453. assert( pId->nRef>0 );
  25454. pId->nRef--;
  25455. if( pId->nRef==0 ){
  25456. struct vxworksFileId **pp;
  25457. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  25458. assert( *pp==pId );
  25459. *pp = pId->pNext;
  25460. sqlite3_free(pId);
  25461. }
  25462. unixLeaveMutex();
  25463. }
  25464. #endif /* OS_VXWORKS */
  25465. /*************** End of Unique File ID Utility Used By VxWorks ****************
  25466. ******************************************************************************/
  25467. /******************************************************************************
  25468. *************************** Posix Advisory Locking ****************************
  25469. **
  25470. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  25471. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  25472. ** sets or clears a lock, that operation overrides any prior locks set
  25473. ** by the same process. It does not explicitly say so, but this implies
  25474. ** that it overrides locks set by the same process using a different
  25475. ** file descriptor. Consider this test case:
  25476. **
  25477. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  25478. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  25479. **
  25480. ** Suppose ./file1 and ./file2 are really the same file (because
  25481. ** one is a hard or symbolic link to the other) then if you set
  25482. ** an exclusive lock on fd1, then try to get an exclusive lock
  25483. ** on fd2, it works. I would have expected the second lock to
  25484. ** fail since there was already a lock on the file due to fd1.
  25485. ** But not so. Since both locks came from the same process, the
  25486. ** second overrides the first, even though they were on different
  25487. ** file descriptors opened on different file names.
  25488. **
  25489. ** This means that we cannot use POSIX locks to synchronize file access
  25490. ** among competing threads of the same process. POSIX locks will work fine
  25491. ** to synchronize access for threads in separate processes, but not
  25492. ** threads within the same process.
  25493. **
  25494. ** To work around the problem, SQLite has to manage file locks internally
  25495. ** on its own. Whenever a new database is opened, we have to find the
  25496. ** specific inode of the database file (the inode is determined by the
  25497. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  25498. ** and check for locks already existing on that inode. When locks are
  25499. ** created or removed, we have to look at our own internal record of the
  25500. ** locks to see if another thread has previously set a lock on that same
  25501. ** inode.
  25502. **
  25503. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  25504. ** For VxWorks, we have to use the alternative unique ID system based on
  25505. ** canonical filename and implemented in the previous division.)
  25506. **
  25507. ** The sqlite3_file structure for POSIX is no longer just an integer file
  25508. ** descriptor. It is now a structure that holds the integer file
  25509. ** descriptor and a pointer to a structure that describes the internal
  25510. ** locks on the corresponding inode. There is one locking structure
  25511. ** per inode, so if the same inode is opened twice, both unixFile structures
  25512. ** point to the same locking structure. The locking structure keeps
  25513. ** a reference count (so we will know when to delete it) and a "cnt"
  25514. ** field that tells us its internal lock status. cnt==0 means the
  25515. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  25516. ** cnt>0 means there are cnt shared locks on the file.
  25517. **
  25518. ** Any attempt to lock or unlock a file first checks the locking
  25519. ** structure. The fcntl() system call is only invoked to set a
  25520. ** POSIX lock if the internal lock structure transitions between
  25521. ** a locked and an unlocked state.
  25522. **
  25523. ** But wait: there are yet more problems with POSIX advisory locks.
  25524. **
  25525. ** If you close a file descriptor that points to a file that has locks,
  25526. ** all locks on that file that are owned by the current process are
  25527. ** released. To work around this problem, each unixInodeInfo object
  25528. ** maintains a count of the number of pending locks on tha inode.
  25529. ** When an attempt is made to close an unixFile, if there are
  25530. ** other unixFile open on the same inode that are holding locks, the call
  25531. ** to close() the file descriptor is deferred until all of the locks clear.
  25532. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  25533. ** be closed and that list is walked (and cleared) when the last lock
  25534. ** clears.
  25535. **
  25536. ** Yet another problem: LinuxThreads do not play well with posix locks.
  25537. **
  25538. ** Many older versions of linux use the LinuxThreads library which is
  25539. ** not posix compliant. Under LinuxThreads, a lock created by thread
  25540. ** A cannot be modified or overridden by a different thread B.
  25541. ** Only thread A can modify the lock. Locking behavior is correct
  25542. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  25543. ** on linux - with NPTL a lock created by thread A can override locks
  25544. ** in thread B. But there is no way to know at compile-time which
  25545. ** threading library is being used. So there is no way to know at
  25546. ** compile-time whether or not thread A can override locks on thread B.
  25547. ** One has to do a run-time check to discover the behavior of the
  25548. ** current process.
  25549. **
  25550. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  25551. ** was dropped beginning with version 3.7.0. SQLite will still work with
  25552. ** LinuxThreads provided that (1) there is no more than one connection
  25553. ** per database file in the same process and (2) database connections
  25554. ** do not move across threads.
  25555. */
  25556. /*
  25557. ** An instance of the following structure serves as the key used
  25558. ** to locate a particular unixInodeInfo object.
  25559. */
  25560. struct unixFileId {
  25561. dev_t dev; /* Device number */
  25562. #if OS_VXWORKS
  25563. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  25564. #else
  25565. ino_t ino; /* Inode number */
  25566. #endif
  25567. };
  25568. /*
  25569. ** An instance of the following structure is allocated for each open
  25570. ** inode. Or, on LinuxThreads, there is one of these structures for
  25571. ** each inode opened by each thread.
  25572. **
  25573. ** A single inode can have multiple file descriptors, so each unixFile
  25574. ** structure contains a pointer to an instance of this object and this
  25575. ** object keeps a count of the number of unixFile pointing to it.
  25576. */
  25577. struct unixInodeInfo {
  25578. struct unixFileId fileId; /* The lookup key */
  25579. int nShared; /* Number of SHARED locks held */
  25580. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  25581. unsigned char bProcessLock; /* An exclusive process lock is held */
  25582. int nRef; /* Number of pointers to this structure */
  25583. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  25584. int nLock; /* Number of outstanding file locks */
  25585. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  25586. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  25587. unixInodeInfo *pPrev; /* .... doubly linked */
  25588. #if SQLITE_ENABLE_LOCKING_STYLE
  25589. unsigned long long sharedByte; /* for AFP simulated shared lock */
  25590. #endif
  25591. #if OS_VXWORKS
  25592. sem_t *pSem; /* Named POSIX semaphore */
  25593. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  25594. #endif
  25595. };
  25596. /*
  25597. ** A lists of all unixInodeInfo objects.
  25598. */
  25599. static unixInodeInfo *inodeList = 0;
  25600. /*
  25601. **
  25602. ** This function - unixLogError_x(), is only ever called via the macro
  25603. ** unixLogError().
  25604. **
  25605. ** It is invoked after an error occurs in an OS function and errno has been
  25606. ** set. It logs a message using sqlite3_log() containing the current value of
  25607. ** errno and, if possible, the human-readable equivalent from strerror() or
  25608. ** strerror_r().
  25609. **
  25610. ** The first argument passed to the macro should be the error code that
  25611. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  25612. ** The two subsequent arguments should be the name of the OS function that
  25613. ** failed (e.g. "unlink", "open") and the associated file-system path,
  25614. ** if any.
  25615. */
  25616. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  25617. static int unixLogErrorAtLine(
  25618. int errcode, /* SQLite error code */
  25619. const char *zFunc, /* Name of OS function that failed */
  25620. const char *zPath, /* File path associated with error */
  25621. int iLine /* Source line number where error occurred */
  25622. ){
  25623. char *zErr; /* Message from strerror() or equivalent */
  25624. int iErrno = errno; /* Saved syscall error number */
  25625. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  25626. ** the strerror() function to obtain the human-readable error message
  25627. ** equivalent to errno. Otherwise, use strerror_r().
  25628. */
  25629. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  25630. char aErr[80];
  25631. memset(aErr, 0, sizeof(aErr));
  25632. zErr = aErr;
  25633. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  25634. ** assume that the system provides the GNU version of strerror_r() that
  25635. ** returns a pointer to a buffer containing the error message. That pointer
  25636. ** may point to aErr[], or it may point to some static storage somewhere.
  25637. ** Otherwise, assume that the system provides the POSIX version of
  25638. ** strerror_r(), which always writes an error message into aErr[].
  25639. **
  25640. ** If the code incorrectly assumes that it is the POSIX version that is
  25641. ** available, the error message will often be an empty string. Not a
  25642. ** huge problem. Incorrectly concluding that the GNU version is available
  25643. ** could lead to a segfault though.
  25644. */
  25645. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  25646. zErr =
  25647. # endif
  25648. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  25649. #elif SQLITE_THREADSAFE
  25650. /* This is a threadsafe build, but strerror_r() is not available. */
  25651. zErr = "";
  25652. #else
  25653. /* Non-threadsafe build, use strerror(). */
  25654. zErr = strerror(iErrno);
  25655. #endif
  25656. if( zPath==0 ) zPath = "";
  25657. sqlite3_log(errcode,
  25658. "os_unix.c:%d: (%d) %s(%s) - %s",
  25659. iLine, iErrno, zFunc, zPath, zErr
  25660. );
  25661. return errcode;
  25662. }
  25663. /*
  25664. ** Close a file descriptor.
  25665. **
  25666. ** We assume that close() almost always works, since it is only in a
  25667. ** very sick application or on a very sick platform that it might fail.
  25668. ** If it does fail, simply leak the file descriptor, but do log the
  25669. ** error.
  25670. **
  25671. ** Note that it is not safe to retry close() after EINTR since the
  25672. ** file descriptor might have already been reused by another thread.
  25673. ** So we don't even try to recover from an EINTR. Just log the error
  25674. ** and move on.
  25675. */
  25676. static void robust_close(unixFile *pFile, int h, int lineno){
  25677. if( osClose(h) ){
  25678. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  25679. pFile ? pFile->zPath : 0, lineno);
  25680. }
  25681. }
  25682. /*
  25683. ** Set the pFile->lastErrno. Do this in a subroutine as that provides
  25684. ** a convenient place to set a breakpoint.
  25685. */
  25686. static void storeLastErrno(unixFile *pFile, int error){
  25687. pFile->lastErrno = error;
  25688. }
  25689. /*
  25690. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  25691. */
  25692. static void closePendingFds(unixFile *pFile){
  25693. unixInodeInfo *pInode = pFile->pInode;
  25694. UnixUnusedFd *p;
  25695. UnixUnusedFd *pNext;
  25696. for(p=pInode->pUnused; p; p=pNext){
  25697. pNext = p->pNext;
  25698. robust_close(pFile, p->fd, __LINE__);
  25699. sqlite3_free(p);
  25700. }
  25701. pInode->pUnused = 0;
  25702. }
  25703. /*
  25704. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  25705. **
  25706. ** The mutex entered using the unixEnterMutex() function must be held
  25707. ** when this function is called.
  25708. */
  25709. static void releaseInodeInfo(unixFile *pFile){
  25710. unixInodeInfo *pInode = pFile->pInode;
  25711. assert( unixMutexHeld() );
  25712. if( ALWAYS(pInode) ){
  25713. pInode->nRef--;
  25714. if( pInode->nRef==0 ){
  25715. assert( pInode->pShmNode==0 );
  25716. closePendingFds(pFile);
  25717. if( pInode->pPrev ){
  25718. assert( pInode->pPrev->pNext==pInode );
  25719. pInode->pPrev->pNext = pInode->pNext;
  25720. }else{
  25721. assert( inodeList==pInode );
  25722. inodeList = pInode->pNext;
  25723. }
  25724. if( pInode->pNext ){
  25725. assert( pInode->pNext->pPrev==pInode );
  25726. pInode->pNext->pPrev = pInode->pPrev;
  25727. }
  25728. sqlite3_free(pInode);
  25729. }
  25730. }
  25731. }
  25732. /*
  25733. ** Given a file descriptor, locate the unixInodeInfo object that
  25734. ** describes that file descriptor. Create a new one if necessary. The
  25735. ** return value might be uninitialized if an error occurs.
  25736. **
  25737. ** The mutex entered using the unixEnterMutex() function must be held
  25738. ** when this function is called.
  25739. **
  25740. ** Return an appropriate error code.
  25741. */
  25742. static int findInodeInfo(
  25743. unixFile *pFile, /* Unix file with file desc used in the key */
  25744. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  25745. ){
  25746. int rc; /* System call return code */
  25747. int fd; /* The file descriptor for pFile */
  25748. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  25749. struct stat statbuf; /* Low-level file information */
  25750. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  25751. assert( unixMutexHeld() );
  25752. /* Get low-level information about the file that we can used to
  25753. ** create a unique name for the file.
  25754. */
  25755. fd = pFile->h;
  25756. rc = osFstat(fd, &statbuf);
  25757. if( rc!=0 ){
  25758. storeLastErrno(pFile, errno);
  25759. #ifdef EOVERFLOW
  25760. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  25761. #endif
  25762. return SQLITE_IOERR;
  25763. }
  25764. #ifdef __APPLE__
  25765. /* On OS X on an msdos filesystem, the inode number is reported
  25766. ** incorrectly for zero-size files. See ticket #3260. To work
  25767. ** around this problem (we consider it a bug in OS X, not SQLite)
  25768. ** we always increase the file size to 1 by writing a single byte
  25769. ** prior to accessing the inode number. The one byte written is
  25770. ** an ASCII 'S' character which also happens to be the first byte
  25771. ** in the header of every SQLite database. In this way, if there
  25772. ** is a race condition such that another thread has already populated
  25773. ** the first page of the database, no damage is done.
  25774. */
  25775. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  25776. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  25777. if( rc!=1 ){
  25778. storeLastErrno(pFile, errno);
  25779. return SQLITE_IOERR;
  25780. }
  25781. rc = osFstat(fd, &statbuf);
  25782. if( rc!=0 ){
  25783. storeLastErrno(pFile, errno);
  25784. return SQLITE_IOERR;
  25785. }
  25786. }
  25787. #endif
  25788. memset(&fileId, 0, sizeof(fileId));
  25789. fileId.dev = statbuf.st_dev;
  25790. #if OS_VXWORKS
  25791. fileId.pId = pFile->pId;
  25792. #else
  25793. fileId.ino = statbuf.st_ino;
  25794. #endif
  25795. pInode = inodeList;
  25796. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  25797. pInode = pInode->pNext;
  25798. }
  25799. if( pInode==0 ){
  25800. pInode = sqlite3_malloc64( sizeof(*pInode) );
  25801. if( pInode==0 ){
  25802. return SQLITE_NOMEM;
  25803. }
  25804. memset(pInode, 0, sizeof(*pInode));
  25805. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  25806. pInode->nRef = 1;
  25807. pInode->pNext = inodeList;
  25808. pInode->pPrev = 0;
  25809. if( inodeList ) inodeList->pPrev = pInode;
  25810. inodeList = pInode;
  25811. }else{
  25812. pInode->nRef++;
  25813. }
  25814. *ppInode = pInode;
  25815. return SQLITE_OK;
  25816. }
  25817. /*
  25818. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  25819. */
  25820. static int fileHasMoved(unixFile *pFile){
  25821. #if OS_VXWORKS
  25822. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  25823. #else
  25824. struct stat buf;
  25825. return pFile->pInode!=0 &&
  25826. (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
  25827. #endif
  25828. }
  25829. /*
  25830. ** Check a unixFile that is a database. Verify the following:
  25831. **
  25832. ** (1) There is exactly one hard link on the file
  25833. ** (2) The file is not a symbolic link
  25834. ** (3) The file has not been renamed or unlinked
  25835. **
  25836. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  25837. */
  25838. static void verifyDbFile(unixFile *pFile){
  25839. struct stat buf;
  25840. int rc;
  25841. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  25842. /* One or more of the following warnings have already been issued. Do not
  25843. ** repeat them so as not to clutter the error log */
  25844. return;
  25845. }
  25846. rc = osFstat(pFile->h, &buf);
  25847. if( rc!=0 ){
  25848. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  25849. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25850. return;
  25851. }
  25852. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  25853. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  25854. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25855. return;
  25856. }
  25857. if( buf.st_nlink>1 ){
  25858. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  25859. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25860. return;
  25861. }
  25862. if( fileHasMoved(pFile) ){
  25863. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  25864. pFile->ctrlFlags |= UNIXFILE_WARNED;
  25865. return;
  25866. }
  25867. }
  25868. /*
  25869. ** This routine checks if there is a RESERVED lock held on the specified
  25870. ** file by this or any other process. If such a lock is held, set *pResOut
  25871. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25872. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25873. */
  25874. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  25875. int rc = SQLITE_OK;
  25876. int reserved = 0;
  25877. unixFile *pFile = (unixFile*)id;
  25878. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25879. assert( pFile );
  25880. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  25881. /* Check if a thread in this process holds such a lock */
  25882. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  25883. reserved = 1;
  25884. }
  25885. /* Otherwise see if some other process holds it.
  25886. */
  25887. #ifndef __DJGPP__
  25888. if( !reserved && !pFile->pInode->bProcessLock ){
  25889. struct flock lock;
  25890. lock.l_whence = SEEK_SET;
  25891. lock.l_start = RESERVED_BYTE;
  25892. lock.l_len = 1;
  25893. lock.l_type = F_WRLCK;
  25894. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  25895. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  25896. storeLastErrno(pFile, errno);
  25897. } else if( lock.l_type!=F_UNLCK ){
  25898. reserved = 1;
  25899. }
  25900. }
  25901. #endif
  25902. unixLeaveMutex();
  25903. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  25904. *pResOut = reserved;
  25905. return rc;
  25906. }
  25907. /*
  25908. ** Attempt to set a system-lock on the file pFile. The lock is
  25909. ** described by pLock.
  25910. **
  25911. ** If the pFile was opened read/write from unix-excl, then the only lock
  25912. ** ever obtained is an exclusive lock, and it is obtained exactly once
  25913. ** the first time any lock is attempted. All subsequent system locking
  25914. ** operations become no-ops. Locking operations still happen internally,
  25915. ** in order to coordinate access between separate database connections
  25916. ** within this process, but all of that is handled in memory and the
  25917. ** operating system does not participate.
  25918. **
  25919. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  25920. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  25921. ** and is read-only.
  25922. **
  25923. ** Zero is returned if the call completes successfully, or -1 if a call
  25924. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  25925. */
  25926. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  25927. int rc;
  25928. unixInodeInfo *pInode = pFile->pInode;
  25929. assert( unixMutexHeld() );
  25930. assert( pInode!=0 );
  25931. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  25932. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  25933. ){
  25934. if( pInode->bProcessLock==0 ){
  25935. struct flock lock;
  25936. assert( pInode->nLock==0 );
  25937. lock.l_whence = SEEK_SET;
  25938. lock.l_start = SHARED_FIRST;
  25939. lock.l_len = SHARED_SIZE;
  25940. lock.l_type = F_WRLCK;
  25941. rc = osFcntl(pFile->h, F_SETLK, &lock);
  25942. if( rc<0 ) return rc;
  25943. pInode->bProcessLock = 1;
  25944. pInode->nLock++;
  25945. }else{
  25946. rc = 0;
  25947. }
  25948. }else{
  25949. rc = osFcntl(pFile->h, F_SETLK, pLock);
  25950. }
  25951. return rc;
  25952. }
  25953. /*
  25954. ** Lock the file with the lock specified by parameter eFileLock - one
  25955. ** of the following:
  25956. **
  25957. ** (1) SHARED_LOCK
  25958. ** (2) RESERVED_LOCK
  25959. ** (3) PENDING_LOCK
  25960. ** (4) EXCLUSIVE_LOCK
  25961. **
  25962. ** Sometimes when requesting one lock state, additional lock states
  25963. ** are inserted in between. The locking might fail on one of the later
  25964. ** transitions leaving the lock state different from what it started but
  25965. ** still short of its goal. The following chart shows the allowed
  25966. ** transitions and the inserted intermediate states:
  25967. **
  25968. ** UNLOCKED -> SHARED
  25969. ** SHARED -> RESERVED
  25970. ** SHARED -> (PENDING) -> EXCLUSIVE
  25971. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25972. ** PENDING -> EXCLUSIVE
  25973. **
  25974. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25975. ** routine to lower a locking level.
  25976. */
  25977. static int unixLock(sqlite3_file *id, int eFileLock){
  25978. /* The following describes the implementation of the various locks and
  25979. ** lock transitions in terms of the POSIX advisory shared and exclusive
  25980. ** lock primitives (called read-locks and write-locks below, to avoid
  25981. ** confusion with SQLite lock names). The algorithms are complicated
  25982. ** slightly in order to be compatible with windows systems simultaneously
  25983. ** accessing the same database file, in case that is ever required.
  25984. **
  25985. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  25986. ** byte', each single bytes at well known offsets, and the 'shared byte
  25987. ** range', a range of 510 bytes at a well known offset.
  25988. **
  25989. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  25990. ** byte'. If this is successful, a random byte from the 'shared byte
  25991. ** range' is read-locked and the lock on the 'pending byte' released.
  25992. **
  25993. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  25994. ** A RESERVED lock is implemented by grabbing a write-lock on the
  25995. ** 'reserved byte'.
  25996. **
  25997. ** A process may only obtain a PENDING lock after it has obtained a
  25998. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  25999. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  26000. ** obtained, but existing SHARED locks are allowed to persist. A process
  26001. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  26002. ** This property is used by the algorithm for rolling back a journal file
  26003. ** after a crash.
  26004. **
  26005. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  26006. ** implemented by obtaining a write-lock on the entire 'shared byte
  26007. ** range'. Since all other locks require a read-lock on one of the bytes
  26008. ** within this range, this ensures that no other locks are held on the
  26009. ** database.
  26010. **
  26011. ** The reason a single byte cannot be used instead of the 'shared byte
  26012. ** range' is that some versions of windows do not support read-locks. By
  26013. ** locking a random byte from a range, concurrent SHARED locks may exist
  26014. ** even if the locking primitive used is always a write-lock.
  26015. */
  26016. int rc = SQLITE_OK;
  26017. unixFile *pFile = (unixFile*)id;
  26018. unixInodeInfo *pInode;
  26019. struct flock lock;
  26020. int tErrno = 0;
  26021. assert( pFile );
  26022. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  26023. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  26024. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
  26025. osGetpid(0)));
  26026. /* If there is already a lock of this type or more restrictive on the
  26027. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  26028. ** unixEnterMutex() hasn't been called yet.
  26029. */
  26030. if( pFile->eFileLock>=eFileLock ){
  26031. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  26032. azFileLock(eFileLock)));
  26033. return SQLITE_OK;
  26034. }
  26035. /* Make sure the locking sequence is correct.
  26036. ** (1) We never move from unlocked to anything higher than shared lock.
  26037. ** (2) SQLite never explicitly requests a pendig lock.
  26038. ** (3) A shared lock is always held when a reserve lock is requested.
  26039. */
  26040. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  26041. assert( eFileLock!=PENDING_LOCK );
  26042. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  26043. /* This mutex is needed because pFile->pInode is shared across threads
  26044. */
  26045. unixEnterMutex();
  26046. pInode = pFile->pInode;
  26047. /* If some thread using this PID has a lock via a different unixFile*
  26048. ** handle that precludes the requested lock, return BUSY.
  26049. */
  26050. if( (pFile->eFileLock!=pInode->eFileLock &&
  26051. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  26052. ){
  26053. rc = SQLITE_BUSY;
  26054. goto end_lock;
  26055. }
  26056. /* If a SHARED lock is requested, and some thread using this PID already
  26057. ** has a SHARED or RESERVED lock, then increment reference counts and
  26058. ** return SQLITE_OK.
  26059. */
  26060. if( eFileLock==SHARED_LOCK &&
  26061. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  26062. assert( eFileLock==SHARED_LOCK );
  26063. assert( pFile->eFileLock==0 );
  26064. assert( pInode->nShared>0 );
  26065. pFile->eFileLock = SHARED_LOCK;
  26066. pInode->nShared++;
  26067. pInode->nLock++;
  26068. goto end_lock;
  26069. }
  26070. /* A PENDING lock is needed before acquiring a SHARED lock and before
  26071. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  26072. ** be released.
  26073. */
  26074. lock.l_len = 1L;
  26075. lock.l_whence = SEEK_SET;
  26076. if( eFileLock==SHARED_LOCK
  26077. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  26078. ){
  26079. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  26080. lock.l_start = PENDING_BYTE;
  26081. if( unixFileLock(pFile, &lock) ){
  26082. tErrno = errno;
  26083. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26084. if( rc!=SQLITE_BUSY ){
  26085. storeLastErrno(pFile, tErrno);
  26086. }
  26087. goto end_lock;
  26088. }
  26089. }
  26090. /* If control gets to this point, then actually go ahead and make
  26091. ** operating system calls for the specified lock.
  26092. */
  26093. if( eFileLock==SHARED_LOCK ){
  26094. assert( pInode->nShared==0 );
  26095. assert( pInode->eFileLock==0 );
  26096. assert( rc==SQLITE_OK );
  26097. /* Now get the read-lock */
  26098. lock.l_start = SHARED_FIRST;
  26099. lock.l_len = SHARED_SIZE;
  26100. if( unixFileLock(pFile, &lock) ){
  26101. tErrno = errno;
  26102. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26103. }
  26104. /* Drop the temporary PENDING lock */
  26105. lock.l_start = PENDING_BYTE;
  26106. lock.l_len = 1L;
  26107. lock.l_type = F_UNLCK;
  26108. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  26109. /* This could happen with a network mount */
  26110. tErrno = errno;
  26111. rc = SQLITE_IOERR_UNLOCK;
  26112. }
  26113. if( rc ){
  26114. if( rc!=SQLITE_BUSY ){
  26115. storeLastErrno(pFile, tErrno);
  26116. }
  26117. goto end_lock;
  26118. }else{
  26119. pFile->eFileLock = SHARED_LOCK;
  26120. pInode->nLock++;
  26121. pInode->nShared = 1;
  26122. }
  26123. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  26124. /* We are trying for an exclusive lock but another thread in this
  26125. ** same process is still holding a shared lock. */
  26126. rc = SQLITE_BUSY;
  26127. }else{
  26128. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  26129. ** assumed that there is a SHARED or greater lock on the file
  26130. ** already.
  26131. */
  26132. assert( 0!=pFile->eFileLock );
  26133. lock.l_type = F_WRLCK;
  26134. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  26135. if( eFileLock==RESERVED_LOCK ){
  26136. lock.l_start = RESERVED_BYTE;
  26137. lock.l_len = 1L;
  26138. }else{
  26139. lock.l_start = SHARED_FIRST;
  26140. lock.l_len = SHARED_SIZE;
  26141. }
  26142. if( unixFileLock(pFile, &lock) ){
  26143. tErrno = errno;
  26144. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26145. if( rc!=SQLITE_BUSY ){
  26146. storeLastErrno(pFile, tErrno);
  26147. }
  26148. }
  26149. }
  26150. #ifdef SQLITE_DEBUG
  26151. /* Set up the transaction-counter change checking flags when
  26152. ** transitioning from a SHARED to a RESERVED lock. The change
  26153. ** from SHARED to RESERVED marks the beginning of a normal
  26154. ** write operation (not a hot journal rollback).
  26155. */
  26156. if( rc==SQLITE_OK
  26157. && pFile->eFileLock<=SHARED_LOCK
  26158. && eFileLock==RESERVED_LOCK
  26159. ){
  26160. pFile->transCntrChng = 0;
  26161. pFile->dbUpdate = 0;
  26162. pFile->inNormalWrite = 1;
  26163. }
  26164. #endif
  26165. if( rc==SQLITE_OK ){
  26166. pFile->eFileLock = eFileLock;
  26167. pInode->eFileLock = eFileLock;
  26168. }else if( eFileLock==EXCLUSIVE_LOCK ){
  26169. pFile->eFileLock = PENDING_LOCK;
  26170. pInode->eFileLock = PENDING_LOCK;
  26171. }
  26172. end_lock:
  26173. unixLeaveMutex();
  26174. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  26175. rc==SQLITE_OK ? "ok" : "failed"));
  26176. return rc;
  26177. }
  26178. /*
  26179. ** Add the file descriptor used by file handle pFile to the corresponding
  26180. ** pUnused list.
  26181. */
  26182. static void setPendingFd(unixFile *pFile){
  26183. unixInodeInfo *pInode = pFile->pInode;
  26184. UnixUnusedFd *p = pFile->pUnused;
  26185. p->pNext = pInode->pUnused;
  26186. pInode->pUnused = p;
  26187. pFile->h = -1;
  26188. pFile->pUnused = 0;
  26189. }
  26190. /*
  26191. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26192. ** must be either NO_LOCK or SHARED_LOCK.
  26193. **
  26194. ** If the locking level of the file descriptor is already at or below
  26195. ** the requested locking level, this routine is a no-op.
  26196. **
  26197. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  26198. ** the byte range is divided into 2 parts and the first part is unlocked then
  26199. ** set to a read lock, then the other part is simply unlocked. This works
  26200. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  26201. ** remove the write lock on a region when a read lock is set.
  26202. */
  26203. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  26204. unixFile *pFile = (unixFile*)id;
  26205. unixInodeInfo *pInode;
  26206. struct flock lock;
  26207. int rc = SQLITE_OK;
  26208. assert( pFile );
  26209. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  26210. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  26211. osGetpid(0)));
  26212. assert( eFileLock<=SHARED_LOCK );
  26213. if( pFile->eFileLock<=eFileLock ){
  26214. return SQLITE_OK;
  26215. }
  26216. unixEnterMutex();
  26217. pInode = pFile->pInode;
  26218. assert( pInode->nShared!=0 );
  26219. if( pFile->eFileLock>SHARED_LOCK ){
  26220. assert( pInode->eFileLock==pFile->eFileLock );
  26221. #ifdef SQLITE_DEBUG
  26222. /* When reducing a lock such that other processes can start
  26223. ** reading the database file again, make sure that the
  26224. ** transaction counter was updated if any part of the database
  26225. ** file changed. If the transaction counter is not updated,
  26226. ** other connections to the same file might not realize that
  26227. ** the file has changed and hence might not know to flush their
  26228. ** cache. The use of a stale cache can lead to database corruption.
  26229. */
  26230. pFile->inNormalWrite = 0;
  26231. #endif
  26232. /* downgrading to a shared lock on NFS involves clearing the write lock
  26233. ** before establishing the readlock - to avoid a race condition we downgrade
  26234. ** the lock in 2 blocks, so that part of the range will be covered by a
  26235. ** write lock until the rest is covered by a read lock:
  26236. ** 1: [WWWWW]
  26237. ** 2: [....W]
  26238. ** 3: [RRRRW]
  26239. ** 4: [RRRR.]
  26240. */
  26241. if( eFileLock==SHARED_LOCK ){
  26242. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  26243. (void)handleNFSUnlock;
  26244. assert( handleNFSUnlock==0 );
  26245. #endif
  26246. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26247. if( handleNFSUnlock ){
  26248. int tErrno; /* Error code from system call errors */
  26249. off_t divSize = SHARED_SIZE - 1;
  26250. lock.l_type = F_UNLCK;
  26251. lock.l_whence = SEEK_SET;
  26252. lock.l_start = SHARED_FIRST;
  26253. lock.l_len = divSize;
  26254. if( unixFileLock(pFile, &lock)==(-1) ){
  26255. tErrno = errno;
  26256. rc = SQLITE_IOERR_UNLOCK;
  26257. if( IS_LOCK_ERROR(rc) ){
  26258. storeLastErrno(pFile, tErrno);
  26259. }
  26260. goto end_unlock;
  26261. }
  26262. lock.l_type = F_RDLCK;
  26263. lock.l_whence = SEEK_SET;
  26264. lock.l_start = SHARED_FIRST;
  26265. lock.l_len = divSize;
  26266. if( unixFileLock(pFile, &lock)==(-1) ){
  26267. tErrno = errno;
  26268. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  26269. if( IS_LOCK_ERROR(rc) ){
  26270. storeLastErrno(pFile, tErrno);
  26271. }
  26272. goto end_unlock;
  26273. }
  26274. lock.l_type = F_UNLCK;
  26275. lock.l_whence = SEEK_SET;
  26276. lock.l_start = SHARED_FIRST+divSize;
  26277. lock.l_len = SHARED_SIZE-divSize;
  26278. if( unixFileLock(pFile, &lock)==(-1) ){
  26279. tErrno = errno;
  26280. rc = SQLITE_IOERR_UNLOCK;
  26281. if( IS_LOCK_ERROR(rc) ){
  26282. storeLastErrno(pFile, tErrno);
  26283. }
  26284. goto end_unlock;
  26285. }
  26286. }else
  26287. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26288. {
  26289. lock.l_type = F_RDLCK;
  26290. lock.l_whence = SEEK_SET;
  26291. lock.l_start = SHARED_FIRST;
  26292. lock.l_len = SHARED_SIZE;
  26293. if( unixFileLock(pFile, &lock) ){
  26294. /* In theory, the call to unixFileLock() cannot fail because another
  26295. ** process is holding an incompatible lock. If it does, this
  26296. ** indicates that the other process is not following the locking
  26297. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  26298. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  26299. ** an assert to fail). */
  26300. rc = SQLITE_IOERR_RDLOCK;
  26301. storeLastErrno(pFile, errno);
  26302. goto end_unlock;
  26303. }
  26304. }
  26305. }
  26306. lock.l_type = F_UNLCK;
  26307. lock.l_whence = SEEK_SET;
  26308. lock.l_start = PENDING_BYTE;
  26309. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  26310. if( unixFileLock(pFile, &lock)==0 ){
  26311. pInode->eFileLock = SHARED_LOCK;
  26312. }else{
  26313. rc = SQLITE_IOERR_UNLOCK;
  26314. storeLastErrno(pFile, errno);
  26315. goto end_unlock;
  26316. }
  26317. }
  26318. if( eFileLock==NO_LOCK ){
  26319. /* Decrement the shared lock counter. Release the lock using an
  26320. ** OS call only when all threads in this same process have released
  26321. ** the lock.
  26322. */
  26323. pInode->nShared--;
  26324. if( pInode->nShared==0 ){
  26325. lock.l_type = F_UNLCK;
  26326. lock.l_whence = SEEK_SET;
  26327. lock.l_start = lock.l_len = 0L;
  26328. if( unixFileLock(pFile, &lock)==0 ){
  26329. pInode->eFileLock = NO_LOCK;
  26330. }else{
  26331. rc = SQLITE_IOERR_UNLOCK;
  26332. storeLastErrno(pFile, errno);
  26333. pInode->eFileLock = NO_LOCK;
  26334. pFile->eFileLock = NO_LOCK;
  26335. }
  26336. }
  26337. /* Decrement the count of locks against this same file. When the
  26338. ** count reaches zero, close any other file descriptors whose close
  26339. ** was deferred because of outstanding locks.
  26340. */
  26341. pInode->nLock--;
  26342. assert( pInode->nLock>=0 );
  26343. if( pInode->nLock==0 ){
  26344. closePendingFds(pFile);
  26345. }
  26346. }
  26347. end_unlock:
  26348. unixLeaveMutex();
  26349. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  26350. return rc;
  26351. }
  26352. /*
  26353. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26354. ** must be either NO_LOCK or SHARED_LOCK.
  26355. **
  26356. ** If the locking level of the file descriptor is already at or below
  26357. ** the requested locking level, this routine is a no-op.
  26358. */
  26359. static int unixUnlock(sqlite3_file *id, int eFileLock){
  26360. #if SQLITE_MAX_MMAP_SIZE>0
  26361. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  26362. #endif
  26363. return posixUnlock(id, eFileLock, 0);
  26364. }
  26365. #if SQLITE_MAX_MMAP_SIZE>0
  26366. static int unixMapfile(unixFile *pFd, i64 nByte);
  26367. static void unixUnmapfile(unixFile *pFd);
  26368. #endif
  26369. /*
  26370. ** This function performs the parts of the "close file" operation
  26371. ** common to all locking schemes. It closes the directory and file
  26372. ** handles, if they are valid, and sets all fields of the unixFile
  26373. ** structure to 0.
  26374. **
  26375. ** It is *not* necessary to hold the mutex when this routine is called,
  26376. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  26377. ** vxworksReleaseFileId() routine.
  26378. */
  26379. static int closeUnixFile(sqlite3_file *id){
  26380. unixFile *pFile = (unixFile*)id;
  26381. #if SQLITE_MAX_MMAP_SIZE>0
  26382. unixUnmapfile(pFile);
  26383. #endif
  26384. if( pFile->h>=0 ){
  26385. robust_close(pFile, pFile->h, __LINE__);
  26386. pFile->h = -1;
  26387. }
  26388. #if OS_VXWORKS
  26389. if( pFile->pId ){
  26390. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  26391. osUnlink(pFile->pId->zCanonicalName);
  26392. }
  26393. vxworksReleaseFileId(pFile->pId);
  26394. pFile->pId = 0;
  26395. }
  26396. #endif
  26397. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  26398. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  26399. osUnlink(pFile->zPath);
  26400. sqlite3_free(*(char**)&pFile->zPath);
  26401. pFile->zPath = 0;
  26402. }
  26403. #endif
  26404. OSTRACE(("CLOSE %-3d\n", pFile->h));
  26405. OpenCounter(-1);
  26406. sqlite3_free(pFile->pUnused);
  26407. memset(pFile, 0, sizeof(unixFile));
  26408. return SQLITE_OK;
  26409. }
  26410. /*
  26411. ** Close a file.
  26412. */
  26413. static int unixClose(sqlite3_file *id){
  26414. int rc = SQLITE_OK;
  26415. unixFile *pFile = (unixFile *)id;
  26416. verifyDbFile(pFile);
  26417. unixUnlock(id, NO_LOCK);
  26418. unixEnterMutex();
  26419. /* unixFile.pInode is always valid here. Otherwise, a different close
  26420. ** routine (e.g. nolockClose()) would be called instead.
  26421. */
  26422. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  26423. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  26424. /* If there are outstanding locks, do not actually close the file just
  26425. ** yet because that would clear those locks. Instead, add the file
  26426. ** descriptor to pInode->pUnused list. It will be automatically closed
  26427. ** when the last lock is cleared.
  26428. */
  26429. setPendingFd(pFile);
  26430. }
  26431. releaseInodeInfo(pFile);
  26432. rc = closeUnixFile(id);
  26433. unixLeaveMutex();
  26434. return rc;
  26435. }
  26436. /************** End of the posix advisory lock implementation *****************
  26437. ******************************************************************************/
  26438. /******************************************************************************
  26439. ****************************** No-op Locking **********************************
  26440. **
  26441. ** Of the various locking implementations available, this is by far the
  26442. ** simplest: locking is ignored. No attempt is made to lock the database
  26443. ** file for reading or writing.
  26444. **
  26445. ** This locking mode is appropriate for use on read-only databases
  26446. ** (ex: databases that are burned into CD-ROM, for example.) It can
  26447. ** also be used if the application employs some external mechanism to
  26448. ** prevent simultaneous access of the same database by two or more
  26449. ** database connections. But there is a serious risk of database
  26450. ** corruption if this locking mode is used in situations where multiple
  26451. ** database connections are accessing the same database file at the same
  26452. ** time and one or more of those connections are writing.
  26453. */
  26454. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  26455. UNUSED_PARAMETER(NotUsed);
  26456. *pResOut = 0;
  26457. return SQLITE_OK;
  26458. }
  26459. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  26460. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  26461. return SQLITE_OK;
  26462. }
  26463. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  26464. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  26465. return SQLITE_OK;
  26466. }
  26467. /*
  26468. ** Close the file.
  26469. */
  26470. static int nolockClose(sqlite3_file *id) {
  26471. return closeUnixFile(id);
  26472. }
  26473. /******************* End of the no-op lock implementation *********************
  26474. ******************************************************************************/
  26475. /******************************************************************************
  26476. ************************* Begin dot-file Locking ******************************
  26477. **
  26478. ** The dotfile locking implementation uses the existence of separate lock
  26479. ** files (really a directory) to control access to the database. This works
  26480. ** on just about every filesystem imaginable. But there are serious downsides:
  26481. **
  26482. ** (1) There is zero concurrency. A single reader blocks all other
  26483. ** connections from reading or writing the database.
  26484. **
  26485. ** (2) An application crash or power loss can leave stale lock files
  26486. ** sitting around that need to be cleared manually.
  26487. **
  26488. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  26489. ** other locking strategy is available.
  26490. **
  26491. ** Dotfile locking works by creating a subdirectory in the same directory as
  26492. ** the database and with the same name but with a ".lock" extension added.
  26493. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  26494. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  26495. */
  26496. /*
  26497. ** The file suffix added to the data base filename in order to create the
  26498. ** lock directory.
  26499. */
  26500. #define DOTLOCK_SUFFIX ".lock"
  26501. /*
  26502. ** This routine checks if there is a RESERVED lock held on the specified
  26503. ** file by this or any other process. If such a lock is held, set *pResOut
  26504. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26505. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26506. **
  26507. ** In dotfile locking, either a lock exists or it does not. So in this
  26508. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  26509. ** is held on the file and false if the file is unlocked.
  26510. */
  26511. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  26512. int rc = SQLITE_OK;
  26513. int reserved = 0;
  26514. unixFile *pFile = (unixFile*)id;
  26515. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26516. assert( pFile );
  26517. /* Check if a thread in this process holds such a lock */
  26518. if( pFile->eFileLock>SHARED_LOCK ){
  26519. /* Either this connection or some other connection in the same process
  26520. ** holds a lock on the file. No need to check further. */
  26521. reserved = 1;
  26522. }else{
  26523. /* The lock is held if and only if the lockfile exists */
  26524. const char *zLockFile = (const char*)pFile->lockingContext;
  26525. reserved = osAccess(zLockFile, 0)==0;
  26526. }
  26527. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  26528. *pResOut = reserved;
  26529. return rc;
  26530. }
  26531. /*
  26532. ** Lock the file with the lock specified by parameter eFileLock - one
  26533. ** of the following:
  26534. **
  26535. ** (1) SHARED_LOCK
  26536. ** (2) RESERVED_LOCK
  26537. ** (3) PENDING_LOCK
  26538. ** (4) EXCLUSIVE_LOCK
  26539. **
  26540. ** Sometimes when requesting one lock state, additional lock states
  26541. ** are inserted in between. The locking might fail on one of the later
  26542. ** transitions leaving the lock state different from what it started but
  26543. ** still short of its goal. The following chart shows the allowed
  26544. ** transitions and the inserted intermediate states:
  26545. **
  26546. ** UNLOCKED -> SHARED
  26547. ** SHARED -> RESERVED
  26548. ** SHARED -> (PENDING) -> EXCLUSIVE
  26549. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26550. ** PENDING -> EXCLUSIVE
  26551. **
  26552. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26553. ** routine to lower a locking level.
  26554. **
  26555. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  26556. ** But we track the other locking levels internally.
  26557. */
  26558. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  26559. unixFile *pFile = (unixFile*)id;
  26560. char *zLockFile = (char *)pFile->lockingContext;
  26561. int rc = SQLITE_OK;
  26562. /* If we have any lock, then the lock file already exists. All we have
  26563. ** to do is adjust our internal record of the lock level.
  26564. */
  26565. if( pFile->eFileLock > NO_LOCK ){
  26566. pFile->eFileLock = eFileLock;
  26567. /* Always update the timestamp on the old file */
  26568. #ifdef HAVE_UTIME
  26569. utime(zLockFile, NULL);
  26570. #else
  26571. utimes(zLockFile, NULL);
  26572. #endif
  26573. return SQLITE_OK;
  26574. }
  26575. /* grab an exclusive lock */
  26576. rc = osMkdir(zLockFile, 0777);
  26577. if( rc<0 ){
  26578. /* failed to open/create the lock directory */
  26579. int tErrno = errno;
  26580. if( EEXIST == tErrno ){
  26581. rc = SQLITE_BUSY;
  26582. } else {
  26583. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26584. if( IS_LOCK_ERROR(rc) ){
  26585. storeLastErrno(pFile, tErrno);
  26586. }
  26587. }
  26588. return rc;
  26589. }
  26590. /* got it, set the type and return ok */
  26591. pFile->eFileLock = eFileLock;
  26592. return rc;
  26593. }
  26594. /*
  26595. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26596. ** must be either NO_LOCK or SHARED_LOCK.
  26597. **
  26598. ** If the locking level of the file descriptor is already at or below
  26599. ** the requested locking level, this routine is a no-op.
  26600. **
  26601. ** When the locking level reaches NO_LOCK, delete the lock file.
  26602. */
  26603. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  26604. unixFile *pFile = (unixFile*)id;
  26605. char *zLockFile = (char *)pFile->lockingContext;
  26606. int rc;
  26607. assert( pFile );
  26608. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  26609. pFile->eFileLock, osGetpid(0)));
  26610. assert( eFileLock<=SHARED_LOCK );
  26611. /* no-op if possible */
  26612. if( pFile->eFileLock==eFileLock ){
  26613. return SQLITE_OK;
  26614. }
  26615. /* To downgrade to shared, simply update our internal notion of the
  26616. ** lock state. No need to mess with the file on disk.
  26617. */
  26618. if( eFileLock==SHARED_LOCK ){
  26619. pFile->eFileLock = SHARED_LOCK;
  26620. return SQLITE_OK;
  26621. }
  26622. /* To fully unlock the database, delete the lock file */
  26623. assert( eFileLock==NO_LOCK );
  26624. rc = osRmdir(zLockFile);
  26625. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  26626. if( rc<0 ){
  26627. int tErrno = errno;
  26628. rc = 0;
  26629. if( ENOENT != tErrno ){
  26630. rc = SQLITE_IOERR_UNLOCK;
  26631. }
  26632. if( IS_LOCK_ERROR(rc) ){
  26633. storeLastErrno(pFile, tErrno);
  26634. }
  26635. return rc;
  26636. }
  26637. pFile->eFileLock = NO_LOCK;
  26638. return SQLITE_OK;
  26639. }
  26640. /*
  26641. ** Close a file. Make sure the lock has been released before closing.
  26642. */
  26643. static int dotlockClose(sqlite3_file *id) {
  26644. int rc = SQLITE_OK;
  26645. if( id ){
  26646. unixFile *pFile = (unixFile*)id;
  26647. dotlockUnlock(id, NO_LOCK);
  26648. sqlite3_free(pFile->lockingContext);
  26649. rc = closeUnixFile(id);
  26650. }
  26651. return rc;
  26652. }
  26653. /****************** End of the dot-file lock implementation *******************
  26654. ******************************************************************************/
  26655. /******************************************************************************
  26656. ************************** Begin flock Locking ********************************
  26657. **
  26658. ** Use the flock() system call to do file locking.
  26659. **
  26660. ** flock() locking is like dot-file locking in that the various
  26661. ** fine-grain locking levels supported by SQLite are collapsed into
  26662. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  26663. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  26664. ** still works when you do this, but concurrency is reduced since
  26665. ** only a single process can be reading the database at a time.
  26666. **
  26667. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
  26668. */
  26669. #if SQLITE_ENABLE_LOCKING_STYLE
  26670. /*
  26671. ** Retry flock() calls that fail with EINTR
  26672. */
  26673. #ifdef EINTR
  26674. static int robust_flock(int fd, int op){
  26675. int rc;
  26676. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  26677. return rc;
  26678. }
  26679. #else
  26680. # define robust_flock(a,b) flock(a,b)
  26681. #endif
  26682. /*
  26683. ** This routine checks if there is a RESERVED lock held on the specified
  26684. ** file by this or any other process. If such a lock is held, set *pResOut
  26685. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26686. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26687. */
  26688. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  26689. int rc = SQLITE_OK;
  26690. int reserved = 0;
  26691. unixFile *pFile = (unixFile*)id;
  26692. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26693. assert( pFile );
  26694. /* Check if a thread in this process holds such a lock */
  26695. if( pFile->eFileLock>SHARED_LOCK ){
  26696. reserved = 1;
  26697. }
  26698. /* Otherwise see if some other process holds it. */
  26699. if( !reserved ){
  26700. /* attempt to get the lock */
  26701. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  26702. if( !lrc ){
  26703. /* got the lock, unlock it */
  26704. lrc = robust_flock(pFile->h, LOCK_UN);
  26705. if ( lrc ) {
  26706. int tErrno = errno;
  26707. /* unlock failed with an error */
  26708. lrc = SQLITE_IOERR_UNLOCK;
  26709. if( IS_LOCK_ERROR(lrc) ){
  26710. storeLastErrno(pFile, tErrno);
  26711. rc = lrc;
  26712. }
  26713. }
  26714. } else {
  26715. int tErrno = errno;
  26716. reserved = 1;
  26717. /* someone else might have it reserved */
  26718. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26719. if( IS_LOCK_ERROR(lrc) ){
  26720. storeLastErrno(pFile, tErrno);
  26721. rc = lrc;
  26722. }
  26723. }
  26724. }
  26725. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  26726. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  26727. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  26728. rc = SQLITE_OK;
  26729. reserved=1;
  26730. }
  26731. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  26732. *pResOut = reserved;
  26733. return rc;
  26734. }
  26735. /*
  26736. ** Lock the file with the lock specified by parameter eFileLock - one
  26737. ** of the following:
  26738. **
  26739. ** (1) SHARED_LOCK
  26740. ** (2) RESERVED_LOCK
  26741. ** (3) PENDING_LOCK
  26742. ** (4) EXCLUSIVE_LOCK
  26743. **
  26744. ** Sometimes when requesting one lock state, additional lock states
  26745. ** are inserted in between. The locking might fail on one of the later
  26746. ** transitions leaving the lock state different from what it started but
  26747. ** still short of its goal. The following chart shows the allowed
  26748. ** transitions and the inserted intermediate states:
  26749. **
  26750. ** UNLOCKED -> SHARED
  26751. ** SHARED -> RESERVED
  26752. ** SHARED -> (PENDING) -> EXCLUSIVE
  26753. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26754. ** PENDING -> EXCLUSIVE
  26755. **
  26756. ** flock() only really support EXCLUSIVE locks. We track intermediate
  26757. ** lock states in the sqlite3_file structure, but all locks SHARED or
  26758. ** above are really EXCLUSIVE locks and exclude all other processes from
  26759. ** access the file.
  26760. **
  26761. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26762. ** routine to lower a locking level.
  26763. */
  26764. static int flockLock(sqlite3_file *id, int eFileLock) {
  26765. int rc = SQLITE_OK;
  26766. unixFile *pFile = (unixFile*)id;
  26767. assert( pFile );
  26768. /* if we already have a lock, it is exclusive.
  26769. ** Just adjust level and punt on outta here. */
  26770. if (pFile->eFileLock > NO_LOCK) {
  26771. pFile->eFileLock = eFileLock;
  26772. return SQLITE_OK;
  26773. }
  26774. /* grab an exclusive lock */
  26775. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  26776. int tErrno = errno;
  26777. /* didn't get, must be busy */
  26778. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  26779. if( IS_LOCK_ERROR(rc) ){
  26780. storeLastErrno(pFile, tErrno);
  26781. }
  26782. } else {
  26783. /* got it, set the type and return ok */
  26784. pFile->eFileLock = eFileLock;
  26785. }
  26786. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  26787. rc==SQLITE_OK ? "ok" : "failed"));
  26788. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  26789. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  26790. rc = SQLITE_BUSY;
  26791. }
  26792. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  26793. return rc;
  26794. }
  26795. /*
  26796. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26797. ** must be either NO_LOCK or SHARED_LOCK.
  26798. **
  26799. ** If the locking level of the file descriptor is already at or below
  26800. ** the requested locking level, this routine is a no-op.
  26801. */
  26802. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  26803. unixFile *pFile = (unixFile*)id;
  26804. assert( pFile );
  26805. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  26806. pFile->eFileLock, osGetpid(0)));
  26807. assert( eFileLock<=SHARED_LOCK );
  26808. /* no-op if possible */
  26809. if( pFile->eFileLock==eFileLock ){
  26810. return SQLITE_OK;
  26811. }
  26812. /* shared can just be set because we always have an exclusive */
  26813. if (eFileLock==SHARED_LOCK) {
  26814. pFile->eFileLock = eFileLock;
  26815. return SQLITE_OK;
  26816. }
  26817. /* no, really, unlock. */
  26818. if( robust_flock(pFile->h, LOCK_UN) ){
  26819. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  26820. return SQLITE_OK;
  26821. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  26822. return SQLITE_IOERR_UNLOCK;
  26823. }else{
  26824. pFile->eFileLock = NO_LOCK;
  26825. return SQLITE_OK;
  26826. }
  26827. }
  26828. /*
  26829. ** Close a file.
  26830. */
  26831. static int flockClose(sqlite3_file *id) {
  26832. int rc = SQLITE_OK;
  26833. if( id ){
  26834. flockUnlock(id, NO_LOCK);
  26835. rc = closeUnixFile(id);
  26836. }
  26837. return rc;
  26838. }
  26839. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  26840. /******************* End of the flock lock implementation *********************
  26841. ******************************************************************************/
  26842. /******************************************************************************
  26843. ************************ Begin Named Semaphore Locking ************************
  26844. **
  26845. ** Named semaphore locking is only supported on VxWorks.
  26846. **
  26847. ** Semaphore locking is like dot-lock and flock in that it really only
  26848. ** supports EXCLUSIVE locking. Only a single process can read or write
  26849. ** the database file at a time. This reduces potential concurrency, but
  26850. ** makes the lock implementation much easier.
  26851. */
  26852. #if OS_VXWORKS
  26853. /*
  26854. ** This routine checks if there is a RESERVED lock held on the specified
  26855. ** file by this or any other process. If such a lock is held, set *pResOut
  26856. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  26857. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  26858. */
  26859. static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
  26860. int rc = SQLITE_OK;
  26861. int reserved = 0;
  26862. unixFile *pFile = (unixFile*)id;
  26863. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  26864. assert( pFile );
  26865. /* Check if a thread in this process holds such a lock */
  26866. if( pFile->eFileLock>SHARED_LOCK ){
  26867. reserved = 1;
  26868. }
  26869. /* Otherwise see if some other process holds it. */
  26870. if( !reserved ){
  26871. sem_t *pSem = pFile->pInode->pSem;
  26872. if( sem_trywait(pSem)==-1 ){
  26873. int tErrno = errno;
  26874. if( EAGAIN != tErrno ){
  26875. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  26876. storeLastErrno(pFile, tErrno);
  26877. } else {
  26878. /* someone else has the lock when we are in NO_LOCK */
  26879. reserved = (pFile->eFileLock < SHARED_LOCK);
  26880. }
  26881. }else{
  26882. /* we could have it if we want it */
  26883. sem_post(pSem);
  26884. }
  26885. }
  26886. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  26887. *pResOut = reserved;
  26888. return rc;
  26889. }
  26890. /*
  26891. ** Lock the file with the lock specified by parameter eFileLock - one
  26892. ** of the following:
  26893. **
  26894. ** (1) SHARED_LOCK
  26895. ** (2) RESERVED_LOCK
  26896. ** (3) PENDING_LOCK
  26897. ** (4) EXCLUSIVE_LOCK
  26898. **
  26899. ** Sometimes when requesting one lock state, additional lock states
  26900. ** are inserted in between. The locking might fail on one of the later
  26901. ** transitions leaving the lock state different from what it started but
  26902. ** still short of its goal. The following chart shows the allowed
  26903. ** transitions and the inserted intermediate states:
  26904. **
  26905. ** UNLOCKED -> SHARED
  26906. ** SHARED -> RESERVED
  26907. ** SHARED -> (PENDING) -> EXCLUSIVE
  26908. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26909. ** PENDING -> EXCLUSIVE
  26910. **
  26911. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  26912. ** lock states in the sqlite3_file structure, but all locks SHARED or
  26913. ** above are really EXCLUSIVE locks and exclude all other processes from
  26914. ** access the file.
  26915. **
  26916. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26917. ** routine to lower a locking level.
  26918. */
  26919. static int semXLock(sqlite3_file *id, int eFileLock) {
  26920. unixFile *pFile = (unixFile*)id;
  26921. sem_t *pSem = pFile->pInode->pSem;
  26922. int rc = SQLITE_OK;
  26923. /* if we already have a lock, it is exclusive.
  26924. ** Just adjust level and punt on outta here. */
  26925. if (pFile->eFileLock > NO_LOCK) {
  26926. pFile->eFileLock = eFileLock;
  26927. rc = SQLITE_OK;
  26928. goto sem_end_lock;
  26929. }
  26930. /* lock semaphore now but bail out when already locked. */
  26931. if( sem_trywait(pSem)==-1 ){
  26932. rc = SQLITE_BUSY;
  26933. goto sem_end_lock;
  26934. }
  26935. /* got it, set the type and return ok */
  26936. pFile->eFileLock = eFileLock;
  26937. sem_end_lock:
  26938. return rc;
  26939. }
  26940. /*
  26941. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26942. ** must be either NO_LOCK or SHARED_LOCK.
  26943. **
  26944. ** If the locking level of the file descriptor is already at or below
  26945. ** the requested locking level, this routine is a no-op.
  26946. */
  26947. static int semXUnlock(sqlite3_file *id, int eFileLock) {
  26948. unixFile *pFile = (unixFile*)id;
  26949. sem_t *pSem = pFile->pInode->pSem;
  26950. assert( pFile );
  26951. assert( pSem );
  26952. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  26953. pFile->eFileLock, osGetpid(0)));
  26954. assert( eFileLock<=SHARED_LOCK );
  26955. /* no-op if possible */
  26956. if( pFile->eFileLock==eFileLock ){
  26957. return SQLITE_OK;
  26958. }
  26959. /* shared can just be set because we always have an exclusive */
  26960. if (eFileLock==SHARED_LOCK) {
  26961. pFile->eFileLock = eFileLock;
  26962. return SQLITE_OK;
  26963. }
  26964. /* no, really unlock. */
  26965. if ( sem_post(pSem)==-1 ) {
  26966. int rc, tErrno = errno;
  26967. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  26968. if( IS_LOCK_ERROR(rc) ){
  26969. storeLastErrno(pFile, tErrno);
  26970. }
  26971. return rc;
  26972. }
  26973. pFile->eFileLock = NO_LOCK;
  26974. return SQLITE_OK;
  26975. }
  26976. /*
  26977. ** Close a file.
  26978. */
  26979. static int semXClose(sqlite3_file *id) {
  26980. if( id ){
  26981. unixFile *pFile = (unixFile*)id;
  26982. semXUnlock(id, NO_LOCK);
  26983. assert( pFile );
  26984. unixEnterMutex();
  26985. releaseInodeInfo(pFile);
  26986. unixLeaveMutex();
  26987. closeUnixFile(id);
  26988. }
  26989. return SQLITE_OK;
  26990. }
  26991. #endif /* OS_VXWORKS */
  26992. /*
  26993. ** Named semaphore locking is only available on VxWorks.
  26994. **
  26995. *************** End of the named semaphore lock implementation ****************
  26996. ******************************************************************************/
  26997. /******************************************************************************
  26998. *************************** Begin AFP Locking *********************************
  26999. **
  27000. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  27001. ** on Apple Macintosh computers - both OS9 and OSX.
  27002. **
  27003. ** Third-party implementations of AFP are available. But this code here
  27004. ** only works on OSX.
  27005. */
  27006. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27007. /*
  27008. ** The afpLockingContext structure contains all afp lock specific state
  27009. */
  27010. typedef struct afpLockingContext afpLockingContext;
  27011. struct afpLockingContext {
  27012. int reserved;
  27013. const char *dbPath; /* Name of the open file */
  27014. };
  27015. struct ByteRangeLockPB2
  27016. {
  27017. unsigned long long offset; /* offset to first byte to lock */
  27018. unsigned long long length; /* nbr of bytes to lock */
  27019. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  27020. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  27021. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  27022. int fd; /* file desc to assoc this lock with */
  27023. };
  27024. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  27025. /*
  27026. ** This is a utility for setting or clearing a bit-range lock on an
  27027. ** AFP filesystem.
  27028. **
  27029. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  27030. */
  27031. static int afpSetLock(
  27032. const char *path, /* Name of the file to be locked or unlocked */
  27033. unixFile *pFile, /* Open file descriptor on path */
  27034. unsigned long long offset, /* First byte to be locked */
  27035. unsigned long long length, /* Number of bytes to lock */
  27036. int setLockFlag /* True to set lock. False to clear lock */
  27037. ){
  27038. struct ByteRangeLockPB2 pb;
  27039. int err;
  27040. pb.unLockFlag = setLockFlag ? 0 : 1;
  27041. pb.startEndFlag = 0;
  27042. pb.offset = offset;
  27043. pb.length = length;
  27044. pb.fd = pFile->h;
  27045. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  27046. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  27047. offset, length));
  27048. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  27049. if ( err==-1 ) {
  27050. int rc;
  27051. int tErrno = errno;
  27052. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  27053. path, tErrno, strerror(tErrno)));
  27054. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  27055. rc = SQLITE_BUSY;
  27056. #else
  27057. rc = sqliteErrorFromPosixError(tErrno,
  27058. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  27059. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  27060. if( IS_LOCK_ERROR(rc) ){
  27061. storeLastErrno(pFile, tErrno);
  27062. }
  27063. return rc;
  27064. } else {
  27065. return SQLITE_OK;
  27066. }
  27067. }
  27068. /*
  27069. ** This routine checks if there is a RESERVED lock held on the specified
  27070. ** file by this or any other process. If such a lock is held, set *pResOut
  27071. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  27072. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  27073. */
  27074. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  27075. int rc = SQLITE_OK;
  27076. int reserved = 0;
  27077. unixFile *pFile = (unixFile*)id;
  27078. afpLockingContext *context;
  27079. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  27080. assert( pFile );
  27081. context = (afpLockingContext *) pFile->lockingContext;
  27082. if( context->reserved ){
  27083. *pResOut = 1;
  27084. return SQLITE_OK;
  27085. }
  27086. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  27087. /* Check if a thread in this process holds such a lock */
  27088. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  27089. reserved = 1;
  27090. }
  27091. /* Otherwise see if some other process holds it.
  27092. */
  27093. if( !reserved ){
  27094. /* lock the RESERVED byte */
  27095. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  27096. if( SQLITE_OK==lrc ){
  27097. /* if we succeeded in taking the reserved lock, unlock it to restore
  27098. ** the original state */
  27099. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  27100. } else {
  27101. /* if we failed to get the lock then someone else must have it */
  27102. reserved = 1;
  27103. }
  27104. if( IS_LOCK_ERROR(lrc) ){
  27105. rc=lrc;
  27106. }
  27107. }
  27108. unixLeaveMutex();
  27109. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  27110. *pResOut = reserved;
  27111. return rc;
  27112. }
  27113. /*
  27114. ** Lock the file with the lock specified by parameter eFileLock - one
  27115. ** of the following:
  27116. **
  27117. ** (1) SHARED_LOCK
  27118. ** (2) RESERVED_LOCK
  27119. ** (3) PENDING_LOCK
  27120. ** (4) EXCLUSIVE_LOCK
  27121. **
  27122. ** Sometimes when requesting one lock state, additional lock states
  27123. ** are inserted in between. The locking might fail on one of the later
  27124. ** transitions leaving the lock state different from what it started but
  27125. ** still short of its goal. The following chart shows the allowed
  27126. ** transitions and the inserted intermediate states:
  27127. **
  27128. ** UNLOCKED -> SHARED
  27129. ** SHARED -> RESERVED
  27130. ** SHARED -> (PENDING) -> EXCLUSIVE
  27131. ** RESERVED -> (PENDING) -> EXCLUSIVE
  27132. ** PENDING -> EXCLUSIVE
  27133. **
  27134. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  27135. ** routine to lower a locking level.
  27136. */
  27137. static int afpLock(sqlite3_file *id, int eFileLock){
  27138. int rc = SQLITE_OK;
  27139. unixFile *pFile = (unixFile*)id;
  27140. unixInodeInfo *pInode = pFile->pInode;
  27141. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  27142. assert( pFile );
  27143. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  27144. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  27145. azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
  27146. /* If there is already a lock of this type or more restrictive on the
  27147. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  27148. ** unixEnterMutex() hasn't been called yet.
  27149. */
  27150. if( pFile->eFileLock>=eFileLock ){
  27151. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  27152. azFileLock(eFileLock)));
  27153. return SQLITE_OK;
  27154. }
  27155. /* Make sure the locking sequence is correct
  27156. ** (1) We never move from unlocked to anything higher than shared lock.
  27157. ** (2) SQLite never explicitly requests a pendig lock.
  27158. ** (3) A shared lock is always held when a reserve lock is requested.
  27159. */
  27160. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  27161. assert( eFileLock!=PENDING_LOCK );
  27162. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  27163. /* This mutex is needed because pFile->pInode is shared across threads
  27164. */
  27165. unixEnterMutex();
  27166. pInode = pFile->pInode;
  27167. /* If some thread using this PID has a lock via a different unixFile*
  27168. ** handle that precludes the requested lock, return BUSY.
  27169. */
  27170. if( (pFile->eFileLock!=pInode->eFileLock &&
  27171. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  27172. ){
  27173. rc = SQLITE_BUSY;
  27174. goto afp_end_lock;
  27175. }
  27176. /* If a SHARED lock is requested, and some thread using this PID already
  27177. ** has a SHARED or RESERVED lock, then increment reference counts and
  27178. ** return SQLITE_OK.
  27179. */
  27180. if( eFileLock==SHARED_LOCK &&
  27181. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  27182. assert( eFileLock==SHARED_LOCK );
  27183. assert( pFile->eFileLock==0 );
  27184. assert( pInode->nShared>0 );
  27185. pFile->eFileLock = SHARED_LOCK;
  27186. pInode->nShared++;
  27187. pInode->nLock++;
  27188. goto afp_end_lock;
  27189. }
  27190. /* A PENDING lock is needed before acquiring a SHARED lock and before
  27191. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  27192. ** be released.
  27193. */
  27194. if( eFileLock==SHARED_LOCK
  27195. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  27196. ){
  27197. int failed;
  27198. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  27199. if (failed) {
  27200. rc = failed;
  27201. goto afp_end_lock;
  27202. }
  27203. }
  27204. /* If control gets to this point, then actually go ahead and make
  27205. ** operating system calls for the specified lock.
  27206. */
  27207. if( eFileLock==SHARED_LOCK ){
  27208. int lrc1, lrc2, lrc1Errno = 0;
  27209. long lk, mask;
  27210. assert( pInode->nShared==0 );
  27211. assert( pInode->eFileLock==0 );
  27212. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  27213. /* Now get the read-lock SHARED_LOCK */
  27214. /* note that the quality of the randomness doesn't matter that much */
  27215. lk = random();
  27216. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  27217. lrc1 = afpSetLock(context->dbPath, pFile,
  27218. SHARED_FIRST+pInode->sharedByte, 1, 1);
  27219. if( IS_LOCK_ERROR(lrc1) ){
  27220. lrc1Errno = pFile->lastErrno;
  27221. }
  27222. /* Drop the temporary PENDING lock */
  27223. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  27224. if( IS_LOCK_ERROR(lrc1) ) {
  27225. storeLastErrno(pFile, lrc1Errno);
  27226. rc = lrc1;
  27227. goto afp_end_lock;
  27228. } else if( IS_LOCK_ERROR(lrc2) ){
  27229. rc = lrc2;
  27230. goto afp_end_lock;
  27231. } else if( lrc1 != SQLITE_OK ) {
  27232. rc = lrc1;
  27233. } else {
  27234. pFile->eFileLock = SHARED_LOCK;
  27235. pInode->nLock++;
  27236. pInode->nShared = 1;
  27237. }
  27238. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  27239. /* We are trying for an exclusive lock but another thread in this
  27240. ** same process is still holding a shared lock. */
  27241. rc = SQLITE_BUSY;
  27242. }else{
  27243. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  27244. ** assumed that there is a SHARED or greater lock on the file
  27245. ** already.
  27246. */
  27247. int failed = 0;
  27248. assert( 0!=pFile->eFileLock );
  27249. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  27250. /* Acquire a RESERVED lock */
  27251. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  27252. if( !failed ){
  27253. context->reserved = 1;
  27254. }
  27255. }
  27256. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  27257. /* Acquire an EXCLUSIVE lock */
  27258. /* Remove the shared lock before trying the range. we'll need to
  27259. ** reestablish the shared lock if we can't get the afpUnlock
  27260. */
  27261. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  27262. pInode->sharedByte, 1, 0)) ){
  27263. int failed2 = SQLITE_OK;
  27264. /* now attemmpt to get the exclusive lock range */
  27265. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  27266. SHARED_SIZE, 1);
  27267. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  27268. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  27269. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  27270. ** a critical I/O error
  27271. */
  27272. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  27273. SQLITE_IOERR_LOCK;
  27274. goto afp_end_lock;
  27275. }
  27276. }else{
  27277. rc = failed;
  27278. }
  27279. }
  27280. if( failed ){
  27281. rc = failed;
  27282. }
  27283. }
  27284. if( rc==SQLITE_OK ){
  27285. pFile->eFileLock = eFileLock;
  27286. pInode->eFileLock = eFileLock;
  27287. }else if( eFileLock==EXCLUSIVE_LOCK ){
  27288. pFile->eFileLock = PENDING_LOCK;
  27289. pInode->eFileLock = PENDING_LOCK;
  27290. }
  27291. afp_end_lock:
  27292. unixLeaveMutex();
  27293. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  27294. rc==SQLITE_OK ? "ok" : "failed"));
  27295. return rc;
  27296. }
  27297. /*
  27298. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27299. ** must be either NO_LOCK or SHARED_LOCK.
  27300. **
  27301. ** If the locking level of the file descriptor is already at or below
  27302. ** the requested locking level, this routine is a no-op.
  27303. */
  27304. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  27305. int rc = SQLITE_OK;
  27306. unixFile *pFile = (unixFile*)id;
  27307. unixInodeInfo *pInode;
  27308. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  27309. int skipShared = 0;
  27310. #ifdef SQLITE_TEST
  27311. int h = pFile->h;
  27312. #endif
  27313. assert( pFile );
  27314. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  27315. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  27316. osGetpid(0)));
  27317. assert( eFileLock<=SHARED_LOCK );
  27318. if( pFile->eFileLock<=eFileLock ){
  27319. return SQLITE_OK;
  27320. }
  27321. unixEnterMutex();
  27322. pInode = pFile->pInode;
  27323. assert( pInode->nShared!=0 );
  27324. if( pFile->eFileLock>SHARED_LOCK ){
  27325. assert( pInode->eFileLock==pFile->eFileLock );
  27326. SimulateIOErrorBenign(1);
  27327. SimulateIOError( h=(-1) )
  27328. SimulateIOErrorBenign(0);
  27329. #ifdef SQLITE_DEBUG
  27330. /* When reducing a lock such that other processes can start
  27331. ** reading the database file again, make sure that the
  27332. ** transaction counter was updated if any part of the database
  27333. ** file changed. If the transaction counter is not updated,
  27334. ** other connections to the same file might not realize that
  27335. ** the file has changed and hence might not know to flush their
  27336. ** cache. The use of a stale cache can lead to database corruption.
  27337. */
  27338. assert( pFile->inNormalWrite==0
  27339. || pFile->dbUpdate==0
  27340. || pFile->transCntrChng==1 );
  27341. pFile->inNormalWrite = 0;
  27342. #endif
  27343. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  27344. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  27345. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  27346. /* only re-establish the shared lock if necessary */
  27347. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  27348. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  27349. } else {
  27350. skipShared = 1;
  27351. }
  27352. }
  27353. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  27354. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  27355. }
  27356. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  27357. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  27358. if( !rc ){
  27359. context->reserved = 0;
  27360. }
  27361. }
  27362. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  27363. pInode->eFileLock = SHARED_LOCK;
  27364. }
  27365. }
  27366. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  27367. /* Decrement the shared lock counter. Release the lock using an
  27368. ** OS call only when all threads in this same process have released
  27369. ** the lock.
  27370. */
  27371. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  27372. pInode->nShared--;
  27373. if( pInode->nShared==0 ){
  27374. SimulateIOErrorBenign(1);
  27375. SimulateIOError( h=(-1) )
  27376. SimulateIOErrorBenign(0);
  27377. if( !skipShared ){
  27378. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  27379. }
  27380. if( !rc ){
  27381. pInode->eFileLock = NO_LOCK;
  27382. pFile->eFileLock = NO_LOCK;
  27383. }
  27384. }
  27385. if( rc==SQLITE_OK ){
  27386. pInode->nLock--;
  27387. assert( pInode->nLock>=0 );
  27388. if( pInode->nLock==0 ){
  27389. closePendingFds(pFile);
  27390. }
  27391. }
  27392. }
  27393. unixLeaveMutex();
  27394. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  27395. return rc;
  27396. }
  27397. /*
  27398. ** Close a file & cleanup AFP specific locking context
  27399. */
  27400. static int afpClose(sqlite3_file *id) {
  27401. int rc = SQLITE_OK;
  27402. if( id ){
  27403. unixFile *pFile = (unixFile*)id;
  27404. afpUnlock(id, NO_LOCK);
  27405. unixEnterMutex();
  27406. if( pFile->pInode && pFile->pInode->nLock ){
  27407. /* If there are outstanding locks, do not actually close the file just
  27408. ** yet because that would clear those locks. Instead, add the file
  27409. ** descriptor to pInode->aPending. It will be automatically closed when
  27410. ** the last lock is cleared.
  27411. */
  27412. setPendingFd(pFile);
  27413. }
  27414. releaseInodeInfo(pFile);
  27415. sqlite3_free(pFile->lockingContext);
  27416. rc = closeUnixFile(id);
  27417. unixLeaveMutex();
  27418. }
  27419. return rc;
  27420. }
  27421. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  27422. /*
  27423. ** The code above is the AFP lock implementation. The code is specific
  27424. ** to MacOSX and does not work on other unix platforms. No alternative
  27425. ** is available. If you don't compile for a mac, then the "unix-afp"
  27426. ** VFS is not available.
  27427. **
  27428. ********************* End of the AFP lock implementation **********************
  27429. ******************************************************************************/
  27430. /******************************************************************************
  27431. *************************** Begin NFS Locking ********************************/
  27432. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27433. /*
  27434. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  27435. ** must be either NO_LOCK or SHARED_LOCK.
  27436. **
  27437. ** If the locking level of the file descriptor is already at or below
  27438. ** the requested locking level, this routine is a no-op.
  27439. */
  27440. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  27441. return posixUnlock(id, eFileLock, 1);
  27442. }
  27443. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  27444. /*
  27445. ** The code above is the NFS lock implementation. The code is specific
  27446. ** to MacOSX and does not work on other unix platforms. No alternative
  27447. ** is available.
  27448. **
  27449. ********************* End of the NFS lock implementation **********************
  27450. ******************************************************************************/
  27451. /******************************************************************************
  27452. **************** Non-locking sqlite3_file methods *****************************
  27453. **
  27454. ** The next division contains implementations for all methods of the
  27455. ** sqlite3_file object other than the locking methods. The locking
  27456. ** methods were defined in divisions above (one locking method per
  27457. ** division). Those methods that are common to all locking modes
  27458. ** are gather together into this division.
  27459. */
  27460. /*
  27461. ** Seek to the offset passed as the second argument, then read cnt
  27462. ** bytes into pBuf. Return the number of bytes actually read.
  27463. **
  27464. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  27465. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  27466. ** one system to another. Since SQLite does not define USE_PREAD
  27467. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  27468. ** See tickets #2741 and #2681.
  27469. **
  27470. ** To avoid stomping the errno value on a failed read the lastErrno value
  27471. ** is set before returning.
  27472. */
  27473. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  27474. int got;
  27475. int prior = 0;
  27476. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  27477. i64 newOffset;
  27478. #endif
  27479. TIMER_START;
  27480. assert( cnt==(cnt&0x1ffff) );
  27481. assert( id->h>2 );
  27482. cnt &= 0x1ffff;
  27483. do{
  27484. #if defined(USE_PREAD)
  27485. got = osPread(id->h, pBuf, cnt, offset);
  27486. SimulateIOError( got = -1 );
  27487. #elif defined(USE_PREAD64)
  27488. got = osPread64(id->h, pBuf, cnt, offset);
  27489. SimulateIOError( got = -1 );
  27490. #else
  27491. newOffset = lseek(id->h, offset, SEEK_SET);
  27492. SimulateIOError( newOffset-- );
  27493. if( newOffset!=offset ){
  27494. if( newOffset == -1 ){
  27495. storeLastErrno((unixFile*)id, errno);
  27496. }else{
  27497. storeLastErrno((unixFile*)id, 0);
  27498. }
  27499. return -1;
  27500. }
  27501. got = osRead(id->h, pBuf, cnt);
  27502. #endif
  27503. if( got==cnt ) break;
  27504. if( got<0 ){
  27505. if( errno==EINTR ){ got = 1; continue; }
  27506. prior = 0;
  27507. storeLastErrno((unixFile*)id, errno);
  27508. break;
  27509. }else if( got>0 ){
  27510. cnt -= got;
  27511. offset += got;
  27512. prior += got;
  27513. pBuf = (void*)(got + (char*)pBuf);
  27514. }
  27515. }while( got>0 );
  27516. TIMER_END;
  27517. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  27518. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  27519. return got+prior;
  27520. }
  27521. /*
  27522. ** Read data from a file into a buffer. Return SQLITE_OK if all
  27523. ** bytes were read successfully and SQLITE_IOERR if anything goes
  27524. ** wrong.
  27525. */
  27526. static int unixRead(
  27527. sqlite3_file *id,
  27528. void *pBuf,
  27529. int amt,
  27530. sqlite3_int64 offset
  27531. ){
  27532. unixFile *pFile = (unixFile *)id;
  27533. int got;
  27534. assert( id );
  27535. assert( offset>=0 );
  27536. assert( amt>0 );
  27537. /* If this is a database file (not a journal, master-journal or temp
  27538. ** file), the bytes in the locking range should never be read or written. */
  27539. #if 0
  27540. assert( pFile->pUnused==0
  27541. || offset>=PENDING_BYTE+512
  27542. || offset+amt<=PENDING_BYTE
  27543. );
  27544. #endif
  27545. #if SQLITE_MAX_MMAP_SIZE>0
  27546. /* Deal with as much of this read request as possible by transfering
  27547. ** data from the memory mapping using memcpy(). */
  27548. if( offset<pFile->mmapSize ){
  27549. if( offset+amt <= pFile->mmapSize ){
  27550. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  27551. return SQLITE_OK;
  27552. }else{
  27553. int nCopy = pFile->mmapSize - offset;
  27554. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  27555. pBuf = &((u8 *)pBuf)[nCopy];
  27556. amt -= nCopy;
  27557. offset += nCopy;
  27558. }
  27559. }
  27560. #endif
  27561. got = seekAndRead(pFile, offset, pBuf, amt);
  27562. if( got==amt ){
  27563. return SQLITE_OK;
  27564. }else if( got<0 ){
  27565. /* lastErrno set by seekAndRead */
  27566. return SQLITE_IOERR_READ;
  27567. }else{
  27568. storeLastErrno(pFile, 0); /* not a system error */
  27569. /* Unread parts of the buffer must be zero-filled */
  27570. memset(&((char*)pBuf)[got], 0, amt-got);
  27571. return SQLITE_IOERR_SHORT_READ;
  27572. }
  27573. }
  27574. /*
  27575. ** Attempt to seek the file-descriptor passed as the first argument to
  27576. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  27577. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  27578. ** return the actual number of bytes written (which may be less than
  27579. ** nBuf).
  27580. */
  27581. static int seekAndWriteFd(
  27582. int fd, /* File descriptor to write to */
  27583. i64 iOff, /* File offset to begin writing at */
  27584. const void *pBuf, /* Copy data from this buffer to the file */
  27585. int nBuf, /* Size of buffer pBuf in bytes */
  27586. int *piErrno /* OUT: Error number if error occurs */
  27587. ){
  27588. int rc = 0; /* Value returned by system call */
  27589. assert( nBuf==(nBuf&0x1ffff) );
  27590. assert( fd>2 );
  27591. nBuf &= 0x1ffff;
  27592. TIMER_START;
  27593. #if defined(USE_PREAD)
  27594. do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  27595. #elif defined(USE_PREAD64)
  27596. do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  27597. #else
  27598. do{
  27599. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  27600. SimulateIOError( iSeek-- );
  27601. if( iSeek!=iOff ){
  27602. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  27603. return -1;
  27604. }
  27605. rc = osWrite(fd, pBuf, nBuf);
  27606. }while( rc<0 && errno==EINTR );
  27607. #endif
  27608. TIMER_END;
  27609. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  27610. if( rc<0 && piErrno ) *piErrno = errno;
  27611. return rc;
  27612. }
  27613. /*
  27614. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  27615. ** Return the number of bytes actually read. Update the offset.
  27616. **
  27617. ** To avoid stomping the errno value on a failed write the lastErrno value
  27618. ** is set before returning.
  27619. */
  27620. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  27621. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  27622. }
  27623. /*
  27624. ** Write data from a buffer into a file. Return SQLITE_OK on success
  27625. ** or some other error code on failure.
  27626. */
  27627. static int unixWrite(
  27628. sqlite3_file *id,
  27629. const void *pBuf,
  27630. int amt,
  27631. sqlite3_int64 offset
  27632. ){
  27633. unixFile *pFile = (unixFile*)id;
  27634. int wrote = 0;
  27635. assert( id );
  27636. assert( amt>0 );
  27637. /* If this is a database file (not a journal, master-journal or temp
  27638. ** file), the bytes in the locking range should never be read or written. */
  27639. #if 0
  27640. assert( pFile->pUnused==0
  27641. || offset>=PENDING_BYTE+512
  27642. || offset+amt<=PENDING_BYTE
  27643. );
  27644. #endif
  27645. #ifdef SQLITE_DEBUG
  27646. /* If we are doing a normal write to a database file (as opposed to
  27647. ** doing a hot-journal rollback or a write to some file other than a
  27648. ** normal database file) then record the fact that the database
  27649. ** has changed. If the transaction counter is modified, record that
  27650. ** fact too.
  27651. */
  27652. if( pFile->inNormalWrite ){
  27653. pFile->dbUpdate = 1; /* The database has been modified */
  27654. if( offset<=24 && offset+amt>=27 ){
  27655. int rc;
  27656. char oldCntr[4];
  27657. SimulateIOErrorBenign(1);
  27658. rc = seekAndRead(pFile, 24, oldCntr, 4);
  27659. SimulateIOErrorBenign(0);
  27660. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  27661. pFile->transCntrChng = 1; /* The transaction counter has changed */
  27662. }
  27663. }
  27664. }
  27665. #endif
  27666. #if SQLITE_MAX_MMAP_SIZE>0
  27667. /* Deal with as much of this write request as possible by transfering
  27668. ** data from the memory mapping using memcpy(). */
  27669. if( offset<pFile->mmapSize ){
  27670. if( offset+amt <= pFile->mmapSize ){
  27671. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  27672. return SQLITE_OK;
  27673. }else{
  27674. int nCopy = pFile->mmapSize - offset;
  27675. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  27676. pBuf = &((u8 *)pBuf)[nCopy];
  27677. amt -= nCopy;
  27678. offset += nCopy;
  27679. }
  27680. }
  27681. #endif
  27682. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  27683. amt -= wrote;
  27684. offset += wrote;
  27685. pBuf = &((char*)pBuf)[wrote];
  27686. }
  27687. SimulateIOError(( wrote=(-1), amt=1 ));
  27688. SimulateDiskfullError(( wrote=0, amt=1 ));
  27689. if( amt>0 ){
  27690. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  27691. /* lastErrno set by seekAndWrite */
  27692. return SQLITE_IOERR_WRITE;
  27693. }else{
  27694. storeLastErrno(pFile, 0); /* not a system error */
  27695. return SQLITE_FULL;
  27696. }
  27697. }
  27698. return SQLITE_OK;
  27699. }
  27700. #ifdef SQLITE_TEST
  27701. /*
  27702. ** Count the number of fullsyncs and normal syncs. This is used to test
  27703. ** that syncs and fullsyncs are occurring at the right times.
  27704. */
  27705. SQLITE_API int sqlite3_sync_count = 0;
  27706. SQLITE_API int sqlite3_fullsync_count = 0;
  27707. #endif
  27708. /*
  27709. ** We do not trust systems to provide a working fdatasync(). Some do.
  27710. ** Others do no. To be safe, we will stick with the (slightly slower)
  27711. ** fsync(). If you know that your system does support fdatasync() correctly,
  27712. ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
  27713. */
  27714. #if !defined(fdatasync) && !HAVE_FDATASYNC
  27715. # define fdatasync fsync
  27716. #endif
  27717. /*
  27718. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  27719. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  27720. ** only available on Mac OS X. But that could change.
  27721. */
  27722. #ifdef F_FULLFSYNC
  27723. # define HAVE_FULLFSYNC 1
  27724. #else
  27725. # define HAVE_FULLFSYNC 0
  27726. #endif
  27727. /*
  27728. ** The fsync() system call does not work as advertised on many
  27729. ** unix systems. The following procedure is an attempt to make
  27730. ** it work better.
  27731. **
  27732. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  27733. ** for testing when we want to run through the test suite quickly.
  27734. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  27735. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  27736. ** or power failure will likely corrupt the database file.
  27737. **
  27738. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  27739. ** The idea behind dataOnly is that it should only write the file content
  27740. ** to disk, not the inode. We only set dataOnly if the file size is
  27741. ** unchanged since the file size is part of the inode. However,
  27742. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  27743. ** file size has changed. The only real difference between fdatasync()
  27744. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  27745. ** inode if the mtime or owner or other inode attributes have changed.
  27746. ** We only care about the file size, not the other file attributes, so
  27747. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  27748. ** So, we always use fdatasync() if it is available, regardless of
  27749. ** the value of the dataOnly flag.
  27750. */
  27751. static int full_fsync(int fd, int fullSync, int dataOnly){
  27752. int rc;
  27753. /* The following "ifdef/elif/else/" block has the same structure as
  27754. ** the one below. It is replicated here solely to avoid cluttering
  27755. ** up the real code with the UNUSED_PARAMETER() macros.
  27756. */
  27757. #ifdef SQLITE_NO_SYNC
  27758. UNUSED_PARAMETER(fd);
  27759. UNUSED_PARAMETER(fullSync);
  27760. UNUSED_PARAMETER(dataOnly);
  27761. #elif HAVE_FULLFSYNC
  27762. UNUSED_PARAMETER(dataOnly);
  27763. #else
  27764. UNUSED_PARAMETER(fullSync);
  27765. UNUSED_PARAMETER(dataOnly);
  27766. #endif
  27767. /* Record the number of times that we do a normal fsync() and
  27768. ** FULLSYNC. This is used during testing to verify that this procedure
  27769. ** gets called with the correct arguments.
  27770. */
  27771. #ifdef SQLITE_TEST
  27772. if( fullSync ) sqlite3_fullsync_count++;
  27773. sqlite3_sync_count++;
  27774. #endif
  27775. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  27776. ** no-op
  27777. */
  27778. #ifdef SQLITE_NO_SYNC
  27779. rc = SQLITE_OK;
  27780. #elif HAVE_FULLFSYNC
  27781. if( fullSync ){
  27782. rc = osFcntl(fd, F_FULLFSYNC, 0);
  27783. }else{
  27784. rc = 1;
  27785. }
  27786. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  27787. ** It shouldn't be possible for fullfsync to fail on the local
  27788. ** file system (on OSX), so failure indicates that FULLFSYNC
  27789. ** isn't supported for this file system. So, attempt an fsync
  27790. ** and (for now) ignore the overhead of a superfluous fcntl call.
  27791. ** It'd be better to detect fullfsync support once and avoid
  27792. ** the fcntl call every time sync is called.
  27793. */
  27794. if( rc ) rc = fsync(fd);
  27795. #elif defined(__APPLE__)
  27796. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  27797. ** so currently we default to the macro that redefines fdatasync to fsync
  27798. */
  27799. rc = fsync(fd);
  27800. #else
  27801. rc = fdatasync(fd);
  27802. #if OS_VXWORKS
  27803. if( rc==-1 && errno==ENOTSUP ){
  27804. rc = fsync(fd);
  27805. }
  27806. #endif /* OS_VXWORKS */
  27807. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  27808. if( OS_VXWORKS && rc!= -1 ){
  27809. rc = 0;
  27810. }
  27811. return rc;
  27812. }
  27813. /*
  27814. ** Open a file descriptor to the directory containing file zFilename.
  27815. ** If successful, *pFd is set to the opened file descriptor and
  27816. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  27817. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  27818. ** value.
  27819. **
  27820. ** The directory file descriptor is used for only one thing - to
  27821. ** fsync() a directory to make sure file creation and deletion events
  27822. ** are flushed to disk. Such fsyncs are not needed on newer
  27823. ** journaling filesystems, but are required on older filesystems.
  27824. **
  27825. ** This routine can be overridden using the xSetSysCall interface.
  27826. ** The ability to override this routine was added in support of the
  27827. ** chromium sandbox. Opening a directory is a security risk (we are
  27828. ** told) so making it overrideable allows the chromium sandbox to
  27829. ** replace this routine with a harmless no-op. To make this routine
  27830. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  27831. ** *pFd set to a negative number.
  27832. **
  27833. ** If SQLITE_OK is returned, the caller is responsible for closing
  27834. ** the file descriptor *pFd using close().
  27835. */
  27836. static int openDirectory(const char *zFilename, int *pFd){
  27837. int ii;
  27838. int fd = -1;
  27839. char zDirname[MAX_PATHNAME+1];
  27840. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  27841. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  27842. if( ii>0 ){
  27843. zDirname[ii] = '\0';
  27844. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  27845. if( fd>=0 ){
  27846. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  27847. }
  27848. }
  27849. *pFd = fd;
  27850. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  27851. }
  27852. /*
  27853. ** Make sure all writes to a particular file are committed to disk.
  27854. **
  27855. ** If dataOnly==0 then both the file itself and its metadata (file
  27856. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  27857. ** file data is synced.
  27858. **
  27859. ** Under Unix, also make sure that the directory entry for the file
  27860. ** has been created by fsync-ing the directory that contains the file.
  27861. ** If we do not do this and we encounter a power failure, the directory
  27862. ** entry for the journal might not exist after we reboot. The next
  27863. ** SQLite to access the file will not know that the journal exists (because
  27864. ** the directory entry for the journal was never created) and the transaction
  27865. ** will not roll back - possibly leading to database corruption.
  27866. */
  27867. static int unixSync(sqlite3_file *id, int flags){
  27868. int rc;
  27869. unixFile *pFile = (unixFile*)id;
  27870. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  27871. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  27872. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  27873. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  27874. || (flags&0x0F)==SQLITE_SYNC_FULL
  27875. );
  27876. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  27877. ** line is to test that doing so does not cause any problems.
  27878. */
  27879. SimulateDiskfullError( return SQLITE_FULL );
  27880. assert( pFile );
  27881. OSTRACE(("SYNC %-3d\n", pFile->h));
  27882. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  27883. SimulateIOError( rc=1 );
  27884. if( rc ){
  27885. storeLastErrno(pFile, errno);
  27886. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  27887. }
  27888. /* Also fsync the directory containing the file if the DIRSYNC flag
  27889. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  27890. ** are unable to fsync a directory, so ignore errors on the fsync.
  27891. */
  27892. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  27893. int dirfd;
  27894. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  27895. HAVE_FULLFSYNC, isFullsync));
  27896. rc = osOpenDirectory(pFile->zPath, &dirfd);
  27897. if( rc==SQLITE_OK && dirfd>=0 ){
  27898. full_fsync(dirfd, 0, 0);
  27899. robust_close(pFile, dirfd, __LINE__);
  27900. }else if( rc==SQLITE_CANTOPEN ){
  27901. rc = SQLITE_OK;
  27902. }
  27903. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  27904. }
  27905. return rc;
  27906. }
  27907. /*
  27908. ** Truncate an open file to a specified size
  27909. */
  27910. static int unixTruncate(sqlite3_file *id, i64 nByte){
  27911. unixFile *pFile = (unixFile *)id;
  27912. int rc;
  27913. assert( pFile );
  27914. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  27915. /* If the user has configured a chunk-size for this file, truncate the
  27916. ** file so that it consists of an integer number of chunks (i.e. the
  27917. ** actual file size after the operation may be larger than the requested
  27918. ** size).
  27919. */
  27920. if( pFile->szChunk>0 ){
  27921. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  27922. }
  27923. rc = robust_ftruncate(pFile->h, nByte);
  27924. if( rc ){
  27925. storeLastErrno(pFile, errno);
  27926. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  27927. }else{
  27928. #ifdef SQLITE_DEBUG
  27929. /* If we are doing a normal write to a database file (as opposed to
  27930. ** doing a hot-journal rollback or a write to some file other than a
  27931. ** normal database file) and we truncate the file to zero length,
  27932. ** that effectively updates the change counter. This might happen
  27933. ** when restoring a database using the backup API from a zero-length
  27934. ** source.
  27935. */
  27936. if( pFile->inNormalWrite && nByte==0 ){
  27937. pFile->transCntrChng = 1;
  27938. }
  27939. #endif
  27940. #if SQLITE_MAX_MMAP_SIZE>0
  27941. /* If the file was just truncated to a size smaller than the currently
  27942. ** mapped region, reduce the effective mapping size as well. SQLite will
  27943. ** use read() and write() to access data beyond this point from now on.
  27944. */
  27945. if( nByte<pFile->mmapSize ){
  27946. pFile->mmapSize = nByte;
  27947. }
  27948. #endif
  27949. return SQLITE_OK;
  27950. }
  27951. }
  27952. /*
  27953. ** Determine the current size of a file in bytes
  27954. */
  27955. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  27956. int rc;
  27957. struct stat buf;
  27958. assert( id );
  27959. rc = osFstat(((unixFile*)id)->h, &buf);
  27960. SimulateIOError( rc=1 );
  27961. if( rc!=0 ){
  27962. storeLastErrno((unixFile*)id, errno);
  27963. return SQLITE_IOERR_FSTAT;
  27964. }
  27965. *pSize = buf.st_size;
  27966. /* When opening a zero-size database, the findInodeInfo() procedure
  27967. ** writes a single byte into that file in order to work around a bug
  27968. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  27969. ** layers, we need to report this file size as zero even though it is
  27970. ** really 1. Ticket #3260.
  27971. */
  27972. if( *pSize==1 ) *pSize = 0;
  27973. return SQLITE_OK;
  27974. }
  27975. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27976. /*
  27977. ** Handler for proxy-locking file-control verbs. Defined below in the
  27978. ** proxying locking division.
  27979. */
  27980. static int proxyFileControl(sqlite3_file*,int,void*);
  27981. #endif
  27982. /*
  27983. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  27984. ** file-control operation. Enlarge the database to nBytes in size
  27985. ** (rounded up to the next chunk-size). If the database is already
  27986. ** nBytes or larger, this routine is a no-op.
  27987. */
  27988. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  27989. if( pFile->szChunk>0 ){
  27990. i64 nSize; /* Required file size */
  27991. struct stat buf; /* Used to hold return values of fstat() */
  27992. if( osFstat(pFile->h, &buf) ){
  27993. return SQLITE_IOERR_FSTAT;
  27994. }
  27995. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  27996. if( nSize>(i64)buf.st_size ){
  27997. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  27998. /* The code below is handling the return value of osFallocate()
  27999. ** correctly. posix_fallocate() is defined to "returns zero on success,
  28000. ** or an error number on failure". See the manpage for details. */
  28001. int err;
  28002. do{
  28003. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  28004. }while( err==EINTR );
  28005. if( err ) return SQLITE_IOERR_WRITE;
  28006. #else
  28007. /* If the OS does not have posix_fallocate(), fake it. Write a
  28008. ** single byte to the last byte in each block that falls entirely
  28009. ** within the extended region. Then, if required, a single byte
  28010. ** at offset (nSize-1), to set the size of the file correctly.
  28011. ** This is a similar technique to that used by glibc on systems
  28012. ** that do not have a real fallocate() call.
  28013. */
  28014. int nBlk = buf.st_blksize; /* File-system block size */
  28015. int nWrite = 0; /* Number of bytes written by seekAndWrite */
  28016. i64 iWrite; /* Next offset to write to */
  28017. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  28018. assert( iWrite>=buf.st_size );
  28019. assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
  28020. assert( ((iWrite+1)%nBlk)==0 );
  28021. for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
  28022. nWrite = seekAndWrite(pFile, iWrite, "", 1);
  28023. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  28024. }
  28025. if( nWrite==0 || (nSize%nBlk) ){
  28026. nWrite = seekAndWrite(pFile, nSize-1, "", 1);
  28027. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  28028. }
  28029. #endif
  28030. }
  28031. }
  28032. #if SQLITE_MAX_MMAP_SIZE>0
  28033. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  28034. int rc;
  28035. if( pFile->szChunk<=0 ){
  28036. if( robust_ftruncate(pFile->h, nByte) ){
  28037. storeLastErrno(pFile, errno);
  28038. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  28039. }
  28040. }
  28041. rc = unixMapfile(pFile, nByte);
  28042. return rc;
  28043. }
  28044. #endif
  28045. return SQLITE_OK;
  28046. }
  28047. /*
  28048. ** If *pArg is initially negative then this is a query. Set *pArg to
  28049. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  28050. **
  28051. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  28052. */
  28053. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  28054. if( *pArg<0 ){
  28055. *pArg = (pFile->ctrlFlags & mask)!=0;
  28056. }else if( (*pArg)==0 ){
  28057. pFile->ctrlFlags &= ~mask;
  28058. }else{
  28059. pFile->ctrlFlags |= mask;
  28060. }
  28061. }
  28062. /* Forward declaration */
  28063. static int unixGetTempname(int nBuf, char *zBuf);
  28064. /*
  28065. ** Information and control of an open file handle.
  28066. */
  28067. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  28068. unixFile *pFile = (unixFile*)id;
  28069. switch( op ){
  28070. case SQLITE_FCNTL_WAL_BLOCK: {
  28071. /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
  28072. return SQLITE_OK;
  28073. }
  28074. case SQLITE_FCNTL_LOCKSTATE: {
  28075. *(int*)pArg = pFile->eFileLock;
  28076. return SQLITE_OK;
  28077. }
  28078. case SQLITE_FCNTL_LAST_ERRNO: {
  28079. *(int*)pArg = pFile->lastErrno;
  28080. return SQLITE_OK;
  28081. }
  28082. case SQLITE_FCNTL_CHUNK_SIZE: {
  28083. pFile->szChunk = *(int *)pArg;
  28084. return SQLITE_OK;
  28085. }
  28086. case SQLITE_FCNTL_SIZE_HINT: {
  28087. int rc;
  28088. SimulateIOErrorBenign(1);
  28089. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  28090. SimulateIOErrorBenign(0);
  28091. return rc;
  28092. }
  28093. case SQLITE_FCNTL_PERSIST_WAL: {
  28094. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  28095. return SQLITE_OK;
  28096. }
  28097. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  28098. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  28099. return SQLITE_OK;
  28100. }
  28101. case SQLITE_FCNTL_VFSNAME: {
  28102. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  28103. return SQLITE_OK;
  28104. }
  28105. case SQLITE_FCNTL_TEMPFILENAME: {
  28106. char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
  28107. if( zTFile ){
  28108. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  28109. *(char**)pArg = zTFile;
  28110. }
  28111. return SQLITE_OK;
  28112. }
  28113. case SQLITE_FCNTL_HAS_MOVED: {
  28114. *(int*)pArg = fileHasMoved(pFile);
  28115. return SQLITE_OK;
  28116. }
  28117. #if SQLITE_MAX_MMAP_SIZE>0
  28118. case SQLITE_FCNTL_MMAP_SIZE: {
  28119. i64 newLimit = *(i64*)pArg;
  28120. int rc = SQLITE_OK;
  28121. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  28122. newLimit = sqlite3GlobalConfig.mxMmap;
  28123. }
  28124. *(i64*)pArg = pFile->mmapSizeMax;
  28125. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  28126. pFile->mmapSizeMax = newLimit;
  28127. if( pFile->mmapSize>0 ){
  28128. unixUnmapfile(pFile);
  28129. rc = unixMapfile(pFile, -1);
  28130. }
  28131. }
  28132. return rc;
  28133. }
  28134. #endif
  28135. #ifdef SQLITE_DEBUG
  28136. /* The pager calls this method to signal that it has done
  28137. ** a rollback and that the database is therefore unchanged and
  28138. ** it hence it is OK for the transaction change counter to be
  28139. ** unchanged.
  28140. */
  28141. case SQLITE_FCNTL_DB_UNCHANGED: {
  28142. ((unixFile*)id)->dbUpdate = 0;
  28143. return SQLITE_OK;
  28144. }
  28145. #endif
  28146. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28147. case SQLITE_FCNTL_SET_LOCKPROXYFILE:
  28148. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  28149. return proxyFileControl(id,op,pArg);
  28150. }
  28151. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  28152. }
  28153. return SQLITE_NOTFOUND;
  28154. }
  28155. /*
  28156. ** Return the sector size in bytes of the underlying block device for
  28157. ** the specified file. This is almost always 512 bytes, but may be
  28158. ** larger for some devices.
  28159. **
  28160. ** SQLite code assumes this function cannot fail. It also assumes that
  28161. ** if two files are created in the same file-system directory (i.e.
  28162. ** a database and its journal file) that the sector size will be the
  28163. ** same for both.
  28164. */
  28165. #ifndef __QNXNTO__
  28166. static int unixSectorSize(sqlite3_file *NotUsed){
  28167. UNUSED_PARAMETER(NotUsed);
  28168. return SQLITE_DEFAULT_SECTOR_SIZE;
  28169. }
  28170. #endif
  28171. /*
  28172. ** The following version of unixSectorSize() is optimized for QNX.
  28173. */
  28174. #ifdef __QNXNTO__
  28175. #include <sys/dcmd_blk.h>
  28176. #include <sys/statvfs.h>
  28177. static int unixSectorSize(sqlite3_file *id){
  28178. unixFile *pFile = (unixFile*)id;
  28179. if( pFile->sectorSize == 0 ){
  28180. struct statvfs fsInfo;
  28181. /* Set defaults for non-supported filesystems */
  28182. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  28183. pFile->deviceCharacteristics = 0;
  28184. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  28185. return pFile->sectorSize;
  28186. }
  28187. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  28188. pFile->sectorSize = fsInfo.f_bsize;
  28189. pFile->deviceCharacteristics =
  28190. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  28191. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28192. ** the write succeeds */
  28193. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28194. ** so it is ordered */
  28195. 0;
  28196. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  28197. pFile->sectorSize = fsInfo.f_bsize;
  28198. pFile->deviceCharacteristics =
  28199. /* etfs cluster size writes are atomic */
  28200. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  28201. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28202. ** the write succeeds */
  28203. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28204. ** so it is ordered */
  28205. 0;
  28206. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  28207. pFile->sectorSize = fsInfo.f_bsize;
  28208. pFile->deviceCharacteristics =
  28209. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  28210. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28211. ** the write succeeds */
  28212. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28213. ** so it is ordered */
  28214. 0;
  28215. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  28216. pFile->sectorSize = fsInfo.f_bsize;
  28217. pFile->deviceCharacteristics =
  28218. /* full bitset of atomics from max sector size and smaller */
  28219. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  28220. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28221. ** so it is ordered */
  28222. 0;
  28223. }else if( strstr(fsInfo.f_basetype, "dos") ){
  28224. pFile->sectorSize = fsInfo.f_bsize;
  28225. pFile->deviceCharacteristics =
  28226. /* full bitset of atomics from max sector size and smaller */
  28227. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  28228. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  28229. ** so it is ordered */
  28230. 0;
  28231. }else{
  28232. pFile->deviceCharacteristics =
  28233. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  28234. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  28235. ** the write succeeds */
  28236. 0;
  28237. }
  28238. }
  28239. /* Last chance verification. If the sector size isn't a multiple of 512
  28240. ** then it isn't valid.*/
  28241. if( pFile->sectorSize % 512 != 0 ){
  28242. pFile->deviceCharacteristics = 0;
  28243. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  28244. }
  28245. return pFile->sectorSize;
  28246. }
  28247. #endif /* __QNXNTO__ */
  28248. /*
  28249. ** Return the device characteristics for the file.
  28250. **
  28251. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  28252. ** However, that choice is controversial since technically the underlying
  28253. ** file system does not always provide powersafe overwrites. (In other
  28254. ** words, after a power-loss event, parts of the file that were never
  28255. ** written might end up being altered.) However, non-PSOW behavior is very,
  28256. ** very rare. And asserting PSOW makes a large reduction in the amount
  28257. ** of required I/O for journaling, since a lot of padding is eliminated.
  28258. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  28259. ** available to turn it off and URI query parameter available to turn it off.
  28260. */
  28261. static int unixDeviceCharacteristics(sqlite3_file *id){
  28262. unixFile *p = (unixFile*)id;
  28263. int rc = 0;
  28264. #ifdef __QNXNTO__
  28265. if( p->sectorSize==0 ) unixSectorSize(id);
  28266. rc = p->deviceCharacteristics;
  28267. #endif
  28268. if( p->ctrlFlags & UNIXFILE_PSOW ){
  28269. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  28270. }
  28271. return rc;
  28272. }
  28273. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  28274. /*
  28275. ** Return the system page size.
  28276. **
  28277. ** This function should not be called directly by other code in this file.
  28278. ** Instead, it should be called via macro osGetpagesize().
  28279. */
  28280. static int unixGetpagesize(void){
  28281. #if OS_VXWORKS
  28282. return 1024;
  28283. #elif defined(_BSD_SOURCE)
  28284. return getpagesize();
  28285. #else
  28286. return (int)sysconf(_SC_PAGESIZE);
  28287. #endif
  28288. }
  28289. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  28290. #ifndef SQLITE_OMIT_WAL
  28291. /*
  28292. ** Object used to represent an shared memory buffer.
  28293. **
  28294. ** When multiple threads all reference the same wal-index, each thread
  28295. ** has its own unixShm object, but they all point to a single instance
  28296. ** of this unixShmNode object. In other words, each wal-index is opened
  28297. ** only once per process.
  28298. **
  28299. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  28300. ** We could coalesce this object into unixInodeInfo, but that would mean
  28301. ** every open file that does not use shared memory (in other words, most
  28302. ** open files) would have to carry around this extra information. So
  28303. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  28304. ** and the unixShmNode object is created only when needed.
  28305. **
  28306. ** unixMutexHeld() must be true when creating or destroying
  28307. ** this object or while reading or writing the following fields:
  28308. **
  28309. ** nRef
  28310. **
  28311. ** The following fields are read-only after the object is created:
  28312. **
  28313. ** fid
  28314. ** zFilename
  28315. **
  28316. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  28317. ** unixMutexHeld() is true when reading or writing any other field
  28318. ** in this structure.
  28319. */
  28320. struct unixShmNode {
  28321. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  28322. sqlite3_mutex *mutex; /* Mutex to access this object */
  28323. char *zFilename; /* Name of the mmapped file */
  28324. int h; /* Open file descriptor */
  28325. int szRegion; /* Size of shared-memory regions */
  28326. u16 nRegion; /* Size of array apRegion */
  28327. u8 isReadonly; /* True if read-only */
  28328. char **apRegion; /* Array of mapped shared-memory regions */
  28329. int nRef; /* Number of unixShm objects pointing to this */
  28330. unixShm *pFirst; /* All unixShm objects pointing to this */
  28331. #ifdef SQLITE_DEBUG
  28332. u8 exclMask; /* Mask of exclusive locks held */
  28333. u8 sharedMask; /* Mask of shared locks held */
  28334. u8 nextShmId; /* Next available unixShm.id value */
  28335. #endif
  28336. };
  28337. /*
  28338. ** Structure used internally by this VFS to record the state of an
  28339. ** open shared memory connection.
  28340. **
  28341. ** The following fields are initialized when this object is created and
  28342. ** are read-only thereafter:
  28343. **
  28344. ** unixShm.pFile
  28345. ** unixShm.id
  28346. **
  28347. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  28348. ** while accessing any read/write fields.
  28349. */
  28350. struct unixShm {
  28351. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  28352. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  28353. u8 hasMutex; /* True if holding the unixShmNode mutex */
  28354. u8 id; /* Id of this connection within its unixShmNode */
  28355. u16 sharedMask; /* Mask of shared locks held */
  28356. u16 exclMask; /* Mask of exclusive locks held */
  28357. };
  28358. /*
  28359. ** Constants used for locking
  28360. */
  28361. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  28362. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  28363. /*
  28364. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  28365. **
  28366. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  28367. ** otherwise.
  28368. */
  28369. static int unixShmSystemLock(
  28370. unixFile *pFile, /* Open connection to the WAL file */
  28371. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  28372. int ofst, /* First byte of the locking range */
  28373. int n /* Number of bytes to lock */
  28374. ){
  28375. unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
  28376. struct flock f; /* The posix advisory locking structure */
  28377. int rc = SQLITE_OK; /* Result code form fcntl() */
  28378. /* Access to the unixShmNode object is serialized by the caller */
  28379. pShmNode = pFile->pInode->pShmNode;
  28380. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  28381. /* Shared locks never span more than one byte */
  28382. assert( n==1 || lockType!=F_RDLCK );
  28383. /* Locks are within range */
  28384. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  28385. if( pShmNode->h>=0 ){
  28386. int lkType;
  28387. /* Initialize the locking parameters */
  28388. memset(&f, 0, sizeof(f));
  28389. f.l_type = lockType;
  28390. f.l_whence = SEEK_SET;
  28391. f.l_start = ofst;
  28392. f.l_len = n;
  28393. lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
  28394. rc = osFcntl(pShmNode->h, lkType, &f);
  28395. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  28396. pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
  28397. }
  28398. /* Update the global lock state and do debug tracing */
  28399. #ifdef SQLITE_DEBUG
  28400. { u16 mask;
  28401. OSTRACE(("SHM-LOCK "));
  28402. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  28403. if( rc==SQLITE_OK ){
  28404. if( lockType==F_UNLCK ){
  28405. OSTRACE(("unlock %d ok", ofst));
  28406. pShmNode->exclMask &= ~mask;
  28407. pShmNode->sharedMask &= ~mask;
  28408. }else if( lockType==F_RDLCK ){
  28409. OSTRACE(("read-lock %d ok", ofst));
  28410. pShmNode->exclMask &= ~mask;
  28411. pShmNode->sharedMask |= mask;
  28412. }else{
  28413. assert( lockType==F_WRLCK );
  28414. OSTRACE(("write-lock %d ok", ofst));
  28415. pShmNode->exclMask |= mask;
  28416. pShmNode->sharedMask &= ~mask;
  28417. }
  28418. }else{
  28419. if( lockType==F_UNLCK ){
  28420. OSTRACE(("unlock %d failed", ofst));
  28421. }else if( lockType==F_RDLCK ){
  28422. OSTRACE(("read-lock failed"));
  28423. }else{
  28424. assert( lockType==F_WRLCK );
  28425. OSTRACE(("write-lock %d failed", ofst));
  28426. }
  28427. }
  28428. OSTRACE((" - afterwards %03x,%03x\n",
  28429. pShmNode->sharedMask, pShmNode->exclMask));
  28430. }
  28431. #endif
  28432. return rc;
  28433. }
  28434. /*
  28435. ** Return the minimum number of 32KB shm regions that should be mapped at
  28436. ** a time, assuming that each mapping must be an integer multiple of the
  28437. ** current system page-size.
  28438. **
  28439. ** Usually, this is 1. The exception seems to be systems that are configured
  28440. ** to use 64KB pages - in this case each mapping must cover at least two
  28441. ** shm regions.
  28442. */
  28443. static int unixShmRegionPerMap(void){
  28444. int shmsz = 32*1024; /* SHM region size */
  28445. int pgsz = osGetpagesize(); /* System page size */
  28446. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  28447. if( pgsz<shmsz ) return 1;
  28448. return pgsz/shmsz;
  28449. }
  28450. /*
  28451. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  28452. **
  28453. ** This is not a VFS shared-memory method; it is a utility function called
  28454. ** by VFS shared-memory methods.
  28455. */
  28456. static void unixShmPurge(unixFile *pFd){
  28457. unixShmNode *p = pFd->pInode->pShmNode;
  28458. assert( unixMutexHeld() );
  28459. if( p && p->nRef==0 ){
  28460. int nShmPerMap = unixShmRegionPerMap();
  28461. int i;
  28462. assert( p->pInode==pFd->pInode );
  28463. sqlite3_mutex_free(p->mutex);
  28464. for(i=0; i<p->nRegion; i+=nShmPerMap){
  28465. if( p->h>=0 ){
  28466. osMunmap(p->apRegion[i], p->szRegion);
  28467. }else{
  28468. sqlite3_free(p->apRegion[i]);
  28469. }
  28470. }
  28471. sqlite3_free(p->apRegion);
  28472. if( p->h>=0 ){
  28473. robust_close(pFd, p->h, __LINE__);
  28474. p->h = -1;
  28475. }
  28476. p->pInode->pShmNode = 0;
  28477. sqlite3_free(p);
  28478. }
  28479. }
  28480. /*
  28481. ** Open a shared-memory area associated with open database file pDbFd.
  28482. ** This particular implementation uses mmapped files.
  28483. **
  28484. ** The file used to implement shared-memory is in the same directory
  28485. ** as the open database file and has the same name as the open database
  28486. ** file with the "-shm" suffix added. For example, if the database file
  28487. ** is "/home/user1/config.db" then the file that is created and mmapped
  28488. ** for shared memory will be called "/home/user1/config.db-shm".
  28489. **
  28490. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  28491. ** some other tmpfs mount. But if a file in a different directory
  28492. ** from the database file is used, then differing access permissions
  28493. ** or a chroot() might cause two different processes on the same
  28494. ** database to end up using different files for shared memory -
  28495. ** meaning that their memory would not really be shared - resulting
  28496. ** in database corruption. Nevertheless, this tmpfs file usage
  28497. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  28498. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  28499. ** option results in an incompatible build of SQLite; builds of SQLite
  28500. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  28501. ** same database file at the same time, database corruption will likely
  28502. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  28503. ** "unsupported" and may go away in a future SQLite release.
  28504. **
  28505. ** When opening a new shared-memory file, if no other instances of that
  28506. ** file are currently open, in this process or in other processes, then
  28507. ** the file must be truncated to zero length or have its header cleared.
  28508. **
  28509. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  28510. ** that means that an exclusive lock is held on the database file and
  28511. ** that no other processes are able to read or write the database. In
  28512. ** that case, we do not really need shared memory. No shared memory
  28513. ** file is created. The shared memory will be simulated with heap memory.
  28514. */
  28515. static int unixOpenSharedMemory(unixFile *pDbFd){
  28516. struct unixShm *p = 0; /* The connection to be opened */
  28517. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  28518. int rc; /* Result code */
  28519. unixInodeInfo *pInode; /* The inode of fd */
  28520. char *zShmFilename; /* Name of the file used for SHM */
  28521. int nShmFilename; /* Size of the SHM filename in bytes */
  28522. /* Allocate space for the new unixShm object. */
  28523. p = sqlite3_malloc64( sizeof(*p) );
  28524. if( p==0 ) return SQLITE_NOMEM;
  28525. memset(p, 0, sizeof(*p));
  28526. assert( pDbFd->pShm==0 );
  28527. /* Check to see if a unixShmNode object already exists. Reuse an existing
  28528. ** one if present. Create a new one if necessary.
  28529. */
  28530. unixEnterMutex();
  28531. pInode = pDbFd->pInode;
  28532. pShmNode = pInode->pShmNode;
  28533. if( pShmNode==0 ){
  28534. struct stat sStat; /* fstat() info for database file */
  28535. #ifndef SQLITE_SHM_DIRECTORY
  28536. const char *zBasePath = pDbFd->zPath;
  28537. #endif
  28538. /* Call fstat() to figure out the permissions on the database file. If
  28539. ** a new *-shm file is created, an attempt will be made to create it
  28540. ** with the same permissions.
  28541. */
  28542. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  28543. rc = SQLITE_IOERR_FSTAT;
  28544. goto shm_open_err;
  28545. }
  28546. #ifdef SQLITE_SHM_DIRECTORY
  28547. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  28548. #else
  28549. nShmFilename = 6 + (int)strlen(zBasePath);
  28550. #endif
  28551. pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
  28552. if( pShmNode==0 ){
  28553. rc = SQLITE_NOMEM;
  28554. goto shm_open_err;
  28555. }
  28556. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  28557. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  28558. #ifdef SQLITE_SHM_DIRECTORY
  28559. sqlite3_snprintf(nShmFilename, zShmFilename,
  28560. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  28561. (u32)sStat.st_ino, (u32)sStat.st_dev);
  28562. #else
  28563. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
  28564. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  28565. #endif
  28566. pShmNode->h = -1;
  28567. pDbFd->pInode->pShmNode = pShmNode;
  28568. pShmNode->pInode = pDbFd->pInode;
  28569. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  28570. if( pShmNode->mutex==0 ){
  28571. rc = SQLITE_NOMEM;
  28572. goto shm_open_err;
  28573. }
  28574. if( pInode->bProcessLock==0 ){
  28575. int openFlags = O_RDWR | O_CREAT;
  28576. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  28577. openFlags = O_RDONLY;
  28578. pShmNode->isReadonly = 1;
  28579. }
  28580. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  28581. if( pShmNode->h<0 ){
  28582. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  28583. goto shm_open_err;
  28584. }
  28585. /* If this process is running as root, make sure that the SHM file
  28586. ** is owned by the same user that owns the original database. Otherwise,
  28587. ** the original owner will not be able to connect.
  28588. */
  28589. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  28590. /* Check to see if another process is holding the dead-man switch.
  28591. ** If not, truncate the file to zero length.
  28592. */
  28593. rc = SQLITE_OK;
  28594. if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  28595. if( robust_ftruncate(pShmNode->h, 0) ){
  28596. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  28597. }
  28598. }
  28599. if( rc==SQLITE_OK ){
  28600. rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
  28601. }
  28602. if( rc ) goto shm_open_err;
  28603. }
  28604. }
  28605. /* Make the new connection a child of the unixShmNode */
  28606. p->pShmNode = pShmNode;
  28607. #ifdef SQLITE_DEBUG
  28608. p->id = pShmNode->nextShmId++;
  28609. #endif
  28610. pShmNode->nRef++;
  28611. pDbFd->pShm = p;
  28612. unixLeaveMutex();
  28613. /* The reference count on pShmNode has already been incremented under
  28614. ** the cover of the unixEnterMutex() mutex and the pointer from the
  28615. ** new (struct unixShm) object to the pShmNode has been set. All that is
  28616. ** left to do is to link the new object into the linked list starting
  28617. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  28618. ** mutex.
  28619. */
  28620. sqlite3_mutex_enter(pShmNode->mutex);
  28621. p->pNext = pShmNode->pFirst;
  28622. pShmNode->pFirst = p;
  28623. sqlite3_mutex_leave(pShmNode->mutex);
  28624. return SQLITE_OK;
  28625. /* Jump here on any error */
  28626. shm_open_err:
  28627. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  28628. sqlite3_free(p);
  28629. unixLeaveMutex();
  28630. return rc;
  28631. }
  28632. /*
  28633. ** This function is called to obtain a pointer to region iRegion of the
  28634. ** shared-memory associated with the database file fd. Shared-memory regions
  28635. ** are numbered starting from zero. Each shared-memory region is szRegion
  28636. ** bytes in size.
  28637. **
  28638. ** If an error occurs, an error code is returned and *pp is set to NULL.
  28639. **
  28640. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  28641. ** region has not been allocated (by any client, including one running in a
  28642. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  28643. ** bExtend is non-zero and the requested shared-memory region has not yet
  28644. ** been allocated, it is allocated by this function.
  28645. **
  28646. ** If the shared-memory region has already been allocated or is allocated by
  28647. ** this call as described above, then it is mapped into this processes
  28648. ** address space (if it is not already), *pp is set to point to the mapped
  28649. ** memory and SQLITE_OK returned.
  28650. */
  28651. static int unixShmMap(
  28652. sqlite3_file *fd, /* Handle open on database file */
  28653. int iRegion, /* Region to retrieve */
  28654. int szRegion, /* Size of regions */
  28655. int bExtend, /* True to extend file if necessary */
  28656. void volatile **pp /* OUT: Mapped memory */
  28657. ){
  28658. unixFile *pDbFd = (unixFile*)fd;
  28659. unixShm *p;
  28660. unixShmNode *pShmNode;
  28661. int rc = SQLITE_OK;
  28662. int nShmPerMap = unixShmRegionPerMap();
  28663. int nReqRegion;
  28664. /* If the shared-memory file has not yet been opened, open it now. */
  28665. if( pDbFd->pShm==0 ){
  28666. rc = unixOpenSharedMemory(pDbFd);
  28667. if( rc!=SQLITE_OK ) return rc;
  28668. }
  28669. p = pDbFd->pShm;
  28670. pShmNode = p->pShmNode;
  28671. sqlite3_mutex_enter(pShmNode->mutex);
  28672. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  28673. assert( pShmNode->pInode==pDbFd->pInode );
  28674. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  28675. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  28676. /* Minimum number of regions required to be mapped. */
  28677. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  28678. if( pShmNode->nRegion<nReqRegion ){
  28679. char **apNew; /* New apRegion[] array */
  28680. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  28681. struct stat sStat; /* Used by fstat() */
  28682. pShmNode->szRegion = szRegion;
  28683. if( pShmNode->h>=0 ){
  28684. /* The requested region is not mapped into this processes address space.
  28685. ** Check to see if it has been allocated (i.e. if the wal-index file is
  28686. ** large enough to contain the requested region).
  28687. */
  28688. if( osFstat(pShmNode->h, &sStat) ){
  28689. rc = SQLITE_IOERR_SHMSIZE;
  28690. goto shmpage_out;
  28691. }
  28692. if( sStat.st_size<nByte ){
  28693. /* The requested memory region does not exist. If bExtend is set to
  28694. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  28695. */
  28696. if( !bExtend ){
  28697. goto shmpage_out;
  28698. }
  28699. /* Alternatively, if bExtend is true, extend the file. Do this by
  28700. ** writing a single byte to the end of each (OS) page being
  28701. ** allocated or extended. Technically, we need only write to the
  28702. ** last page in order to extend the file. But writing to all new
  28703. ** pages forces the OS to allocate them immediately, which reduces
  28704. ** the chances of SIGBUS while accessing the mapped region later on.
  28705. */
  28706. else{
  28707. static const int pgsz = 4096;
  28708. int iPg;
  28709. /* Write to the last byte of each newly allocated or extended page */
  28710. assert( (nByte % pgsz)==0 );
  28711. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  28712. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  28713. const char *zFile = pShmNode->zFilename;
  28714. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  28715. goto shmpage_out;
  28716. }
  28717. }
  28718. }
  28719. }
  28720. }
  28721. /* Map the requested memory region into this processes address space. */
  28722. apNew = (char **)sqlite3_realloc(
  28723. pShmNode->apRegion, nReqRegion*sizeof(char *)
  28724. );
  28725. if( !apNew ){
  28726. rc = SQLITE_IOERR_NOMEM;
  28727. goto shmpage_out;
  28728. }
  28729. pShmNode->apRegion = apNew;
  28730. while( pShmNode->nRegion<nReqRegion ){
  28731. int nMap = szRegion*nShmPerMap;
  28732. int i;
  28733. void *pMem;
  28734. if( pShmNode->h>=0 ){
  28735. pMem = osMmap(0, nMap,
  28736. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  28737. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  28738. );
  28739. if( pMem==MAP_FAILED ){
  28740. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  28741. goto shmpage_out;
  28742. }
  28743. }else{
  28744. pMem = sqlite3_malloc64(szRegion);
  28745. if( pMem==0 ){
  28746. rc = SQLITE_NOMEM;
  28747. goto shmpage_out;
  28748. }
  28749. memset(pMem, 0, szRegion);
  28750. }
  28751. for(i=0; i<nShmPerMap; i++){
  28752. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  28753. }
  28754. pShmNode->nRegion += nShmPerMap;
  28755. }
  28756. }
  28757. shmpage_out:
  28758. if( pShmNode->nRegion>iRegion ){
  28759. *pp = pShmNode->apRegion[iRegion];
  28760. }else{
  28761. *pp = 0;
  28762. }
  28763. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  28764. sqlite3_mutex_leave(pShmNode->mutex);
  28765. return rc;
  28766. }
  28767. /*
  28768. ** Change the lock state for a shared-memory segment.
  28769. **
  28770. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  28771. ** different here than in posix. In xShmLock(), one can go from unlocked
  28772. ** to shared and back or from unlocked to exclusive and back. But one may
  28773. ** not go from shared to exclusive or from exclusive to shared.
  28774. */
  28775. static int unixShmLock(
  28776. sqlite3_file *fd, /* Database file holding the shared memory */
  28777. int ofst, /* First lock to acquire or release */
  28778. int n, /* Number of locks to acquire or release */
  28779. int flags /* What to do with the lock */
  28780. ){
  28781. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  28782. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  28783. unixShm *pX; /* For looping over all siblings */
  28784. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  28785. int rc = SQLITE_OK; /* Result code */
  28786. u16 mask; /* Mask of locks to take or release */
  28787. assert( pShmNode==pDbFd->pInode->pShmNode );
  28788. assert( pShmNode->pInode==pDbFd->pInode );
  28789. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  28790. assert( n>=1 );
  28791. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  28792. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  28793. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  28794. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  28795. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  28796. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  28797. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  28798. mask = (1<<(ofst+n)) - (1<<ofst);
  28799. assert( n>1 || mask==(1<<ofst) );
  28800. sqlite3_mutex_enter(pShmNode->mutex);
  28801. if( flags & SQLITE_SHM_UNLOCK ){
  28802. u16 allMask = 0; /* Mask of locks held by siblings */
  28803. /* See if any siblings hold this same lock */
  28804. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  28805. if( pX==p ) continue;
  28806. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  28807. allMask |= pX->sharedMask;
  28808. }
  28809. /* Unlock the system-level locks */
  28810. if( (mask & allMask)==0 ){
  28811. rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  28812. }else{
  28813. rc = SQLITE_OK;
  28814. }
  28815. /* Undo the local locks */
  28816. if( rc==SQLITE_OK ){
  28817. p->exclMask &= ~mask;
  28818. p->sharedMask &= ~mask;
  28819. }
  28820. }else if( flags & SQLITE_SHM_SHARED ){
  28821. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  28822. /* Find out which shared locks are already held by sibling connections.
  28823. ** If any sibling already holds an exclusive lock, go ahead and return
  28824. ** SQLITE_BUSY.
  28825. */
  28826. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  28827. if( (pX->exclMask & mask)!=0 ){
  28828. rc = SQLITE_BUSY;
  28829. break;
  28830. }
  28831. allShared |= pX->sharedMask;
  28832. }
  28833. /* Get shared locks at the system level, if necessary */
  28834. if( rc==SQLITE_OK ){
  28835. if( (allShared & mask)==0 ){
  28836. rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  28837. }else{
  28838. rc = SQLITE_OK;
  28839. }
  28840. }
  28841. /* Get the local shared locks */
  28842. if( rc==SQLITE_OK ){
  28843. p->sharedMask |= mask;
  28844. }
  28845. }else{
  28846. /* Make sure no sibling connections hold locks that will block this
  28847. ** lock. If any do, return SQLITE_BUSY right away.
  28848. */
  28849. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  28850. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  28851. rc = SQLITE_BUSY;
  28852. break;
  28853. }
  28854. }
  28855. /* Get the exclusive locks at the system level. Then if successful
  28856. ** also mark the local connection as being locked.
  28857. */
  28858. if( rc==SQLITE_OK ){
  28859. rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  28860. if( rc==SQLITE_OK ){
  28861. assert( (p->sharedMask & mask)==0 );
  28862. p->exclMask |= mask;
  28863. }
  28864. }
  28865. }
  28866. sqlite3_mutex_leave(pShmNode->mutex);
  28867. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  28868. p->id, osGetpid(0), p->sharedMask, p->exclMask));
  28869. return rc;
  28870. }
  28871. /*
  28872. ** Implement a memory barrier or memory fence on shared memory.
  28873. **
  28874. ** All loads and stores begun before the barrier must complete before
  28875. ** any load or store begun after the barrier.
  28876. */
  28877. static void unixShmBarrier(
  28878. sqlite3_file *fd /* Database file holding the shared memory */
  28879. ){
  28880. UNUSED_PARAMETER(fd);
  28881. unixEnterMutex();
  28882. unixLeaveMutex();
  28883. }
  28884. /*
  28885. ** Close a connection to shared-memory. Delete the underlying
  28886. ** storage if deleteFlag is true.
  28887. **
  28888. ** If there is no shared memory associated with the connection then this
  28889. ** routine is a harmless no-op.
  28890. */
  28891. static int unixShmUnmap(
  28892. sqlite3_file *fd, /* The underlying database file */
  28893. int deleteFlag /* Delete shared-memory if true */
  28894. ){
  28895. unixShm *p; /* The connection to be closed */
  28896. unixShmNode *pShmNode; /* The underlying shared-memory file */
  28897. unixShm **pp; /* For looping over sibling connections */
  28898. unixFile *pDbFd; /* The underlying database file */
  28899. pDbFd = (unixFile*)fd;
  28900. p = pDbFd->pShm;
  28901. if( p==0 ) return SQLITE_OK;
  28902. pShmNode = p->pShmNode;
  28903. assert( pShmNode==pDbFd->pInode->pShmNode );
  28904. assert( pShmNode->pInode==pDbFd->pInode );
  28905. /* Remove connection p from the set of connections associated
  28906. ** with pShmNode */
  28907. sqlite3_mutex_enter(pShmNode->mutex);
  28908. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  28909. *pp = p->pNext;
  28910. /* Free the connection p */
  28911. sqlite3_free(p);
  28912. pDbFd->pShm = 0;
  28913. sqlite3_mutex_leave(pShmNode->mutex);
  28914. /* If pShmNode->nRef has reached 0, then close the underlying
  28915. ** shared-memory file, too */
  28916. unixEnterMutex();
  28917. assert( pShmNode->nRef>0 );
  28918. pShmNode->nRef--;
  28919. if( pShmNode->nRef==0 ){
  28920. if( deleteFlag && pShmNode->h>=0 ){
  28921. osUnlink(pShmNode->zFilename);
  28922. }
  28923. unixShmPurge(pDbFd);
  28924. }
  28925. unixLeaveMutex();
  28926. return SQLITE_OK;
  28927. }
  28928. #else
  28929. # define unixShmMap 0
  28930. # define unixShmLock 0
  28931. # define unixShmBarrier 0
  28932. # define unixShmUnmap 0
  28933. #endif /* #ifndef SQLITE_OMIT_WAL */
  28934. #if SQLITE_MAX_MMAP_SIZE>0
  28935. /*
  28936. ** If it is currently memory mapped, unmap file pFd.
  28937. */
  28938. static void unixUnmapfile(unixFile *pFd){
  28939. assert( pFd->nFetchOut==0 );
  28940. if( pFd->pMapRegion ){
  28941. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  28942. pFd->pMapRegion = 0;
  28943. pFd->mmapSize = 0;
  28944. pFd->mmapSizeActual = 0;
  28945. }
  28946. }
  28947. /*
  28948. ** Attempt to set the size of the memory mapping maintained by file
  28949. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  28950. **
  28951. ** If successful, this function sets the following variables:
  28952. **
  28953. ** unixFile.pMapRegion
  28954. ** unixFile.mmapSize
  28955. ** unixFile.mmapSizeActual
  28956. **
  28957. ** If unsuccessful, an error message is logged via sqlite3_log() and
  28958. ** the three variables above are zeroed. In this case SQLite should
  28959. ** continue accessing the database using the xRead() and xWrite()
  28960. ** methods.
  28961. */
  28962. static void unixRemapfile(
  28963. unixFile *pFd, /* File descriptor object */
  28964. i64 nNew /* Required mapping size */
  28965. ){
  28966. const char *zErr = "mmap";
  28967. int h = pFd->h; /* File descriptor open on db file */
  28968. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  28969. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  28970. u8 *pNew = 0; /* Location of new mapping */
  28971. int flags = PROT_READ; /* Flags to pass to mmap() */
  28972. assert( pFd->nFetchOut==0 );
  28973. assert( nNew>pFd->mmapSize );
  28974. assert( nNew<=pFd->mmapSizeMax );
  28975. assert( nNew>0 );
  28976. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  28977. assert( MAP_FAILED!=0 );
  28978. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  28979. if( pOrig ){
  28980. #if HAVE_MREMAP
  28981. i64 nReuse = pFd->mmapSize;
  28982. #else
  28983. const int szSyspage = osGetpagesize();
  28984. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  28985. #endif
  28986. u8 *pReq = &pOrig[nReuse];
  28987. /* Unmap any pages of the existing mapping that cannot be reused. */
  28988. if( nReuse!=nOrig ){
  28989. osMunmap(pReq, nOrig-nReuse);
  28990. }
  28991. #if HAVE_MREMAP
  28992. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  28993. zErr = "mremap";
  28994. #else
  28995. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  28996. if( pNew!=MAP_FAILED ){
  28997. if( pNew!=pReq ){
  28998. osMunmap(pNew, nNew - nReuse);
  28999. pNew = 0;
  29000. }else{
  29001. pNew = pOrig;
  29002. }
  29003. }
  29004. #endif
  29005. /* The attempt to extend the existing mapping failed. Free it. */
  29006. if( pNew==MAP_FAILED || pNew==0 ){
  29007. osMunmap(pOrig, nReuse);
  29008. }
  29009. }
  29010. /* If pNew is still NULL, try to create an entirely new mapping. */
  29011. if( pNew==0 ){
  29012. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  29013. }
  29014. if( pNew==MAP_FAILED ){
  29015. pNew = 0;
  29016. nNew = 0;
  29017. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  29018. /* If the mmap() above failed, assume that all subsequent mmap() calls
  29019. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  29020. ** in this case. */
  29021. pFd->mmapSizeMax = 0;
  29022. }
  29023. pFd->pMapRegion = (void *)pNew;
  29024. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  29025. }
  29026. /*
  29027. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  29028. ** is already mapped, the existing mapping is replaced by the new). Or, if
  29029. ** there already exists a mapping for this file, and there are still
  29030. ** outstanding xFetch() references to it, this function is a no-op.
  29031. **
  29032. ** If parameter nByte is non-negative, then it is the requested size of
  29033. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  29034. ** requested size is the size of the file on disk. The actual size of the
  29035. ** created mapping is either the requested size or the value configured
  29036. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  29037. **
  29038. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  29039. ** recreated as a result of outstanding references) or an SQLite error
  29040. ** code otherwise.
  29041. */
  29042. static int unixMapfile(unixFile *pFd, i64 nByte){
  29043. i64 nMap = nByte;
  29044. int rc;
  29045. assert( nMap>=0 || pFd->nFetchOut==0 );
  29046. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  29047. if( nMap<0 ){
  29048. struct stat statbuf; /* Low-level file information */
  29049. rc = osFstat(pFd->h, &statbuf);
  29050. if( rc!=SQLITE_OK ){
  29051. return SQLITE_IOERR_FSTAT;
  29052. }
  29053. nMap = statbuf.st_size;
  29054. }
  29055. if( nMap>pFd->mmapSizeMax ){
  29056. nMap = pFd->mmapSizeMax;
  29057. }
  29058. if( nMap!=pFd->mmapSize ){
  29059. if( nMap>0 ){
  29060. unixRemapfile(pFd, nMap);
  29061. }else{
  29062. unixUnmapfile(pFd);
  29063. }
  29064. }
  29065. return SQLITE_OK;
  29066. }
  29067. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  29068. /*
  29069. ** If possible, return a pointer to a mapping of file fd starting at offset
  29070. ** iOff. The mapping must be valid for at least nAmt bytes.
  29071. **
  29072. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  29073. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  29074. ** Finally, if an error does occur, return an SQLite error code. The final
  29075. ** value of *pp is undefined in this case.
  29076. **
  29077. ** If this function does return a pointer, the caller must eventually
  29078. ** release the reference by calling unixUnfetch().
  29079. */
  29080. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  29081. #if SQLITE_MAX_MMAP_SIZE>0
  29082. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  29083. #endif
  29084. *pp = 0;
  29085. #if SQLITE_MAX_MMAP_SIZE>0
  29086. if( pFd->mmapSizeMax>0 ){
  29087. if( pFd->pMapRegion==0 ){
  29088. int rc = unixMapfile(pFd, -1);
  29089. if( rc!=SQLITE_OK ) return rc;
  29090. }
  29091. if( pFd->mmapSize >= iOff+nAmt ){
  29092. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  29093. pFd->nFetchOut++;
  29094. }
  29095. }
  29096. #endif
  29097. return SQLITE_OK;
  29098. }
  29099. /*
  29100. ** If the third argument is non-NULL, then this function releases a
  29101. ** reference obtained by an earlier call to unixFetch(). The second
  29102. ** argument passed to this function must be the same as the corresponding
  29103. ** argument that was passed to the unixFetch() invocation.
  29104. **
  29105. ** Or, if the third argument is NULL, then this function is being called
  29106. ** to inform the VFS layer that, according to POSIX, any existing mapping
  29107. ** may now be invalid and should be unmapped.
  29108. */
  29109. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  29110. #if SQLITE_MAX_MMAP_SIZE>0
  29111. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  29112. UNUSED_PARAMETER(iOff);
  29113. /* If p==0 (unmap the entire file) then there must be no outstanding
  29114. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  29115. ** then there must be at least one outstanding. */
  29116. assert( (p==0)==(pFd->nFetchOut==0) );
  29117. /* If p!=0, it must match the iOff value. */
  29118. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  29119. if( p ){
  29120. pFd->nFetchOut--;
  29121. }else{
  29122. unixUnmapfile(pFd);
  29123. }
  29124. assert( pFd->nFetchOut>=0 );
  29125. #else
  29126. UNUSED_PARAMETER(fd);
  29127. UNUSED_PARAMETER(p);
  29128. UNUSED_PARAMETER(iOff);
  29129. #endif
  29130. return SQLITE_OK;
  29131. }
  29132. /*
  29133. ** Here ends the implementation of all sqlite3_file methods.
  29134. **
  29135. ********************** End sqlite3_file Methods *******************************
  29136. ******************************************************************************/
  29137. /*
  29138. ** This division contains definitions of sqlite3_io_methods objects that
  29139. ** implement various file locking strategies. It also contains definitions
  29140. ** of "finder" functions. A finder-function is used to locate the appropriate
  29141. ** sqlite3_io_methods object for a particular database file. The pAppData
  29142. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  29143. ** the correct finder-function for that VFS.
  29144. **
  29145. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  29146. ** object. The only interesting finder-function is autolockIoFinder, which
  29147. ** looks at the filesystem type and tries to guess the best locking
  29148. ** strategy from that.
  29149. **
  29150. ** For finder-function F, two objects are created:
  29151. **
  29152. ** (1) The real finder-function named "FImpt()".
  29153. **
  29154. ** (2) A constant pointer to this function named just "F".
  29155. **
  29156. **
  29157. ** A pointer to the F pointer is used as the pAppData value for VFS
  29158. ** objects. We have to do this instead of letting pAppData point
  29159. ** directly at the finder-function since C90 rules prevent a void*
  29160. ** from be cast into a function pointer.
  29161. **
  29162. **
  29163. ** Each instance of this macro generates two objects:
  29164. **
  29165. ** * A constant sqlite3_io_methods object call METHOD that has locking
  29166. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  29167. **
  29168. ** * An I/O method finder function called FINDER that returns a pointer
  29169. ** to the METHOD object in the previous bullet.
  29170. */
  29171. #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
  29172. static const sqlite3_io_methods METHOD = { \
  29173. VERSION, /* iVersion */ \
  29174. CLOSE, /* xClose */ \
  29175. unixRead, /* xRead */ \
  29176. unixWrite, /* xWrite */ \
  29177. unixTruncate, /* xTruncate */ \
  29178. unixSync, /* xSync */ \
  29179. unixFileSize, /* xFileSize */ \
  29180. LOCK, /* xLock */ \
  29181. UNLOCK, /* xUnlock */ \
  29182. CKLOCK, /* xCheckReservedLock */ \
  29183. unixFileControl, /* xFileControl */ \
  29184. unixSectorSize, /* xSectorSize */ \
  29185. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  29186. SHMMAP, /* xShmMap */ \
  29187. unixShmLock, /* xShmLock */ \
  29188. unixShmBarrier, /* xShmBarrier */ \
  29189. unixShmUnmap, /* xShmUnmap */ \
  29190. unixFetch, /* xFetch */ \
  29191. unixUnfetch, /* xUnfetch */ \
  29192. }; \
  29193. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  29194. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  29195. return &METHOD; \
  29196. } \
  29197. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  29198. = FINDER##Impl;
  29199. /*
  29200. ** Here are all of the sqlite3_io_methods objects for each of the
  29201. ** locking strategies. Functions that return pointers to these methods
  29202. ** are also created.
  29203. */
  29204. IOMETHODS(
  29205. posixIoFinder, /* Finder function name */
  29206. posixIoMethods, /* sqlite3_io_methods object name */
  29207. 3, /* shared memory and mmap are enabled */
  29208. unixClose, /* xClose method */
  29209. unixLock, /* xLock method */
  29210. unixUnlock, /* xUnlock method */
  29211. unixCheckReservedLock, /* xCheckReservedLock method */
  29212. unixShmMap /* xShmMap method */
  29213. )
  29214. IOMETHODS(
  29215. nolockIoFinder, /* Finder function name */
  29216. nolockIoMethods, /* sqlite3_io_methods object name */
  29217. 3, /* shared memory is disabled */
  29218. nolockClose, /* xClose method */
  29219. nolockLock, /* xLock method */
  29220. nolockUnlock, /* xUnlock method */
  29221. nolockCheckReservedLock, /* xCheckReservedLock method */
  29222. 0 /* xShmMap method */
  29223. )
  29224. IOMETHODS(
  29225. dotlockIoFinder, /* Finder function name */
  29226. dotlockIoMethods, /* sqlite3_io_methods object name */
  29227. 1, /* shared memory is disabled */
  29228. dotlockClose, /* xClose method */
  29229. dotlockLock, /* xLock method */
  29230. dotlockUnlock, /* xUnlock method */
  29231. dotlockCheckReservedLock, /* xCheckReservedLock method */
  29232. 0 /* xShmMap method */
  29233. )
  29234. #if SQLITE_ENABLE_LOCKING_STYLE
  29235. IOMETHODS(
  29236. flockIoFinder, /* Finder function name */
  29237. flockIoMethods, /* sqlite3_io_methods object name */
  29238. 1, /* shared memory is disabled */
  29239. flockClose, /* xClose method */
  29240. flockLock, /* xLock method */
  29241. flockUnlock, /* xUnlock method */
  29242. flockCheckReservedLock, /* xCheckReservedLock method */
  29243. 0 /* xShmMap method */
  29244. )
  29245. #endif
  29246. #if OS_VXWORKS
  29247. IOMETHODS(
  29248. semIoFinder, /* Finder function name */
  29249. semIoMethods, /* sqlite3_io_methods object name */
  29250. 1, /* shared memory is disabled */
  29251. semXClose, /* xClose method */
  29252. semXLock, /* xLock method */
  29253. semXUnlock, /* xUnlock method */
  29254. semXCheckReservedLock, /* xCheckReservedLock method */
  29255. 0 /* xShmMap method */
  29256. )
  29257. #endif
  29258. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29259. IOMETHODS(
  29260. afpIoFinder, /* Finder function name */
  29261. afpIoMethods, /* sqlite3_io_methods object name */
  29262. 1, /* shared memory is disabled */
  29263. afpClose, /* xClose method */
  29264. afpLock, /* xLock method */
  29265. afpUnlock, /* xUnlock method */
  29266. afpCheckReservedLock, /* xCheckReservedLock method */
  29267. 0 /* xShmMap method */
  29268. )
  29269. #endif
  29270. /*
  29271. ** The proxy locking method is a "super-method" in the sense that it
  29272. ** opens secondary file descriptors for the conch and lock files and
  29273. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  29274. ** secondary files. For this reason, the division that implements
  29275. ** proxy locking is located much further down in the file. But we need
  29276. ** to go ahead and define the sqlite3_io_methods and finder function
  29277. ** for proxy locking here. So we forward declare the I/O methods.
  29278. */
  29279. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29280. static int proxyClose(sqlite3_file*);
  29281. static int proxyLock(sqlite3_file*, int);
  29282. static int proxyUnlock(sqlite3_file*, int);
  29283. static int proxyCheckReservedLock(sqlite3_file*, int*);
  29284. IOMETHODS(
  29285. proxyIoFinder, /* Finder function name */
  29286. proxyIoMethods, /* sqlite3_io_methods object name */
  29287. 1, /* shared memory is disabled */
  29288. proxyClose, /* xClose method */
  29289. proxyLock, /* xLock method */
  29290. proxyUnlock, /* xUnlock method */
  29291. proxyCheckReservedLock, /* xCheckReservedLock method */
  29292. 0 /* xShmMap method */
  29293. )
  29294. #endif
  29295. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  29296. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29297. IOMETHODS(
  29298. nfsIoFinder, /* Finder function name */
  29299. nfsIoMethods, /* sqlite3_io_methods object name */
  29300. 1, /* shared memory is disabled */
  29301. unixClose, /* xClose method */
  29302. unixLock, /* xLock method */
  29303. nfsUnlock, /* xUnlock method */
  29304. unixCheckReservedLock, /* xCheckReservedLock method */
  29305. 0 /* xShmMap method */
  29306. )
  29307. #endif
  29308. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29309. /*
  29310. ** This "finder" function attempts to determine the best locking strategy
  29311. ** for the database file "filePath". It then returns the sqlite3_io_methods
  29312. ** object that implements that strategy.
  29313. **
  29314. ** This is for MacOSX only.
  29315. */
  29316. static const sqlite3_io_methods *autolockIoFinderImpl(
  29317. const char *filePath, /* name of the database file */
  29318. unixFile *pNew /* open file object for the database file */
  29319. ){
  29320. static const struct Mapping {
  29321. const char *zFilesystem; /* Filesystem type name */
  29322. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  29323. } aMap[] = {
  29324. { "hfs", &posixIoMethods },
  29325. { "ufs", &posixIoMethods },
  29326. { "afpfs", &afpIoMethods },
  29327. { "smbfs", &afpIoMethods },
  29328. { "webdav", &nolockIoMethods },
  29329. { 0, 0 }
  29330. };
  29331. int i;
  29332. struct statfs fsInfo;
  29333. struct flock lockInfo;
  29334. if( !filePath ){
  29335. /* If filePath==NULL that means we are dealing with a transient file
  29336. ** that does not need to be locked. */
  29337. return &nolockIoMethods;
  29338. }
  29339. if( statfs(filePath, &fsInfo) != -1 ){
  29340. if( fsInfo.f_flags & MNT_RDONLY ){
  29341. return &nolockIoMethods;
  29342. }
  29343. for(i=0; aMap[i].zFilesystem; i++){
  29344. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  29345. return aMap[i].pMethods;
  29346. }
  29347. }
  29348. }
  29349. /* Default case. Handles, amongst others, "nfs".
  29350. ** Test byte-range lock using fcntl(). If the call succeeds,
  29351. ** assume that the file-system supports POSIX style locks.
  29352. */
  29353. lockInfo.l_len = 1;
  29354. lockInfo.l_start = 0;
  29355. lockInfo.l_whence = SEEK_SET;
  29356. lockInfo.l_type = F_RDLCK;
  29357. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  29358. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  29359. return &nfsIoMethods;
  29360. } else {
  29361. return &posixIoMethods;
  29362. }
  29363. }else{
  29364. return &dotlockIoMethods;
  29365. }
  29366. }
  29367. static const sqlite3_io_methods
  29368. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  29369. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  29370. #if OS_VXWORKS
  29371. /*
  29372. ** This "finder" function for VxWorks checks to see if posix advisory
  29373. ** locking works. If it does, then that is what is used. If it does not
  29374. ** work, then fallback to named semaphore locking.
  29375. */
  29376. static const sqlite3_io_methods *vxworksIoFinderImpl(
  29377. const char *filePath, /* name of the database file */
  29378. unixFile *pNew /* the open file object */
  29379. ){
  29380. struct flock lockInfo;
  29381. if( !filePath ){
  29382. /* If filePath==NULL that means we are dealing with a transient file
  29383. ** that does not need to be locked. */
  29384. return &nolockIoMethods;
  29385. }
  29386. /* Test if fcntl() is supported and use POSIX style locks.
  29387. ** Otherwise fall back to the named semaphore method.
  29388. */
  29389. lockInfo.l_len = 1;
  29390. lockInfo.l_start = 0;
  29391. lockInfo.l_whence = SEEK_SET;
  29392. lockInfo.l_type = F_RDLCK;
  29393. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  29394. return &posixIoMethods;
  29395. }else{
  29396. return &semIoMethods;
  29397. }
  29398. }
  29399. static const sqlite3_io_methods
  29400. *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
  29401. #endif /* OS_VXWORKS */
  29402. /*
  29403. ** An abstract type for a pointer to an IO method finder function:
  29404. */
  29405. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  29406. /****************************************************************************
  29407. **************************** sqlite3_vfs methods ****************************
  29408. **
  29409. ** This division contains the implementation of methods on the
  29410. ** sqlite3_vfs object.
  29411. */
  29412. /*
  29413. ** Initialize the contents of the unixFile structure pointed to by pId.
  29414. */
  29415. static int fillInUnixFile(
  29416. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  29417. int h, /* Open file descriptor of file being opened */
  29418. sqlite3_file *pId, /* Write to the unixFile structure here */
  29419. const char *zFilename, /* Name of the file being opened */
  29420. int ctrlFlags /* Zero or more UNIXFILE_* values */
  29421. ){
  29422. const sqlite3_io_methods *pLockingStyle;
  29423. unixFile *pNew = (unixFile *)pId;
  29424. int rc = SQLITE_OK;
  29425. assert( pNew->pInode==NULL );
  29426. /* Usually the path zFilename should not be a relative pathname. The
  29427. ** exception is when opening the proxy "conch" file in builds that
  29428. ** include the special Apple locking styles.
  29429. */
  29430. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29431. assert( zFilename==0 || zFilename[0]=='/'
  29432. || pVfs->pAppData==(void*)&autolockIoFinder );
  29433. #else
  29434. assert( zFilename==0 || zFilename[0]=='/' );
  29435. #endif
  29436. /* No locking occurs in temporary files */
  29437. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  29438. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  29439. pNew->h = h;
  29440. pNew->pVfs = pVfs;
  29441. pNew->zPath = zFilename;
  29442. pNew->ctrlFlags = (u8)ctrlFlags;
  29443. #if SQLITE_MAX_MMAP_SIZE>0
  29444. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  29445. #endif
  29446. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  29447. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  29448. pNew->ctrlFlags |= UNIXFILE_PSOW;
  29449. }
  29450. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  29451. pNew->ctrlFlags |= UNIXFILE_EXCL;
  29452. }
  29453. #if OS_VXWORKS
  29454. pNew->pId = vxworksFindFileId(zFilename);
  29455. if( pNew->pId==0 ){
  29456. ctrlFlags |= UNIXFILE_NOLOCK;
  29457. rc = SQLITE_NOMEM;
  29458. }
  29459. #endif
  29460. if( ctrlFlags & UNIXFILE_NOLOCK ){
  29461. pLockingStyle = &nolockIoMethods;
  29462. }else{
  29463. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  29464. #if SQLITE_ENABLE_LOCKING_STYLE
  29465. /* Cache zFilename in the locking context (AFP and dotlock override) for
  29466. ** proxyLock activation is possible (remote proxy is based on db name)
  29467. ** zFilename remains valid until file is closed, to support */
  29468. pNew->lockingContext = (void*)zFilename;
  29469. #endif
  29470. }
  29471. if( pLockingStyle == &posixIoMethods
  29472. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29473. || pLockingStyle == &nfsIoMethods
  29474. #endif
  29475. ){
  29476. unixEnterMutex();
  29477. rc = findInodeInfo(pNew, &pNew->pInode);
  29478. if( rc!=SQLITE_OK ){
  29479. /* If an error occurred in findInodeInfo(), close the file descriptor
  29480. ** immediately, before releasing the mutex. findInodeInfo() may fail
  29481. ** in two scenarios:
  29482. **
  29483. ** (a) A call to fstat() failed.
  29484. ** (b) A malloc failed.
  29485. **
  29486. ** Scenario (b) may only occur if the process is holding no other
  29487. ** file descriptors open on the same file. If there were other file
  29488. ** descriptors on this file, then no malloc would be required by
  29489. ** findInodeInfo(). If this is the case, it is quite safe to close
  29490. ** handle h - as it is guaranteed that no posix locks will be released
  29491. ** by doing so.
  29492. **
  29493. ** If scenario (a) caused the error then things are not so safe. The
  29494. ** implicit assumption here is that if fstat() fails, things are in
  29495. ** such bad shape that dropping a lock or two doesn't matter much.
  29496. */
  29497. robust_close(pNew, h, __LINE__);
  29498. h = -1;
  29499. }
  29500. unixLeaveMutex();
  29501. }
  29502. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29503. else if( pLockingStyle == &afpIoMethods ){
  29504. /* AFP locking uses the file path so it needs to be included in
  29505. ** the afpLockingContext.
  29506. */
  29507. afpLockingContext *pCtx;
  29508. pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  29509. if( pCtx==0 ){
  29510. rc = SQLITE_NOMEM;
  29511. }else{
  29512. /* NB: zFilename exists and remains valid until the file is closed
  29513. ** according to requirement F11141. So we do not need to make a
  29514. ** copy of the filename. */
  29515. pCtx->dbPath = zFilename;
  29516. pCtx->reserved = 0;
  29517. srandomdev();
  29518. unixEnterMutex();
  29519. rc = findInodeInfo(pNew, &pNew->pInode);
  29520. if( rc!=SQLITE_OK ){
  29521. sqlite3_free(pNew->lockingContext);
  29522. robust_close(pNew, h, __LINE__);
  29523. h = -1;
  29524. }
  29525. unixLeaveMutex();
  29526. }
  29527. }
  29528. #endif
  29529. else if( pLockingStyle == &dotlockIoMethods ){
  29530. /* Dotfile locking uses the file path so it needs to be included in
  29531. ** the dotlockLockingContext
  29532. */
  29533. char *zLockFile;
  29534. int nFilename;
  29535. assert( zFilename!=0 );
  29536. nFilename = (int)strlen(zFilename) + 6;
  29537. zLockFile = (char *)sqlite3_malloc64(nFilename);
  29538. if( zLockFile==0 ){
  29539. rc = SQLITE_NOMEM;
  29540. }else{
  29541. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  29542. }
  29543. pNew->lockingContext = zLockFile;
  29544. }
  29545. #if OS_VXWORKS
  29546. else if( pLockingStyle == &semIoMethods ){
  29547. /* Named semaphore locking uses the file path so it needs to be
  29548. ** included in the semLockingContext
  29549. */
  29550. unixEnterMutex();
  29551. rc = findInodeInfo(pNew, &pNew->pInode);
  29552. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  29553. char *zSemName = pNew->pInode->aSemName;
  29554. int n;
  29555. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  29556. pNew->pId->zCanonicalName);
  29557. for( n=1; zSemName[n]; n++ )
  29558. if( zSemName[n]=='/' ) zSemName[n] = '_';
  29559. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  29560. if( pNew->pInode->pSem == SEM_FAILED ){
  29561. rc = SQLITE_NOMEM;
  29562. pNew->pInode->aSemName[0] = '\0';
  29563. }
  29564. }
  29565. unixLeaveMutex();
  29566. }
  29567. #endif
  29568. storeLastErrno(pNew, 0);
  29569. #if OS_VXWORKS
  29570. if( rc!=SQLITE_OK ){
  29571. if( h>=0 ) robust_close(pNew, h, __LINE__);
  29572. h = -1;
  29573. osUnlink(zFilename);
  29574. pNew->ctrlFlags |= UNIXFILE_DELETE;
  29575. }
  29576. #endif
  29577. if( rc!=SQLITE_OK ){
  29578. if( h>=0 ) robust_close(pNew, h, __LINE__);
  29579. }else{
  29580. pNew->pMethod = pLockingStyle;
  29581. OpenCounter(+1);
  29582. verifyDbFile(pNew);
  29583. }
  29584. return rc;
  29585. }
  29586. /*
  29587. ** Return the name of a directory in which to put temporary files.
  29588. ** If no suitable temporary file directory can be found, return NULL.
  29589. */
  29590. static const char *unixTempFileDir(void){
  29591. static const char *azDirs[] = {
  29592. 0,
  29593. 0,
  29594. 0,
  29595. "/var/tmp",
  29596. "/usr/tmp",
  29597. "/tmp",
  29598. 0 /* List terminator */
  29599. };
  29600. unsigned int i;
  29601. struct stat buf;
  29602. const char *zDir = 0;
  29603. azDirs[0] = sqlite3_temp_directory;
  29604. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  29605. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  29606. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  29607. if( zDir==0 ) continue;
  29608. if( osStat(zDir, &buf) ) continue;
  29609. if( !S_ISDIR(buf.st_mode) ) continue;
  29610. if( osAccess(zDir, 07) ) continue;
  29611. break;
  29612. }
  29613. return zDir;
  29614. }
  29615. /*
  29616. ** Create a temporary file name in zBuf. zBuf must be allocated
  29617. ** by the calling process and must be big enough to hold at least
  29618. ** pVfs->mxPathname bytes.
  29619. */
  29620. static int unixGetTempname(int nBuf, char *zBuf){
  29621. static const unsigned char zChars[] =
  29622. "abcdefghijklmnopqrstuvwxyz"
  29623. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  29624. "0123456789";
  29625. unsigned int i, j;
  29626. const char *zDir;
  29627. /* It's odd to simulate an io-error here, but really this is just
  29628. ** using the io-error infrastructure to test that SQLite handles this
  29629. ** function failing.
  29630. */
  29631. SimulateIOError( return SQLITE_IOERR );
  29632. zDir = unixTempFileDir();
  29633. if( zDir==0 ) zDir = ".";
  29634. /* Check that the output buffer is large enough for the temporary file
  29635. ** name. If it is not, return SQLITE_ERROR.
  29636. */
  29637. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  29638. return SQLITE_ERROR;
  29639. }
  29640. do{
  29641. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  29642. j = (int)strlen(zBuf);
  29643. sqlite3_randomness(15, &zBuf[j]);
  29644. for(i=0; i<15; i++, j++){
  29645. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  29646. }
  29647. zBuf[j] = 0;
  29648. zBuf[j+1] = 0;
  29649. }while( osAccess(zBuf,0)==0 );
  29650. return SQLITE_OK;
  29651. }
  29652. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29653. /*
  29654. ** Routine to transform a unixFile into a proxy-locking unixFile.
  29655. ** Implementation in the proxy-lock division, but used by unixOpen()
  29656. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  29657. */
  29658. static int proxyTransformUnixFile(unixFile*, const char*);
  29659. #endif
  29660. /*
  29661. ** Search for an unused file descriptor that was opened on the database
  29662. ** file (not a journal or master-journal file) identified by pathname
  29663. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  29664. ** argument to this function.
  29665. **
  29666. ** Such a file descriptor may exist if a database connection was closed
  29667. ** but the associated file descriptor could not be closed because some
  29668. ** other file descriptor open on the same file is holding a file-lock.
  29669. ** Refer to comments in the unixClose() function and the lengthy comment
  29670. ** describing "Posix Advisory Locking" at the start of this file for
  29671. ** further details. Also, ticket #4018.
  29672. **
  29673. ** If a suitable file descriptor is found, then it is returned. If no
  29674. ** such file descriptor is located, -1 is returned.
  29675. */
  29676. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  29677. UnixUnusedFd *pUnused = 0;
  29678. /* Do not search for an unused file descriptor on vxworks. Not because
  29679. ** vxworks would not benefit from the change (it might, we're not sure),
  29680. ** but because no way to test it is currently available. It is better
  29681. ** not to risk breaking vxworks support for the sake of such an obscure
  29682. ** feature. */
  29683. #if !OS_VXWORKS
  29684. struct stat sStat; /* Results of stat() call */
  29685. /* A stat() call may fail for various reasons. If this happens, it is
  29686. ** almost certain that an open() call on the same path will also fail.
  29687. ** For this reason, if an error occurs in the stat() call here, it is
  29688. ** ignored and -1 is returned. The caller will try to open a new file
  29689. ** descriptor on the same path, fail, and return an error to SQLite.
  29690. **
  29691. ** Even if a subsequent open() call does succeed, the consequences of
  29692. ** not searching for a reusable file descriptor are not dire. */
  29693. if( 0==osStat(zPath, &sStat) ){
  29694. unixInodeInfo *pInode;
  29695. unixEnterMutex();
  29696. pInode = inodeList;
  29697. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  29698. || pInode->fileId.ino!=sStat.st_ino) ){
  29699. pInode = pInode->pNext;
  29700. }
  29701. if( pInode ){
  29702. UnixUnusedFd **pp;
  29703. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  29704. pUnused = *pp;
  29705. if( pUnused ){
  29706. *pp = pUnused->pNext;
  29707. }
  29708. }
  29709. unixLeaveMutex();
  29710. }
  29711. #endif /* if !OS_VXWORKS */
  29712. return pUnused;
  29713. }
  29714. /*
  29715. ** This function is called by unixOpen() to determine the unix permissions
  29716. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  29717. ** and a value suitable for passing as the third argument to open(2) is
  29718. ** written to *pMode. If an IO error occurs, an SQLite error code is
  29719. ** returned and the value of *pMode is not modified.
  29720. **
  29721. ** In most cases, this routine sets *pMode to 0, which will become
  29722. ** an indication to robust_open() to create the file using
  29723. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  29724. ** But if the file being opened is a WAL or regular journal file, then
  29725. ** this function queries the file-system for the permissions on the
  29726. ** corresponding database file and sets *pMode to this value. Whenever
  29727. ** possible, WAL and journal files are created using the same permissions
  29728. ** as the associated database file.
  29729. **
  29730. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  29731. ** original filename is unavailable. But 8_3_NAMES is only used for
  29732. ** FAT filesystems and permissions do not matter there, so just use
  29733. ** the default permissions.
  29734. */
  29735. static int findCreateFileMode(
  29736. const char *zPath, /* Path of file (possibly) being created */
  29737. int flags, /* Flags passed as 4th argument to xOpen() */
  29738. mode_t *pMode, /* OUT: Permissions to open file with */
  29739. uid_t *pUid, /* OUT: uid to set on the file */
  29740. gid_t *pGid /* OUT: gid to set on the file */
  29741. ){
  29742. int rc = SQLITE_OK; /* Return Code */
  29743. *pMode = 0;
  29744. *pUid = 0;
  29745. *pGid = 0;
  29746. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  29747. char zDb[MAX_PATHNAME+1]; /* Database file path */
  29748. int nDb; /* Number of valid bytes in zDb */
  29749. struct stat sStat; /* Output of stat() on database file */
  29750. /* zPath is a path to a WAL or journal file. The following block derives
  29751. ** the path to the associated database file from zPath. This block handles
  29752. ** the following naming conventions:
  29753. **
  29754. ** "<path to db>-journal"
  29755. ** "<path to db>-wal"
  29756. ** "<path to db>-journalNN"
  29757. ** "<path to db>-walNN"
  29758. **
  29759. ** where NN is a decimal number. The NN naming schemes are
  29760. ** used by the test_multiplex.c module.
  29761. */
  29762. nDb = sqlite3Strlen30(zPath) - 1;
  29763. #ifdef SQLITE_ENABLE_8_3_NAMES
  29764. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  29765. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  29766. #else
  29767. while( zPath[nDb]!='-' ){
  29768. assert( nDb>0 );
  29769. assert( zPath[nDb]!='\n' );
  29770. nDb--;
  29771. }
  29772. #endif
  29773. memcpy(zDb, zPath, nDb);
  29774. zDb[nDb] = '\0';
  29775. if( 0==osStat(zDb, &sStat) ){
  29776. *pMode = sStat.st_mode & 0777;
  29777. *pUid = sStat.st_uid;
  29778. *pGid = sStat.st_gid;
  29779. }else{
  29780. rc = SQLITE_IOERR_FSTAT;
  29781. }
  29782. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  29783. *pMode = 0600;
  29784. }
  29785. return rc;
  29786. }
  29787. /*
  29788. ** Open the file zPath.
  29789. **
  29790. ** Previously, the SQLite OS layer used three functions in place of this
  29791. ** one:
  29792. **
  29793. ** sqlite3OsOpenReadWrite();
  29794. ** sqlite3OsOpenReadOnly();
  29795. ** sqlite3OsOpenExclusive();
  29796. **
  29797. ** These calls correspond to the following combinations of flags:
  29798. **
  29799. ** ReadWrite() -> (READWRITE | CREATE)
  29800. ** ReadOnly() -> (READONLY)
  29801. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  29802. **
  29803. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  29804. ** true, the file was configured to be automatically deleted when the
  29805. ** file handle closed. To achieve the same effect using this new
  29806. ** interface, add the DELETEONCLOSE flag to those specified above for
  29807. ** OpenExclusive().
  29808. */
  29809. static int unixOpen(
  29810. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  29811. const char *zPath, /* Pathname of file to be opened */
  29812. sqlite3_file *pFile, /* The file descriptor to be filled in */
  29813. int flags, /* Input flags to control the opening */
  29814. int *pOutFlags /* Output flags returned to SQLite core */
  29815. ){
  29816. unixFile *p = (unixFile *)pFile;
  29817. int fd = -1; /* File descriptor returned by open() */
  29818. int openFlags = 0; /* Flags to pass to open() */
  29819. int eType = flags&0xFFFFFF00; /* Type of file to open */
  29820. int noLock; /* True to omit locking primitives */
  29821. int rc = SQLITE_OK; /* Function Return Code */
  29822. int ctrlFlags = 0; /* UNIXFILE_* flags */
  29823. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  29824. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  29825. int isCreate = (flags & SQLITE_OPEN_CREATE);
  29826. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  29827. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  29828. #if SQLITE_ENABLE_LOCKING_STYLE
  29829. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  29830. #endif
  29831. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  29832. struct statfs fsInfo;
  29833. #endif
  29834. /* If creating a master or main-file journal, this function will open
  29835. ** a file-descriptor on the directory too. The first time unixSync()
  29836. ** is called the directory file descriptor will be fsync()ed and close()d.
  29837. */
  29838. int syncDir = (isCreate && (
  29839. eType==SQLITE_OPEN_MASTER_JOURNAL
  29840. || eType==SQLITE_OPEN_MAIN_JOURNAL
  29841. || eType==SQLITE_OPEN_WAL
  29842. ));
  29843. /* If argument zPath is a NULL pointer, this function is required to open
  29844. ** a temporary file. Use this buffer to store the file name in.
  29845. */
  29846. char zTmpname[MAX_PATHNAME+2];
  29847. const char *zName = zPath;
  29848. /* Check the following statements are true:
  29849. **
  29850. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  29851. ** (b) if CREATE is set, then READWRITE must also be set, and
  29852. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  29853. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  29854. */
  29855. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  29856. assert(isCreate==0 || isReadWrite);
  29857. assert(isExclusive==0 || isCreate);
  29858. assert(isDelete==0 || isCreate);
  29859. /* The main DB, main journal, WAL file and master journal are never
  29860. ** automatically deleted. Nor are they ever temporary files. */
  29861. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  29862. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  29863. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  29864. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  29865. /* Assert that the upper layer has set one of the "file-type" flags. */
  29866. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  29867. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  29868. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  29869. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  29870. );
  29871. /* Detect a pid change and reset the PRNG. There is a race condition
  29872. ** here such that two or more threads all trying to open databases at
  29873. ** the same instant might all reset the PRNG. But multiple resets
  29874. ** are harmless.
  29875. */
  29876. if( randomnessPid!=osGetpid(0) ){
  29877. randomnessPid = osGetpid(0);
  29878. sqlite3_randomness(0,0);
  29879. }
  29880. memset(p, 0, sizeof(unixFile));
  29881. if( eType==SQLITE_OPEN_MAIN_DB ){
  29882. UnixUnusedFd *pUnused;
  29883. pUnused = findReusableFd(zName, flags);
  29884. if( pUnused ){
  29885. fd = pUnused->fd;
  29886. }else{
  29887. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  29888. if( !pUnused ){
  29889. return SQLITE_NOMEM;
  29890. }
  29891. }
  29892. p->pUnused = pUnused;
  29893. /* Database filenames are double-zero terminated if they are not
  29894. ** URIs with parameters. Hence, they can always be passed into
  29895. ** sqlite3_uri_parameter(). */
  29896. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  29897. }else if( !zName ){
  29898. /* If zName is NULL, the upper layer is requesting a temp file. */
  29899. assert(isDelete && !syncDir);
  29900. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  29901. if( rc!=SQLITE_OK ){
  29902. return rc;
  29903. }
  29904. zName = zTmpname;
  29905. /* Generated temporary filenames are always double-zero terminated
  29906. ** for use by sqlite3_uri_parameter(). */
  29907. assert( zName[strlen(zName)+1]==0 );
  29908. }
  29909. /* Determine the value of the flags parameter passed to POSIX function
  29910. ** open(). These must be calculated even if open() is not called, as
  29911. ** they may be stored as part of the file handle and used by the
  29912. ** 'conch file' locking functions later on. */
  29913. if( isReadonly ) openFlags |= O_RDONLY;
  29914. if( isReadWrite ) openFlags |= O_RDWR;
  29915. if( isCreate ) openFlags |= O_CREAT;
  29916. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  29917. openFlags |= (O_LARGEFILE|O_BINARY);
  29918. if( fd<0 ){
  29919. mode_t openMode; /* Permissions to create file with */
  29920. uid_t uid; /* Userid for the file */
  29921. gid_t gid; /* Groupid for the file */
  29922. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  29923. if( rc!=SQLITE_OK ){
  29924. assert( !p->pUnused );
  29925. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  29926. return rc;
  29927. }
  29928. fd = robust_open(zName, openFlags, openMode);
  29929. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  29930. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  29931. /* Failed to open the file for read/write access. Try read-only. */
  29932. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  29933. openFlags &= ~(O_RDWR|O_CREAT);
  29934. flags |= SQLITE_OPEN_READONLY;
  29935. openFlags |= O_RDONLY;
  29936. isReadonly = 1;
  29937. fd = robust_open(zName, openFlags, openMode);
  29938. }
  29939. if( fd<0 ){
  29940. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  29941. goto open_finished;
  29942. }
  29943. /* If this process is running as root and if creating a new rollback
  29944. ** journal or WAL file, set the ownership of the journal or WAL to be
  29945. ** the same as the original database.
  29946. */
  29947. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  29948. osFchown(fd, uid, gid);
  29949. }
  29950. }
  29951. assert( fd>=0 );
  29952. if( pOutFlags ){
  29953. *pOutFlags = flags;
  29954. }
  29955. if( p->pUnused ){
  29956. p->pUnused->fd = fd;
  29957. p->pUnused->flags = flags;
  29958. }
  29959. if( isDelete ){
  29960. #if OS_VXWORKS
  29961. zPath = zName;
  29962. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  29963. zPath = sqlite3_mprintf("%s", zName);
  29964. if( zPath==0 ){
  29965. robust_close(p, fd, __LINE__);
  29966. return SQLITE_NOMEM;
  29967. }
  29968. #else
  29969. osUnlink(zName);
  29970. #endif
  29971. }
  29972. #if SQLITE_ENABLE_LOCKING_STYLE
  29973. else{
  29974. p->openFlags = openFlags;
  29975. }
  29976. #endif
  29977. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  29978. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  29979. if( fstatfs(fd, &fsInfo) == -1 ){
  29980. storeLastErrno(p, errno);
  29981. robust_close(p, fd, __LINE__);
  29982. return SQLITE_IOERR_ACCESS;
  29983. }
  29984. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  29985. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  29986. }
  29987. if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
  29988. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  29989. }
  29990. #endif
  29991. /* Set up appropriate ctrlFlags */
  29992. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  29993. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  29994. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  29995. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  29996. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  29997. #if SQLITE_ENABLE_LOCKING_STYLE
  29998. #if SQLITE_PREFER_PROXY_LOCKING
  29999. isAutoProxy = 1;
  30000. #endif
  30001. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  30002. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  30003. int useProxy = 0;
  30004. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  30005. ** never use proxy, NULL means use proxy for non-local files only. */
  30006. if( envforce!=NULL ){
  30007. useProxy = atoi(envforce)>0;
  30008. }else{
  30009. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  30010. }
  30011. if( useProxy ){
  30012. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  30013. if( rc==SQLITE_OK ){
  30014. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  30015. if( rc!=SQLITE_OK ){
  30016. /* Use unixClose to clean up the resources added in fillInUnixFile
  30017. ** and clear all the structure's references. Specifically,
  30018. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  30019. */
  30020. unixClose(pFile);
  30021. return rc;
  30022. }
  30023. }
  30024. goto open_finished;
  30025. }
  30026. }
  30027. #endif
  30028. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  30029. open_finished:
  30030. if( rc!=SQLITE_OK ){
  30031. sqlite3_free(p->pUnused);
  30032. }
  30033. return rc;
  30034. }
  30035. /*
  30036. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  30037. ** the directory after deleting the file.
  30038. */
  30039. static int unixDelete(
  30040. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  30041. const char *zPath, /* Name of file to be deleted */
  30042. int dirSync /* If true, fsync() directory after deleting file */
  30043. ){
  30044. int rc = SQLITE_OK;
  30045. UNUSED_PARAMETER(NotUsed);
  30046. SimulateIOError(return SQLITE_IOERR_DELETE);
  30047. if( osUnlink(zPath)==(-1) ){
  30048. if( errno==ENOENT
  30049. #if OS_VXWORKS
  30050. || osAccess(zPath,0)!=0
  30051. #endif
  30052. ){
  30053. rc = SQLITE_IOERR_DELETE_NOENT;
  30054. }else{
  30055. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  30056. }
  30057. return rc;
  30058. }
  30059. #ifndef SQLITE_DISABLE_DIRSYNC
  30060. if( (dirSync & 1)!=0 ){
  30061. int fd;
  30062. rc = osOpenDirectory(zPath, &fd);
  30063. if( rc==SQLITE_OK ){
  30064. #if OS_VXWORKS
  30065. if( fsync(fd)==-1 )
  30066. #else
  30067. if( fsync(fd) )
  30068. #endif
  30069. {
  30070. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  30071. }
  30072. robust_close(0, fd, __LINE__);
  30073. }else if( rc==SQLITE_CANTOPEN ){
  30074. rc = SQLITE_OK;
  30075. }
  30076. }
  30077. #endif
  30078. return rc;
  30079. }
  30080. /*
  30081. ** Test the existence of or access permissions of file zPath. The
  30082. ** test performed depends on the value of flags:
  30083. **
  30084. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  30085. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  30086. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  30087. **
  30088. ** Otherwise return 0.
  30089. */
  30090. static int unixAccess(
  30091. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  30092. const char *zPath, /* Path of the file to examine */
  30093. int flags, /* What do we want to learn about the zPath file? */
  30094. int *pResOut /* Write result boolean here */
  30095. ){
  30096. int amode = 0;
  30097. UNUSED_PARAMETER(NotUsed);
  30098. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  30099. switch( flags ){
  30100. case SQLITE_ACCESS_EXISTS:
  30101. amode = F_OK;
  30102. break;
  30103. case SQLITE_ACCESS_READWRITE:
  30104. amode = W_OK|R_OK;
  30105. break;
  30106. case SQLITE_ACCESS_READ:
  30107. amode = R_OK;
  30108. break;
  30109. default:
  30110. assert(!"Invalid flags argument");
  30111. }
  30112. *pResOut = (osAccess(zPath, amode)==0);
  30113. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  30114. struct stat buf;
  30115. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  30116. *pResOut = 0;
  30117. }
  30118. }
  30119. return SQLITE_OK;
  30120. }
  30121. /*
  30122. ** Turn a relative pathname into a full pathname. The relative path
  30123. ** is stored as a nul-terminated string in the buffer pointed to by
  30124. ** zPath.
  30125. **
  30126. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  30127. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  30128. ** this buffer before returning.
  30129. */
  30130. static int unixFullPathname(
  30131. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  30132. const char *zPath, /* Possibly relative input path */
  30133. int nOut, /* Size of output buffer in bytes */
  30134. char *zOut /* Output buffer */
  30135. ){
  30136. /* It's odd to simulate an io-error here, but really this is just
  30137. ** using the io-error infrastructure to test that SQLite handles this
  30138. ** function failing. This function could fail if, for example, the
  30139. ** current working directory has been unlinked.
  30140. */
  30141. SimulateIOError( return SQLITE_ERROR );
  30142. assert( pVfs->mxPathname==MAX_PATHNAME );
  30143. UNUSED_PARAMETER(pVfs);
  30144. zOut[nOut-1] = '\0';
  30145. if( zPath[0]=='/' ){
  30146. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  30147. }else{
  30148. int nCwd;
  30149. if( osGetcwd(zOut, nOut-1)==0 ){
  30150. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  30151. }
  30152. nCwd = (int)strlen(zOut);
  30153. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  30154. }
  30155. return SQLITE_OK;
  30156. }
  30157. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  30158. /*
  30159. ** Interfaces for opening a shared library, finding entry points
  30160. ** within the shared library, and closing the shared library.
  30161. */
  30162. #include <dlfcn.h>
  30163. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  30164. UNUSED_PARAMETER(NotUsed);
  30165. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  30166. }
  30167. /*
  30168. ** SQLite calls this function immediately after a call to unixDlSym() or
  30169. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  30170. ** message is available, it is written to zBufOut. If no error message
  30171. ** is available, zBufOut is left unmodified and SQLite uses a default
  30172. ** error message.
  30173. */
  30174. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  30175. const char *zErr;
  30176. UNUSED_PARAMETER(NotUsed);
  30177. unixEnterMutex();
  30178. zErr = dlerror();
  30179. if( zErr ){
  30180. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  30181. }
  30182. unixLeaveMutex();
  30183. }
  30184. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  30185. /*
  30186. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  30187. ** cast into a pointer to a function. And yet the library dlsym() routine
  30188. ** returns a void* which is really a pointer to a function. So how do we
  30189. ** use dlsym() with -pedantic-errors?
  30190. **
  30191. ** Variable x below is defined to be a pointer to a function taking
  30192. ** parameters void* and const char* and returning a pointer to a function.
  30193. ** We initialize x by assigning it a pointer to the dlsym() function.
  30194. ** (That assignment requires a cast.) Then we call the function that
  30195. ** x points to.
  30196. **
  30197. ** This work-around is unlikely to work correctly on any system where
  30198. ** you really cannot cast a function pointer into void*. But then, on the
  30199. ** other hand, dlsym() will not work on such a system either, so we have
  30200. ** not really lost anything.
  30201. */
  30202. void (*(*x)(void*,const char*))(void);
  30203. UNUSED_PARAMETER(NotUsed);
  30204. x = (void(*(*)(void*,const char*))(void))dlsym;
  30205. return (*x)(p, zSym);
  30206. }
  30207. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  30208. UNUSED_PARAMETER(NotUsed);
  30209. dlclose(pHandle);
  30210. }
  30211. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  30212. #define unixDlOpen 0
  30213. #define unixDlError 0
  30214. #define unixDlSym 0
  30215. #define unixDlClose 0
  30216. #endif
  30217. /*
  30218. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  30219. */
  30220. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  30221. UNUSED_PARAMETER(NotUsed);
  30222. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  30223. /* We have to initialize zBuf to prevent valgrind from reporting
  30224. ** errors. The reports issued by valgrind are incorrect - we would
  30225. ** prefer that the randomness be increased by making use of the
  30226. ** uninitialized space in zBuf - but valgrind errors tend to worry
  30227. ** some users. Rather than argue, it seems easier just to initialize
  30228. ** the whole array and silence valgrind, even if that means less randomness
  30229. ** in the random seed.
  30230. **
  30231. ** When testing, initializing zBuf[] to zero is all we do. That means
  30232. ** that we always use the same random number sequence. This makes the
  30233. ** tests repeatable.
  30234. */
  30235. memset(zBuf, 0, nBuf);
  30236. randomnessPid = osGetpid(0);
  30237. #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
  30238. {
  30239. int fd, got;
  30240. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  30241. if( fd<0 ){
  30242. time_t t;
  30243. time(&t);
  30244. memcpy(zBuf, &t, sizeof(t));
  30245. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  30246. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  30247. nBuf = sizeof(t) + sizeof(randomnessPid);
  30248. }else{
  30249. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  30250. robust_close(0, fd, __LINE__);
  30251. }
  30252. }
  30253. #endif
  30254. return nBuf;
  30255. }
  30256. /*
  30257. ** Sleep for a little while. Return the amount of time slept.
  30258. ** The argument is the number of microseconds we want to sleep.
  30259. ** The return value is the number of microseconds of sleep actually
  30260. ** requested from the underlying operating system, a number which
  30261. ** might be greater than or equal to the argument, but not less
  30262. ** than the argument.
  30263. */
  30264. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  30265. #if OS_VXWORKS
  30266. struct timespec sp;
  30267. sp.tv_sec = microseconds / 1000000;
  30268. sp.tv_nsec = (microseconds % 1000000) * 1000;
  30269. nanosleep(&sp, NULL);
  30270. UNUSED_PARAMETER(NotUsed);
  30271. return microseconds;
  30272. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  30273. usleep(microseconds);
  30274. UNUSED_PARAMETER(NotUsed);
  30275. return microseconds;
  30276. #else
  30277. int seconds = (microseconds+999999)/1000000;
  30278. sleep(seconds);
  30279. UNUSED_PARAMETER(NotUsed);
  30280. return seconds*1000000;
  30281. #endif
  30282. }
  30283. /*
  30284. ** The following variable, if set to a non-zero value, is interpreted as
  30285. ** the number of seconds since 1970 and is used to set the result of
  30286. ** sqlite3OsCurrentTime() during testing.
  30287. */
  30288. #ifdef SQLITE_TEST
  30289. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  30290. #endif
  30291. /*
  30292. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  30293. ** the current time and date as a Julian Day number times 86_400_000. In
  30294. ** other words, write into *piNow the number of milliseconds since the Julian
  30295. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  30296. ** proleptic Gregorian calendar.
  30297. **
  30298. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  30299. ** cannot be found.
  30300. */
  30301. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  30302. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  30303. int rc = SQLITE_OK;
  30304. #if defined(NO_GETTOD)
  30305. time_t t;
  30306. time(&t);
  30307. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  30308. #elif OS_VXWORKS
  30309. struct timespec sNow;
  30310. clock_gettime(CLOCK_REALTIME, &sNow);
  30311. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  30312. #else
  30313. struct timeval sNow;
  30314. if( gettimeofday(&sNow, 0)==0 ){
  30315. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  30316. }else{
  30317. rc = SQLITE_ERROR;
  30318. }
  30319. #endif
  30320. #ifdef SQLITE_TEST
  30321. if( sqlite3_current_time ){
  30322. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  30323. }
  30324. #endif
  30325. UNUSED_PARAMETER(NotUsed);
  30326. return rc;
  30327. }
  30328. /*
  30329. ** Find the current time (in Universal Coordinated Time). Write the
  30330. ** current time and date as a Julian Day number into *prNow and
  30331. ** return 0. Return 1 if the time and date cannot be found.
  30332. */
  30333. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  30334. sqlite3_int64 i = 0;
  30335. int rc;
  30336. UNUSED_PARAMETER(NotUsed);
  30337. rc = unixCurrentTimeInt64(0, &i);
  30338. *prNow = i/86400000.0;
  30339. return rc;
  30340. }
  30341. /*
  30342. ** We added the xGetLastError() method with the intention of providing
  30343. ** better low-level error messages when operating-system problems come up
  30344. ** during SQLite operation. But so far, none of that has been implemented
  30345. ** in the core. So this routine is never called. For now, it is merely
  30346. ** a place-holder.
  30347. */
  30348. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  30349. UNUSED_PARAMETER(NotUsed);
  30350. UNUSED_PARAMETER(NotUsed2);
  30351. UNUSED_PARAMETER(NotUsed3);
  30352. return 0;
  30353. }
  30354. /*
  30355. ************************ End of sqlite3_vfs methods ***************************
  30356. ******************************************************************************/
  30357. /******************************************************************************
  30358. ************************** Begin Proxy Locking ********************************
  30359. **
  30360. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  30361. ** other locking methods on secondary lock files. Proxy locking is a
  30362. ** meta-layer over top of the primitive locking implemented above. For
  30363. ** this reason, the division that implements of proxy locking is deferred
  30364. ** until late in the file (here) after all of the other I/O methods have
  30365. ** been defined - so that the primitive locking methods are available
  30366. ** as services to help with the implementation of proxy locking.
  30367. **
  30368. ****
  30369. **
  30370. ** The default locking schemes in SQLite use byte-range locks on the
  30371. ** database file to coordinate safe, concurrent access by multiple readers
  30372. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  30373. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  30374. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  30375. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  30376. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  30377. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  30378. ** address in the shared range is taken for a SHARED lock, the entire
  30379. ** shared range is taken for an EXCLUSIVE lock):
  30380. **
  30381. ** PENDING_BYTE 0x40000000
  30382. ** RESERVED_BYTE 0x40000001
  30383. ** SHARED_RANGE 0x40000002 -> 0x40000200
  30384. **
  30385. ** This works well on the local file system, but shows a nearly 100x
  30386. ** slowdown in read performance on AFP because the AFP client disables
  30387. ** the read cache when byte-range locks are present. Enabling the read
  30388. ** cache exposes a cache coherency problem that is present on all OS X
  30389. ** supported network file systems. NFS and AFP both observe the
  30390. ** close-to-open semantics for ensuring cache coherency
  30391. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  30392. ** address the requirements for concurrent database access by multiple
  30393. ** readers and writers
  30394. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  30395. **
  30396. ** To address the performance and cache coherency issues, proxy file locking
  30397. ** changes the way database access is controlled by limiting access to a
  30398. ** single host at a time and moving file locks off of the database file
  30399. ** and onto a proxy file on the local file system.
  30400. **
  30401. **
  30402. ** Using proxy locks
  30403. ** -----------------
  30404. **
  30405. ** C APIs
  30406. **
  30407. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
  30408. ** <proxy_path> | ":auto:");
  30409. ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
  30410. ** &<proxy_path>);
  30411. **
  30412. **
  30413. ** SQL pragmas
  30414. **
  30415. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  30416. ** PRAGMA [database.]lock_proxy_file
  30417. **
  30418. ** Specifying ":auto:" means that if there is a conch file with a matching
  30419. ** host ID in it, the proxy path in the conch file will be used, otherwise
  30420. ** a proxy path based on the user's temp dir
  30421. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  30422. ** actual proxy file name is generated from the name and path of the
  30423. ** database file. For example:
  30424. **
  30425. ** For database path "/Users/me/foo.db"
  30426. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  30427. **
  30428. ** Once a lock proxy is configured for a database connection, it can not
  30429. ** be removed, however it may be switched to a different proxy path via
  30430. ** the above APIs (assuming the conch file is not being held by another
  30431. ** connection or process).
  30432. **
  30433. **
  30434. ** How proxy locking works
  30435. ** -----------------------
  30436. **
  30437. ** Proxy file locking relies primarily on two new supporting files:
  30438. **
  30439. ** * conch file to limit access to the database file to a single host
  30440. ** at a time
  30441. **
  30442. ** * proxy file to act as a proxy for the advisory locks normally
  30443. ** taken on the database
  30444. **
  30445. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  30446. ** by taking an sqlite-style shared lock on the conch file, reading the
  30447. ** contents and comparing the host's unique host ID (see below) and lock
  30448. ** proxy path against the values stored in the conch. The conch file is
  30449. ** stored in the same directory as the database file and the file name
  30450. ** is patterned after the database file name as ".<databasename>-conch".
  30451. ** If the conch file does not exist, or its contents do not match the
  30452. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  30453. ** lock and the conch file contents is updated with the host ID and proxy
  30454. ** path and the lock is downgraded to a shared lock again. If the conch
  30455. ** is held by another process (with a shared lock), the exclusive lock
  30456. ** will fail and SQLITE_BUSY is returned.
  30457. **
  30458. ** The proxy file - a single-byte file used for all advisory file locks
  30459. ** normally taken on the database file. This allows for safe sharing
  30460. ** of the database file for multiple readers and writers on the same
  30461. ** host (the conch ensures that they all use the same local lock file).
  30462. **
  30463. ** Requesting the lock proxy does not immediately take the conch, it is
  30464. ** only taken when the first request to lock database file is made.
  30465. ** This matches the semantics of the traditional locking behavior, where
  30466. ** opening a connection to a database file does not take a lock on it.
  30467. ** The shared lock and an open file descriptor are maintained until
  30468. ** the connection to the database is closed.
  30469. **
  30470. ** The proxy file and the lock file are never deleted so they only need
  30471. ** to be created the first time they are used.
  30472. **
  30473. ** Configuration options
  30474. ** ---------------------
  30475. **
  30476. ** SQLITE_PREFER_PROXY_LOCKING
  30477. **
  30478. ** Database files accessed on non-local file systems are
  30479. ** automatically configured for proxy locking, lock files are
  30480. ** named automatically using the same logic as
  30481. ** PRAGMA lock_proxy_file=":auto:"
  30482. **
  30483. ** SQLITE_PROXY_DEBUG
  30484. **
  30485. ** Enables the logging of error messages during host id file
  30486. ** retrieval and creation
  30487. **
  30488. ** LOCKPROXYDIR
  30489. **
  30490. ** Overrides the default directory used for lock proxy files that
  30491. ** are named automatically via the ":auto:" setting
  30492. **
  30493. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  30494. **
  30495. ** Permissions to use when creating a directory for storing the
  30496. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  30497. **
  30498. **
  30499. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  30500. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  30501. ** force proxy locking to be used for every database file opened, and 0
  30502. ** will force automatic proxy locking to be disabled for all database
  30503. ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
  30504. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  30505. */
  30506. /*
  30507. ** Proxy locking is only available on MacOSX
  30508. */
  30509. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  30510. /*
  30511. ** The proxyLockingContext has the path and file structures for the remote
  30512. ** and local proxy files in it
  30513. */
  30514. typedef struct proxyLockingContext proxyLockingContext;
  30515. struct proxyLockingContext {
  30516. unixFile *conchFile; /* Open conch file */
  30517. char *conchFilePath; /* Name of the conch file */
  30518. unixFile *lockProxy; /* Open proxy lock file */
  30519. char *lockProxyPath; /* Name of the proxy lock file */
  30520. char *dbPath; /* Name of the open file */
  30521. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  30522. int nFails; /* Number of conch taking failures */
  30523. void *oldLockingContext; /* Original lockingcontext to restore on close */
  30524. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  30525. };
  30526. /*
  30527. ** The proxy lock file path for the database at dbPath is written into lPath,
  30528. ** which must point to valid, writable memory large enough for a maxLen length
  30529. ** file path.
  30530. */
  30531. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  30532. int len;
  30533. int dbLen;
  30534. int i;
  30535. #ifdef LOCKPROXYDIR
  30536. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  30537. #else
  30538. # ifdef _CS_DARWIN_USER_TEMP_DIR
  30539. {
  30540. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  30541. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  30542. lPath, errno, osGetpid(0)));
  30543. return SQLITE_IOERR_LOCK;
  30544. }
  30545. len = strlcat(lPath, "sqliteplocks", maxLen);
  30546. }
  30547. # else
  30548. len = strlcpy(lPath, "/tmp/", maxLen);
  30549. # endif
  30550. #endif
  30551. if( lPath[len-1]!='/' ){
  30552. len = strlcat(lPath, "/", maxLen);
  30553. }
  30554. /* transform the db path to a unique cache name */
  30555. dbLen = (int)strlen(dbPath);
  30556. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  30557. char c = dbPath[i];
  30558. lPath[i+len] = (c=='/')?'_':c;
  30559. }
  30560. lPath[i+len]='\0';
  30561. strlcat(lPath, ":auto:", maxLen);
  30562. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
  30563. return SQLITE_OK;
  30564. }
  30565. /*
  30566. ** Creates the lock file and any missing directories in lockPath
  30567. */
  30568. static int proxyCreateLockPath(const char *lockPath){
  30569. int i, len;
  30570. char buf[MAXPATHLEN];
  30571. int start = 0;
  30572. assert(lockPath!=NULL);
  30573. /* try to create all the intermediate directories */
  30574. len = (int)strlen(lockPath);
  30575. buf[0] = lockPath[0];
  30576. for( i=1; i<len; i++ ){
  30577. if( lockPath[i] == '/' && (i - start > 0) ){
  30578. /* only mkdir if leaf dir != "." or "/" or ".." */
  30579. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  30580. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  30581. buf[i]='\0';
  30582. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  30583. int err=errno;
  30584. if( err!=EEXIST ) {
  30585. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  30586. "'%s' proxy lock path=%s pid=%d\n",
  30587. buf, strerror(err), lockPath, osGetpid(0)));
  30588. return err;
  30589. }
  30590. }
  30591. }
  30592. start=i+1;
  30593. }
  30594. buf[i] = lockPath[i];
  30595. }
  30596. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
  30597. return 0;
  30598. }
  30599. /*
  30600. ** Create a new VFS file descriptor (stored in memory obtained from
  30601. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  30602. **
  30603. ** The caller is responsible not only for closing the file descriptor
  30604. ** but also for freeing the memory associated with the file descriptor.
  30605. */
  30606. static int proxyCreateUnixFile(
  30607. const char *path, /* path for the new unixFile */
  30608. unixFile **ppFile, /* unixFile created and returned by ref */
  30609. int islockfile /* if non zero missing dirs will be created */
  30610. ) {
  30611. int fd = -1;
  30612. unixFile *pNew;
  30613. int rc = SQLITE_OK;
  30614. int openFlags = O_RDWR | O_CREAT;
  30615. sqlite3_vfs dummyVfs;
  30616. int terrno = 0;
  30617. UnixUnusedFd *pUnused = NULL;
  30618. /* 1. first try to open/create the file
  30619. ** 2. if that fails, and this is a lock file (not-conch), try creating
  30620. ** the parent directories and then try again.
  30621. ** 3. if that fails, try to open the file read-only
  30622. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  30623. */
  30624. pUnused = findReusableFd(path, openFlags);
  30625. if( pUnused ){
  30626. fd = pUnused->fd;
  30627. }else{
  30628. pUnused = sqlite3_malloc64(sizeof(*pUnused));
  30629. if( !pUnused ){
  30630. return SQLITE_NOMEM;
  30631. }
  30632. }
  30633. if( fd<0 ){
  30634. fd = robust_open(path, openFlags, 0);
  30635. terrno = errno;
  30636. if( fd<0 && errno==ENOENT && islockfile ){
  30637. if( proxyCreateLockPath(path) == SQLITE_OK ){
  30638. fd = robust_open(path, openFlags, 0);
  30639. }
  30640. }
  30641. }
  30642. if( fd<0 ){
  30643. openFlags = O_RDONLY;
  30644. fd = robust_open(path, openFlags, 0);
  30645. terrno = errno;
  30646. }
  30647. if( fd<0 ){
  30648. if( islockfile ){
  30649. return SQLITE_BUSY;
  30650. }
  30651. switch (terrno) {
  30652. case EACCES:
  30653. return SQLITE_PERM;
  30654. case EIO:
  30655. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  30656. default:
  30657. return SQLITE_CANTOPEN_BKPT;
  30658. }
  30659. }
  30660. pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
  30661. if( pNew==NULL ){
  30662. rc = SQLITE_NOMEM;
  30663. goto end_create_proxy;
  30664. }
  30665. memset(pNew, 0, sizeof(unixFile));
  30666. pNew->openFlags = openFlags;
  30667. memset(&dummyVfs, 0, sizeof(dummyVfs));
  30668. dummyVfs.pAppData = (void*)&autolockIoFinder;
  30669. dummyVfs.zName = "dummy";
  30670. pUnused->fd = fd;
  30671. pUnused->flags = openFlags;
  30672. pNew->pUnused = pUnused;
  30673. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  30674. if( rc==SQLITE_OK ){
  30675. *ppFile = pNew;
  30676. return SQLITE_OK;
  30677. }
  30678. end_create_proxy:
  30679. robust_close(pNew, fd, __LINE__);
  30680. sqlite3_free(pNew);
  30681. sqlite3_free(pUnused);
  30682. return rc;
  30683. }
  30684. #ifdef SQLITE_TEST
  30685. /* simulate multiple hosts by creating unique hostid file paths */
  30686. SQLITE_API int sqlite3_hostid_num = 0;
  30687. #endif
  30688. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  30689. #ifdef HAVE_GETHOSTUUID
  30690. /* Not always defined in the headers as it ought to be */
  30691. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  30692. #endif
  30693. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  30694. ** bytes of writable memory.
  30695. */
  30696. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  30697. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  30698. memset(pHostID, 0, PROXY_HOSTIDLEN);
  30699. #ifdef HAVE_GETHOSTUUID
  30700. {
  30701. struct timespec timeout = {1, 0}; /* 1 sec timeout */
  30702. if( gethostuuid(pHostID, &timeout) ){
  30703. int err = errno;
  30704. if( pError ){
  30705. *pError = err;
  30706. }
  30707. return SQLITE_IOERR;
  30708. }
  30709. }
  30710. #else
  30711. UNUSED_PARAMETER(pError);
  30712. #endif
  30713. #ifdef SQLITE_TEST
  30714. /* simulate multiple hosts by creating unique hostid file paths */
  30715. if( sqlite3_hostid_num != 0){
  30716. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  30717. }
  30718. #endif
  30719. return SQLITE_OK;
  30720. }
  30721. /* The conch file contains the header, host id and lock file path
  30722. */
  30723. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  30724. #define PROXY_HEADERLEN 1 /* conch file header length */
  30725. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  30726. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  30727. /*
  30728. ** Takes an open conch file, copies the contents to a new path and then moves
  30729. ** it back. The newly created file's file descriptor is assigned to the
  30730. ** conch file structure and finally the original conch file descriptor is
  30731. ** closed. Returns zero if successful.
  30732. */
  30733. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  30734. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30735. unixFile *conchFile = pCtx->conchFile;
  30736. char tPath[MAXPATHLEN];
  30737. char buf[PROXY_MAXCONCHLEN];
  30738. char *cPath = pCtx->conchFilePath;
  30739. size_t readLen = 0;
  30740. size_t pathLen = 0;
  30741. char errmsg[64] = "";
  30742. int fd = -1;
  30743. int rc = -1;
  30744. UNUSED_PARAMETER(myHostID);
  30745. /* create a new path by replace the trailing '-conch' with '-break' */
  30746. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  30747. if( pathLen>MAXPATHLEN || pathLen<6 ||
  30748. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  30749. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  30750. goto end_breaklock;
  30751. }
  30752. /* read the conch content */
  30753. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  30754. if( readLen<PROXY_PATHINDEX ){
  30755. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  30756. goto end_breaklock;
  30757. }
  30758. /* write it out to the temporary break file */
  30759. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  30760. if( fd<0 ){
  30761. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  30762. goto end_breaklock;
  30763. }
  30764. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  30765. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  30766. goto end_breaklock;
  30767. }
  30768. if( rename(tPath, cPath) ){
  30769. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  30770. goto end_breaklock;
  30771. }
  30772. rc = 0;
  30773. fprintf(stderr, "broke stale lock on %s\n", cPath);
  30774. robust_close(pFile, conchFile->h, __LINE__);
  30775. conchFile->h = fd;
  30776. conchFile->openFlags = O_RDWR | O_CREAT;
  30777. end_breaklock:
  30778. if( rc ){
  30779. if( fd>=0 ){
  30780. osUnlink(tPath);
  30781. robust_close(pFile, fd, __LINE__);
  30782. }
  30783. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  30784. }
  30785. return rc;
  30786. }
  30787. /* Take the requested lock on the conch file and break a stale lock if the
  30788. ** host id matches.
  30789. */
  30790. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  30791. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30792. unixFile *conchFile = pCtx->conchFile;
  30793. int rc = SQLITE_OK;
  30794. int nTries = 0;
  30795. struct timespec conchModTime;
  30796. memset(&conchModTime, 0, sizeof(conchModTime));
  30797. do {
  30798. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  30799. nTries ++;
  30800. if( rc==SQLITE_BUSY ){
  30801. /* If the lock failed (busy):
  30802. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  30803. * 2nd try: fail if the mod time changed or host id is different, wait
  30804. * 10 sec and try again
  30805. * 3rd try: break the lock unless the mod time has changed.
  30806. */
  30807. struct stat buf;
  30808. if( osFstat(conchFile->h, &buf) ){
  30809. storeLastErrno(pFile, errno);
  30810. return SQLITE_IOERR_LOCK;
  30811. }
  30812. if( nTries==1 ){
  30813. conchModTime = buf.st_mtimespec;
  30814. usleep(500000); /* wait 0.5 sec and try the lock again*/
  30815. continue;
  30816. }
  30817. assert( nTries>1 );
  30818. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  30819. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  30820. return SQLITE_BUSY;
  30821. }
  30822. if( nTries==2 ){
  30823. char tBuf[PROXY_MAXCONCHLEN];
  30824. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  30825. if( len<0 ){
  30826. storeLastErrno(pFile, errno);
  30827. return SQLITE_IOERR_LOCK;
  30828. }
  30829. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  30830. /* don't break the lock if the host id doesn't match */
  30831. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  30832. return SQLITE_BUSY;
  30833. }
  30834. }else{
  30835. /* don't break the lock on short read or a version mismatch */
  30836. return SQLITE_BUSY;
  30837. }
  30838. usleep(10000000); /* wait 10 sec and try the lock again */
  30839. continue;
  30840. }
  30841. assert( nTries==3 );
  30842. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  30843. rc = SQLITE_OK;
  30844. if( lockType==EXCLUSIVE_LOCK ){
  30845. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  30846. }
  30847. if( !rc ){
  30848. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  30849. }
  30850. }
  30851. }
  30852. } while( rc==SQLITE_BUSY && nTries<3 );
  30853. return rc;
  30854. }
  30855. /* Takes the conch by taking a shared lock and read the contents conch, if
  30856. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  30857. ** lockPath means that the lockPath in the conch file will be used if the
  30858. ** host IDs match, or a new lock path will be generated automatically
  30859. ** and written to the conch file.
  30860. */
  30861. static int proxyTakeConch(unixFile *pFile){
  30862. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30863. if( pCtx->conchHeld!=0 ){
  30864. return SQLITE_OK;
  30865. }else{
  30866. unixFile *conchFile = pCtx->conchFile;
  30867. uuid_t myHostID;
  30868. int pError = 0;
  30869. char readBuf[PROXY_MAXCONCHLEN];
  30870. char lockPath[MAXPATHLEN];
  30871. char *tempLockPath = NULL;
  30872. int rc = SQLITE_OK;
  30873. int createConch = 0;
  30874. int hostIdMatch = 0;
  30875. int readLen = 0;
  30876. int tryOldLockPath = 0;
  30877. int forceNewLockPath = 0;
  30878. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  30879. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  30880. osGetpid(0)));
  30881. rc = proxyGetHostID(myHostID, &pError);
  30882. if( (rc&0xff)==SQLITE_IOERR ){
  30883. storeLastErrno(pFile, pError);
  30884. goto end_takeconch;
  30885. }
  30886. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  30887. if( rc!=SQLITE_OK ){
  30888. goto end_takeconch;
  30889. }
  30890. /* read the existing conch file */
  30891. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  30892. if( readLen<0 ){
  30893. /* I/O error: lastErrno set by seekAndRead */
  30894. storeLastErrno(pFile, conchFile->lastErrno);
  30895. rc = SQLITE_IOERR_READ;
  30896. goto end_takeconch;
  30897. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  30898. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  30899. /* a short read or version format mismatch means we need to create a new
  30900. ** conch file.
  30901. */
  30902. createConch = 1;
  30903. }
  30904. /* if the host id matches and the lock path already exists in the conch
  30905. ** we'll try to use the path there, if we can't open that path, we'll
  30906. ** retry with a new auto-generated path
  30907. */
  30908. do { /* in case we need to try again for an :auto: named lock file */
  30909. if( !createConch && !forceNewLockPath ){
  30910. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  30911. PROXY_HOSTIDLEN);
  30912. /* if the conch has data compare the contents */
  30913. if( !pCtx->lockProxyPath ){
  30914. /* for auto-named local lock file, just check the host ID and we'll
  30915. ** use the local lock file path that's already in there
  30916. */
  30917. if( hostIdMatch ){
  30918. size_t pathLen = (readLen - PROXY_PATHINDEX);
  30919. if( pathLen>=MAXPATHLEN ){
  30920. pathLen=MAXPATHLEN-1;
  30921. }
  30922. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  30923. lockPath[pathLen] = 0;
  30924. tempLockPath = lockPath;
  30925. tryOldLockPath = 1;
  30926. /* create a copy of the lock path if the conch is taken */
  30927. goto end_takeconch;
  30928. }
  30929. }else if( hostIdMatch
  30930. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  30931. readLen-PROXY_PATHINDEX)
  30932. ){
  30933. /* conch host and lock path match */
  30934. goto end_takeconch;
  30935. }
  30936. }
  30937. /* if the conch isn't writable and doesn't match, we can't take it */
  30938. if( (conchFile->openFlags&O_RDWR) == 0 ){
  30939. rc = SQLITE_BUSY;
  30940. goto end_takeconch;
  30941. }
  30942. /* either the conch didn't match or we need to create a new one */
  30943. if( !pCtx->lockProxyPath ){
  30944. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  30945. tempLockPath = lockPath;
  30946. /* create a copy of the lock path _only_ if the conch is taken */
  30947. }
  30948. /* update conch with host and path (this will fail if other process
  30949. ** has a shared lock already), if the host id matches, use the big
  30950. ** stick.
  30951. */
  30952. futimes(conchFile->h, NULL);
  30953. if( hostIdMatch && !createConch ){
  30954. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  30955. /* We are trying for an exclusive lock but another thread in this
  30956. ** same process is still holding a shared lock. */
  30957. rc = SQLITE_BUSY;
  30958. } else {
  30959. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  30960. }
  30961. }else{
  30962. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  30963. }
  30964. if( rc==SQLITE_OK ){
  30965. char writeBuffer[PROXY_MAXCONCHLEN];
  30966. int writeSize = 0;
  30967. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  30968. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  30969. if( pCtx->lockProxyPath!=NULL ){
  30970. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
  30971. MAXPATHLEN);
  30972. }else{
  30973. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  30974. }
  30975. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  30976. robust_ftruncate(conchFile->h, writeSize);
  30977. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  30978. fsync(conchFile->h);
  30979. /* If we created a new conch file (not just updated the contents of a
  30980. ** valid conch file), try to match the permissions of the database
  30981. */
  30982. if( rc==SQLITE_OK && createConch ){
  30983. struct stat buf;
  30984. int err = osFstat(pFile->h, &buf);
  30985. if( err==0 ){
  30986. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  30987. S_IROTH|S_IWOTH);
  30988. /* try to match the database file R/W permissions, ignore failure */
  30989. #ifndef SQLITE_PROXY_DEBUG
  30990. osFchmod(conchFile->h, cmode);
  30991. #else
  30992. do{
  30993. rc = osFchmod(conchFile->h, cmode);
  30994. }while( rc==(-1) && errno==EINTR );
  30995. if( rc!=0 ){
  30996. int code = errno;
  30997. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  30998. cmode, code, strerror(code));
  30999. } else {
  31000. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  31001. }
  31002. }else{
  31003. int code = errno;
  31004. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  31005. err, code, strerror(code));
  31006. #endif
  31007. }
  31008. }
  31009. }
  31010. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  31011. end_takeconch:
  31012. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  31013. if( rc==SQLITE_OK && pFile->openFlags ){
  31014. int fd;
  31015. if( pFile->h>=0 ){
  31016. robust_close(pFile, pFile->h, __LINE__);
  31017. }
  31018. pFile->h = -1;
  31019. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  31020. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  31021. if( fd>=0 ){
  31022. pFile->h = fd;
  31023. }else{
  31024. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  31025. during locking */
  31026. }
  31027. }
  31028. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  31029. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  31030. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  31031. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  31032. /* we couldn't create the proxy lock file with the old lock file path
  31033. ** so try again via auto-naming
  31034. */
  31035. forceNewLockPath = 1;
  31036. tryOldLockPath = 0;
  31037. continue; /* go back to the do {} while start point, try again */
  31038. }
  31039. }
  31040. if( rc==SQLITE_OK ){
  31041. /* Need to make a copy of path if we extracted the value
  31042. ** from the conch file or the path was allocated on the stack
  31043. */
  31044. if( tempLockPath ){
  31045. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  31046. if( !pCtx->lockProxyPath ){
  31047. rc = SQLITE_NOMEM;
  31048. }
  31049. }
  31050. }
  31051. if( rc==SQLITE_OK ){
  31052. pCtx->conchHeld = 1;
  31053. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  31054. afpLockingContext *afpCtx;
  31055. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  31056. afpCtx->dbPath = pCtx->lockProxyPath;
  31057. }
  31058. } else {
  31059. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  31060. }
  31061. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  31062. rc==SQLITE_OK?"ok":"failed"));
  31063. return rc;
  31064. } while (1); /* in case we need to retry the :auto: lock file -
  31065. ** we should never get here except via the 'continue' call. */
  31066. }
  31067. }
  31068. /*
  31069. ** If pFile holds a lock on a conch file, then release that lock.
  31070. */
  31071. static int proxyReleaseConch(unixFile *pFile){
  31072. int rc = SQLITE_OK; /* Subroutine return code */
  31073. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  31074. unixFile *conchFile; /* Name of the conch file */
  31075. pCtx = (proxyLockingContext *)pFile->lockingContext;
  31076. conchFile = pCtx->conchFile;
  31077. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  31078. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  31079. osGetpid(0)));
  31080. if( pCtx->conchHeld>0 ){
  31081. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  31082. }
  31083. pCtx->conchHeld = 0;
  31084. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  31085. (rc==SQLITE_OK ? "ok" : "failed")));
  31086. return rc;
  31087. }
  31088. /*
  31089. ** Given the name of a database file, compute the name of its conch file.
  31090. ** Store the conch filename in memory obtained from sqlite3_malloc64().
  31091. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  31092. ** or SQLITE_NOMEM if unable to obtain memory.
  31093. **
  31094. ** The caller is responsible for ensuring that the allocated memory
  31095. ** space is eventually freed.
  31096. **
  31097. ** *pConchPath is set to NULL if a memory allocation error occurs.
  31098. */
  31099. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  31100. int i; /* Loop counter */
  31101. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  31102. char *conchPath; /* buffer in which to construct conch name */
  31103. /* Allocate space for the conch filename and initialize the name to
  31104. ** the name of the original database file. */
  31105. *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
  31106. if( conchPath==0 ){
  31107. return SQLITE_NOMEM;
  31108. }
  31109. memcpy(conchPath, dbPath, len+1);
  31110. /* now insert a "." before the last / character */
  31111. for( i=(len-1); i>=0; i-- ){
  31112. if( conchPath[i]=='/' ){
  31113. i++;
  31114. break;
  31115. }
  31116. }
  31117. conchPath[i]='.';
  31118. while ( i<len ){
  31119. conchPath[i+1]=dbPath[i];
  31120. i++;
  31121. }
  31122. /* append the "-conch" suffix to the file */
  31123. memcpy(&conchPath[i+1], "-conch", 7);
  31124. assert( (int)strlen(conchPath) == len+7 );
  31125. return SQLITE_OK;
  31126. }
  31127. /* Takes a fully configured proxy locking-style unix file and switches
  31128. ** the local lock file path
  31129. */
  31130. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  31131. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  31132. char *oldPath = pCtx->lockProxyPath;
  31133. int rc = SQLITE_OK;
  31134. if( pFile->eFileLock!=NO_LOCK ){
  31135. return SQLITE_BUSY;
  31136. }
  31137. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  31138. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  31139. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  31140. return SQLITE_OK;
  31141. }else{
  31142. unixFile *lockProxy = pCtx->lockProxy;
  31143. pCtx->lockProxy=NULL;
  31144. pCtx->conchHeld = 0;
  31145. if( lockProxy!=NULL ){
  31146. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  31147. if( rc ) return rc;
  31148. sqlite3_free(lockProxy);
  31149. }
  31150. sqlite3_free(oldPath);
  31151. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  31152. }
  31153. return rc;
  31154. }
  31155. /*
  31156. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  31157. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  31158. **
  31159. ** This routine find the filename associated with pFile and writes it
  31160. ** int dbPath.
  31161. */
  31162. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  31163. #if defined(__APPLE__)
  31164. if( pFile->pMethod == &afpIoMethods ){
  31165. /* afp style keeps a reference to the db path in the filePath field
  31166. ** of the struct */
  31167. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  31168. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
  31169. MAXPATHLEN);
  31170. } else
  31171. #endif
  31172. if( pFile->pMethod == &dotlockIoMethods ){
  31173. /* dot lock style uses the locking context to store the dot lock
  31174. ** file path */
  31175. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  31176. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  31177. }else{
  31178. /* all other styles use the locking context to store the db file path */
  31179. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  31180. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  31181. }
  31182. return SQLITE_OK;
  31183. }
  31184. /*
  31185. ** Takes an already filled in unix file and alters it so all file locking
  31186. ** will be performed on the local proxy lock file. The following fields
  31187. ** are preserved in the locking context so that they can be restored and
  31188. ** the unix structure properly cleaned up at close time:
  31189. ** ->lockingContext
  31190. ** ->pMethod
  31191. */
  31192. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  31193. proxyLockingContext *pCtx;
  31194. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  31195. char *lockPath=NULL;
  31196. int rc = SQLITE_OK;
  31197. if( pFile->eFileLock!=NO_LOCK ){
  31198. return SQLITE_BUSY;
  31199. }
  31200. proxyGetDbPathForUnixFile(pFile, dbPath);
  31201. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  31202. lockPath=NULL;
  31203. }else{
  31204. lockPath=(char *)path;
  31205. }
  31206. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  31207. (lockPath ? lockPath : ":auto:"), osGetpid(0)));
  31208. pCtx = sqlite3_malloc64( sizeof(*pCtx) );
  31209. if( pCtx==0 ){
  31210. return SQLITE_NOMEM;
  31211. }
  31212. memset(pCtx, 0, sizeof(*pCtx));
  31213. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  31214. if( rc==SQLITE_OK ){
  31215. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  31216. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  31217. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  31218. ** (c) the file system is read-only, then enable no-locking access.
  31219. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  31220. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  31221. */
  31222. struct statfs fsInfo;
  31223. struct stat conchInfo;
  31224. int goLockless = 0;
  31225. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  31226. int err = errno;
  31227. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  31228. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  31229. }
  31230. }
  31231. if( goLockless ){
  31232. pCtx->conchHeld = -1; /* read only FS/ lockless */
  31233. rc = SQLITE_OK;
  31234. }
  31235. }
  31236. }
  31237. if( rc==SQLITE_OK && lockPath ){
  31238. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  31239. }
  31240. if( rc==SQLITE_OK ){
  31241. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  31242. if( pCtx->dbPath==NULL ){
  31243. rc = SQLITE_NOMEM;
  31244. }
  31245. }
  31246. if( rc==SQLITE_OK ){
  31247. /* all memory is allocated, proxys are created and assigned,
  31248. ** switch the locking context and pMethod then return.
  31249. */
  31250. pCtx->oldLockingContext = pFile->lockingContext;
  31251. pFile->lockingContext = pCtx;
  31252. pCtx->pOldMethod = pFile->pMethod;
  31253. pFile->pMethod = &proxyIoMethods;
  31254. }else{
  31255. if( pCtx->conchFile ){
  31256. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  31257. sqlite3_free(pCtx->conchFile);
  31258. }
  31259. sqlite3DbFree(0, pCtx->lockProxyPath);
  31260. sqlite3_free(pCtx->conchFilePath);
  31261. sqlite3_free(pCtx);
  31262. }
  31263. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  31264. (rc==SQLITE_OK ? "ok" : "failed")));
  31265. return rc;
  31266. }
  31267. /*
  31268. ** This routine handles sqlite3_file_control() calls that are specific
  31269. ** to proxy locking.
  31270. */
  31271. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  31272. switch( op ){
  31273. case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
  31274. unixFile *pFile = (unixFile*)id;
  31275. if( pFile->pMethod == &proxyIoMethods ){
  31276. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  31277. proxyTakeConch(pFile);
  31278. if( pCtx->lockProxyPath ){
  31279. *(const char **)pArg = pCtx->lockProxyPath;
  31280. }else{
  31281. *(const char **)pArg = ":auto: (not held)";
  31282. }
  31283. } else {
  31284. *(const char **)pArg = NULL;
  31285. }
  31286. return SQLITE_OK;
  31287. }
  31288. case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
  31289. unixFile *pFile = (unixFile*)id;
  31290. int rc = SQLITE_OK;
  31291. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  31292. if( pArg==NULL || (const char *)pArg==0 ){
  31293. if( isProxyStyle ){
  31294. /* turn off proxy locking - not supported. If support is added for
  31295. ** switching proxy locking mode off then it will need to fail if
  31296. ** the journal mode is WAL mode.
  31297. */
  31298. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  31299. }else{
  31300. /* turn off proxy locking - already off - NOOP */
  31301. rc = SQLITE_OK;
  31302. }
  31303. }else{
  31304. const char *proxyPath = (const char *)pArg;
  31305. if( isProxyStyle ){
  31306. proxyLockingContext *pCtx =
  31307. (proxyLockingContext*)pFile->lockingContext;
  31308. if( !strcmp(pArg, ":auto:")
  31309. || (pCtx->lockProxyPath &&
  31310. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  31311. ){
  31312. rc = SQLITE_OK;
  31313. }else{
  31314. rc = switchLockProxyPath(pFile, proxyPath);
  31315. }
  31316. }else{
  31317. /* turn on proxy file locking */
  31318. rc = proxyTransformUnixFile(pFile, proxyPath);
  31319. }
  31320. }
  31321. return rc;
  31322. }
  31323. default: {
  31324. assert( 0 ); /* The call assures that only valid opcodes are sent */
  31325. }
  31326. }
  31327. /*NOTREACHED*/
  31328. return SQLITE_ERROR;
  31329. }
  31330. /*
  31331. ** Within this division (the proxying locking implementation) the procedures
  31332. ** above this point are all utilities. The lock-related methods of the
  31333. ** proxy-locking sqlite3_io_method object follow.
  31334. */
  31335. /*
  31336. ** This routine checks if there is a RESERVED lock held on the specified
  31337. ** file by this or any other process. If such a lock is held, set *pResOut
  31338. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  31339. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  31340. */
  31341. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  31342. unixFile *pFile = (unixFile*)id;
  31343. int rc = proxyTakeConch(pFile);
  31344. if( rc==SQLITE_OK ){
  31345. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31346. if( pCtx->conchHeld>0 ){
  31347. unixFile *proxy = pCtx->lockProxy;
  31348. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  31349. }else{ /* conchHeld < 0 is lockless */
  31350. pResOut=0;
  31351. }
  31352. }
  31353. return rc;
  31354. }
  31355. /*
  31356. ** Lock the file with the lock specified by parameter eFileLock - one
  31357. ** of the following:
  31358. **
  31359. ** (1) SHARED_LOCK
  31360. ** (2) RESERVED_LOCK
  31361. ** (3) PENDING_LOCK
  31362. ** (4) EXCLUSIVE_LOCK
  31363. **
  31364. ** Sometimes when requesting one lock state, additional lock states
  31365. ** are inserted in between. The locking might fail on one of the later
  31366. ** transitions leaving the lock state different from what it started but
  31367. ** still short of its goal. The following chart shows the allowed
  31368. ** transitions and the inserted intermediate states:
  31369. **
  31370. ** UNLOCKED -> SHARED
  31371. ** SHARED -> RESERVED
  31372. ** SHARED -> (PENDING) -> EXCLUSIVE
  31373. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31374. ** PENDING -> EXCLUSIVE
  31375. **
  31376. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  31377. ** routine to lower a locking level.
  31378. */
  31379. static int proxyLock(sqlite3_file *id, int eFileLock) {
  31380. unixFile *pFile = (unixFile*)id;
  31381. int rc = proxyTakeConch(pFile);
  31382. if( rc==SQLITE_OK ){
  31383. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31384. if( pCtx->conchHeld>0 ){
  31385. unixFile *proxy = pCtx->lockProxy;
  31386. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  31387. pFile->eFileLock = proxy->eFileLock;
  31388. }else{
  31389. /* conchHeld < 0 is lockless */
  31390. }
  31391. }
  31392. return rc;
  31393. }
  31394. /*
  31395. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  31396. ** must be either NO_LOCK or SHARED_LOCK.
  31397. **
  31398. ** If the locking level of the file descriptor is already at or below
  31399. ** the requested locking level, this routine is a no-op.
  31400. */
  31401. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  31402. unixFile *pFile = (unixFile*)id;
  31403. int rc = proxyTakeConch(pFile);
  31404. if( rc==SQLITE_OK ){
  31405. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31406. if( pCtx->conchHeld>0 ){
  31407. unixFile *proxy = pCtx->lockProxy;
  31408. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  31409. pFile->eFileLock = proxy->eFileLock;
  31410. }else{
  31411. /* conchHeld < 0 is lockless */
  31412. }
  31413. }
  31414. return rc;
  31415. }
  31416. /*
  31417. ** Close a file that uses proxy locks.
  31418. */
  31419. static int proxyClose(sqlite3_file *id) {
  31420. if( id ){
  31421. unixFile *pFile = (unixFile*)id;
  31422. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  31423. unixFile *lockProxy = pCtx->lockProxy;
  31424. unixFile *conchFile = pCtx->conchFile;
  31425. int rc = SQLITE_OK;
  31426. if( lockProxy ){
  31427. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  31428. if( rc ) return rc;
  31429. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  31430. if( rc ) return rc;
  31431. sqlite3_free(lockProxy);
  31432. pCtx->lockProxy = 0;
  31433. }
  31434. if( conchFile ){
  31435. if( pCtx->conchHeld ){
  31436. rc = proxyReleaseConch(pFile);
  31437. if( rc ) return rc;
  31438. }
  31439. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  31440. if( rc ) return rc;
  31441. sqlite3_free(conchFile);
  31442. }
  31443. sqlite3DbFree(0, pCtx->lockProxyPath);
  31444. sqlite3_free(pCtx->conchFilePath);
  31445. sqlite3DbFree(0, pCtx->dbPath);
  31446. /* restore the original locking context and pMethod then close it */
  31447. pFile->lockingContext = pCtx->oldLockingContext;
  31448. pFile->pMethod = pCtx->pOldMethod;
  31449. sqlite3_free(pCtx);
  31450. return pFile->pMethod->xClose(id);
  31451. }
  31452. return SQLITE_OK;
  31453. }
  31454. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  31455. /*
  31456. ** The proxy locking style is intended for use with AFP filesystems.
  31457. ** And since AFP is only supported on MacOSX, the proxy locking is also
  31458. ** restricted to MacOSX.
  31459. **
  31460. **
  31461. ******************* End of the proxy lock implementation **********************
  31462. ******************************************************************************/
  31463. /*
  31464. ** Initialize the operating system interface.
  31465. **
  31466. ** This routine registers all VFS implementations for unix-like operating
  31467. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  31468. ** should be the only routines in this file that are visible from other
  31469. ** files.
  31470. **
  31471. ** This routine is called once during SQLite initialization and by a
  31472. ** single thread. The memory allocation and mutex subsystems have not
  31473. ** necessarily been initialized when this routine is called, and so they
  31474. ** should not be used.
  31475. */
  31476. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  31477. /*
  31478. ** The following macro defines an initializer for an sqlite3_vfs object.
  31479. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  31480. ** to the "finder" function. (pAppData is a pointer to a pointer because
  31481. ** silly C90 rules prohibit a void* from being cast to a function pointer
  31482. ** and so we have to go through the intermediate pointer to avoid problems
  31483. ** when compiling with -pedantic-errors on GCC.)
  31484. **
  31485. ** The FINDER parameter to this macro is the name of the pointer to the
  31486. ** finder-function. The finder-function returns a pointer to the
  31487. ** sqlite_io_methods object that implements the desired locking
  31488. ** behaviors. See the division above that contains the IOMETHODS
  31489. ** macro for addition information on finder-functions.
  31490. **
  31491. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  31492. ** object. But the "autolockIoFinder" available on MacOSX does a little
  31493. ** more than that; it looks at the filesystem type that hosts the
  31494. ** database file and tries to choose an locking method appropriate for
  31495. ** that filesystem time.
  31496. */
  31497. #define UNIXVFS(VFSNAME, FINDER) { \
  31498. 3, /* iVersion */ \
  31499. sizeof(unixFile), /* szOsFile */ \
  31500. MAX_PATHNAME, /* mxPathname */ \
  31501. 0, /* pNext */ \
  31502. VFSNAME, /* zName */ \
  31503. (void*)&FINDER, /* pAppData */ \
  31504. unixOpen, /* xOpen */ \
  31505. unixDelete, /* xDelete */ \
  31506. unixAccess, /* xAccess */ \
  31507. unixFullPathname, /* xFullPathname */ \
  31508. unixDlOpen, /* xDlOpen */ \
  31509. unixDlError, /* xDlError */ \
  31510. unixDlSym, /* xDlSym */ \
  31511. unixDlClose, /* xDlClose */ \
  31512. unixRandomness, /* xRandomness */ \
  31513. unixSleep, /* xSleep */ \
  31514. unixCurrentTime, /* xCurrentTime */ \
  31515. unixGetLastError, /* xGetLastError */ \
  31516. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  31517. unixSetSystemCall, /* xSetSystemCall */ \
  31518. unixGetSystemCall, /* xGetSystemCall */ \
  31519. unixNextSystemCall, /* xNextSystemCall */ \
  31520. }
  31521. /*
  31522. ** All default VFSes for unix are contained in the following array.
  31523. **
  31524. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  31525. ** by the SQLite core when the VFS is registered. So the following
  31526. ** array cannot be const.
  31527. */
  31528. static sqlite3_vfs aVfs[] = {
  31529. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31530. UNIXVFS("unix", autolockIoFinder ),
  31531. #elif OS_VXWORKS
  31532. UNIXVFS("unix", vxworksIoFinder ),
  31533. #else
  31534. UNIXVFS("unix", posixIoFinder ),
  31535. #endif
  31536. UNIXVFS("unix-none", nolockIoFinder ),
  31537. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  31538. UNIXVFS("unix-excl", posixIoFinder ),
  31539. #if OS_VXWORKS
  31540. UNIXVFS("unix-namedsem", semIoFinder ),
  31541. #endif
  31542. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  31543. UNIXVFS("unix-posix", posixIoFinder ),
  31544. #endif
  31545. #if SQLITE_ENABLE_LOCKING_STYLE
  31546. UNIXVFS("unix-flock", flockIoFinder ),
  31547. #endif
  31548. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  31549. UNIXVFS("unix-afp", afpIoFinder ),
  31550. UNIXVFS("unix-nfs", nfsIoFinder ),
  31551. UNIXVFS("unix-proxy", proxyIoFinder ),
  31552. #endif
  31553. };
  31554. unsigned int i; /* Loop counter */
  31555. /* Double-check that the aSyscall[] array has been constructed
  31556. ** correctly. See ticket [bb3a86e890c8e96ab] */
  31557. assert( ArraySize(aSyscall)==25 );
  31558. /* Register all VFSes defined in the aVfs[] array */
  31559. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  31560. sqlite3_vfs_register(&aVfs[i], i==0);
  31561. }
  31562. return SQLITE_OK;
  31563. }
  31564. /*
  31565. ** Shutdown the operating system interface.
  31566. **
  31567. ** Some operating systems might need to do some cleanup in this routine,
  31568. ** to release dynamically allocated objects. But not on unix.
  31569. ** This routine is a no-op for unix.
  31570. */
  31571. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  31572. return SQLITE_OK;
  31573. }
  31574. #endif /* SQLITE_OS_UNIX */
  31575. /************** End of os_unix.c *********************************************/
  31576. /************** Begin file os_win.c ******************************************/
  31577. /*
  31578. ** 2004 May 22
  31579. **
  31580. ** The author disclaims copyright to this source code. In place of
  31581. ** a legal notice, here is a blessing:
  31582. **
  31583. ** May you do good and not evil.
  31584. ** May you find forgiveness for yourself and forgive others.
  31585. ** May you share freely, never taking more than you give.
  31586. **
  31587. ******************************************************************************
  31588. **
  31589. ** This file contains code that is specific to Windows.
  31590. */
  31591. /* #include "sqliteInt.h" */
  31592. #if SQLITE_OS_WIN /* This file is used for Windows only */
  31593. /*
  31594. ** Include code that is common to all os_*.c files
  31595. */
  31596. /************** Include os_common.h in the middle of os_win.c ****************/
  31597. /************** Begin file os_common.h ***************************************/
  31598. /*
  31599. ** 2004 May 22
  31600. **
  31601. ** The author disclaims copyright to this source code. In place of
  31602. ** a legal notice, here is a blessing:
  31603. **
  31604. ** May you do good and not evil.
  31605. ** May you find forgiveness for yourself and forgive others.
  31606. ** May you share freely, never taking more than you give.
  31607. **
  31608. ******************************************************************************
  31609. **
  31610. ** This file contains macros and a little bit of code that is common to
  31611. ** all of the platform-specific files (os_*.c) and is #included into those
  31612. ** files.
  31613. **
  31614. ** This file should be #included by the os_*.c files only. It is not a
  31615. ** general purpose header file.
  31616. */
  31617. #ifndef _OS_COMMON_H_
  31618. #define _OS_COMMON_H_
  31619. /*
  31620. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  31621. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  31622. ** switch. The following code should catch this problem at compile-time.
  31623. */
  31624. #ifdef MEMORY_DEBUG
  31625. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  31626. #endif
  31627. /*
  31628. ** Macros for performance tracing. Normally turned off. Only works
  31629. ** on i486 hardware.
  31630. */
  31631. #ifdef SQLITE_PERFORMANCE_TRACE
  31632. /*
  31633. ** hwtime.h contains inline assembler code for implementing
  31634. ** high-performance timing routines.
  31635. */
  31636. /************** Include hwtime.h in the middle of os_common.h ****************/
  31637. /************** Begin file hwtime.h ******************************************/
  31638. /*
  31639. ** 2008 May 27
  31640. **
  31641. ** The author disclaims copyright to this source code. In place of
  31642. ** a legal notice, here is a blessing:
  31643. **
  31644. ** May you do good and not evil.
  31645. ** May you find forgiveness for yourself and forgive others.
  31646. ** May you share freely, never taking more than you give.
  31647. **
  31648. ******************************************************************************
  31649. **
  31650. ** This file contains inline asm code for retrieving "high-performance"
  31651. ** counters for x86 class CPUs.
  31652. */
  31653. #ifndef _HWTIME_H_
  31654. #define _HWTIME_H_
  31655. /*
  31656. ** The following routine only works on pentium-class (or newer) processors.
  31657. ** It uses the RDTSC opcode to read the cycle count value out of the
  31658. ** processor and returns that value. This can be used for high-res
  31659. ** profiling.
  31660. */
  31661. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  31662. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  31663. #if defined(__GNUC__)
  31664. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31665. unsigned int lo, hi;
  31666. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  31667. return (sqlite_uint64)hi << 32 | lo;
  31668. }
  31669. #elif defined(_MSC_VER)
  31670. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  31671. __asm {
  31672. rdtsc
  31673. ret ; return value at EDX:EAX
  31674. }
  31675. }
  31676. #endif
  31677. #elif (defined(__GNUC__) && defined(__x86_64__))
  31678. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31679. unsigned long val;
  31680. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  31681. return val;
  31682. }
  31683. #elif (defined(__GNUC__) && defined(__ppc__))
  31684. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  31685. unsigned long long retval;
  31686. unsigned long junk;
  31687. __asm__ __volatile__ ("\n\
  31688. 1: mftbu %1\n\
  31689. mftb %L0\n\
  31690. mftbu %0\n\
  31691. cmpw %0,%1\n\
  31692. bne 1b"
  31693. : "=r" (retval), "=r" (junk));
  31694. return retval;
  31695. }
  31696. #else
  31697. #error Need implementation of sqlite3Hwtime() for your platform.
  31698. /*
  31699. ** To compile without implementing sqlite3Hwtime() for your platform,
  31700. ** you can remove the above #error and use the following
  31701. ** stub function. You will lose timing support for many
  31702. ** of the debugging and testing utilities, but it should at
  31703. ** least compile and run.
  31704. */
  31705. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  31706. #endif
  31707. #endif /* !defined(_HWTIME_H_) */
  31708. /************** End of hwtime.h **********************************************/
  31709. /************** Continuing where we left off in os_common.h ******************/
  31710. static sqlite_uint64 g_start;
  31711. static sqlite_uint64 g_elapsed;
  31712. #define TIMER_START g_start=sqlite3Hwtime()
  31713. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  31714. #define TIMER_ELAPSED g_elapsed
  31715. #else
  31716. #define TIMER_START
  31717. #define TIMER_END
  31718. #define TIMER_ELAPSED ((sqlite_uint64)0)
  31719. #endif
  31720. /*
  31721. ** If we compile with the SQLITE_TEST macro set, then the following block
  31722. ** of code will give us the ability to simulate a disk I/O error. This
  31723. ** is used for testing the I/O recovery logic.
  31724. */
  31725. #ifdef SQLITE_TEST
  31726. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  31727. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  31728. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  31729. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  31730. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  31731. SQLITE_API int sqlite3_diskfull_pending = 0;
  31732. SQLITE_API int sqlite3_diskfull = 0;
  31733. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  31734. #define SimulateIOError(CODE) \
  31735. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  31736. || sqlite3_io_error_pending-- == 1 ) \
  31737. { local_ioerr(); CODE; }
  31738. static void local_ioerr(){
  31739. IOTRACE(("IOERR\n"));
  31740. sqlite3_io_error_hit++;
  31741. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  31742. }
  31743. #define SimulateDiskfullError(CODE) \
  31744. if( sqlite3_diskfull_pending ){ \
  31745. if( sqlite3_diskfull_pending == 1 ){ \
  31746. local_ioerr(); \
  31747. sqlite3_diskfull = 1; \
  31748. sqlite3_io_error_hit = 1; \
  31749. CODE; \
  31750. }else{ \
  31751. sqlite3_diskfull_pending--; \
  31752. } \
  31753. }
  31754. #else
  31755. #define SimulateIOErrorBenign(X)
  31756. #define SimulateIOError(A)
  31757. #define SimulateDiskfullError(A)
  31758. #endif
  31759. /*
  31760. ** When testing, keep a count of the number of open files.
  31761. */
  31762. #ifdef SQLITE_TEST
  31763. SQLITE_API int sqlite3_open_file_count = 0;
  31764. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  31765. #else
  31766. #define OpenCounter(X)
  31767. #endif
  31768. #endif /* !defined(_OS_COMMON_H_) */
  31769. /************** End of os_common.h *******************************************/
  31770. /************** Continuing where we left off in os_win.c *********************/
  31771. /*
  31772. ** Include the header file for the Windows VFS.
  31773. */
  31774. /* #include "os_win.h" */
  31775. /*
  31776. ** Compiling and using WAL mode requires several APIs that are only
  31777. ** available in Windows platforms based on the NT kernel.
  31778. */
  31779. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  31780. # error "WAL mode requires support from the Windows NT kernel, compile\
  31781. with SQLITE_OMIT_WAL."
  31782. #endif
  31783. #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
  31784. # error "Memory mapped files require support from the Windows NT kernel,\
  31785. compile with SQLITE_MAX_MMAP_SIZE=0."
  31786. #endif
  31787. /*
  31788. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  31789. ** based on the sub-platform)?
  31790. */
  31791. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  31792. # define SQLITE_WIN32_HAS_ANSI
  31793. #endif
  31794. /*
  31795. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  31796. ** based on the sub-platform)?
  31797. */
  31798. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  31799. !defined(SQLITE_WIN32_NO_WIDE)
  31800. # define SQLITE_WIN32_HAS_WIDE
  31801. #endif
  31802. /*
  31803. ** Make sure at least one set of Win32 APIs is available.
  31804. */
  31805. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  31806. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  31807. must be defined."
  31808. #endif
  31809. /*
  31810. ** Define the required Windows SDK version constants if they are not
  31811. ** already available.
  31812. */
  31813. #ifndef NTDDI_WIN8
  31814. # define NTDDI_WIN8 0x06020000
  31815. #endif
  31816. #ifndef NTDDI_WINBLUE
  31817. # define NTDDI_WINBLUE 0x06030000
  31818. #endif
  31819. /*
  31820. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  31821. ** target system. GetVersionEx was first deprecated in Win8.1.
  31822. */
  31823. #ifndef SQLITE_WIN32_GETVERSIONEX
  31824. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  31825. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  31826. # else
  31827. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  31828. # endif
  31829. #endif
  31830. /*
  31831. ** This constant should already be defined (in the "WinDef.h" SDK file).
  31832. */
  31833. #ifndef MAX_PATH
  31834. # define MAX_PATH (260)
  31835. #endif
  31836. /*
  31837. ** Maximum pathname length (in chars) for Win32. This should normally be
  31838. ** MAX_PATH.
  31839. */
  31840. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  31841. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  31842. #endif
  31843. /*
  31844. ** This constant should already be defined (in the "WinNT.h" SDK file).
  31845. */
  31846. #ifndef UNICODE_STRING_MAX_CHARS
  31847. # define UNICODE_STRING_MAX_CHARS (32767)
  31848. #endif
  31849. /*
  31850. ** Maximum pathname length (in chars) for WinNT. This should normally be
  31851. ** UNICODE_STRING_MAX_CHARS.
  31852. */
  31853. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  31854. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  31855. #endif
  31856. /*
  31857. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  31858. ** characters, so we allocate 4 bytes per character assuming worst-case of
  31859. ** 4-bytes-per-character for UTF8.
  31860. */
  31861. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  31862. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  31863. #endif
  31864. /*
  31865. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  31866. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  31867. */
  31868. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  31869. # define SQLITE_WINNT_MAX_PATH_BYTES \
  31870. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  31871. #endif
  31872. /*
  31873. ** Maximum error message length (in chars) for WinRT.
  31874. */
  31875. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  31876. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  31877. #endif
  31878. /*
  31879. ** Returns non-zero if the character should be treated as a directory
  31880. ** separator.
  31881. */
  31882. #ifndef winIsDirSep
  31883. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  31884. #endif
  31885. /*
  31886. ** This macro is used when a local variable is set to a value that is
  31887. ** [sometimes] not used by the code (e.g. via conditional compilation).
  31888. */
  31889. #ifndef UNUSED_VARIABLE_VALUE
  31890. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  31891. #endif
  31892. /*
  31893. ** Returns the character that should be used as the directory separator.
  31894. */
  31895. #ifndef winGetDirSep
  31896. # define winGetDirSep() '\\'
  31897. #endif
  31898. /*
  31899. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  31900. ** mode or memory mapped files (e.g. these APIs are available in the Windows
  31901. ** CE SDK; however, they are not present in the header file)?
  31902. */
  31903. #if SQLITE_WIN32_FILEMAPPING_API && \
  31904. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  31905. /*
  31906. ** Two of the file mapping APIs are different under WinRT. Figure out which
  31907. ** set we need.
  31908. */
  31909. #if SQLITE_OS_WINRT
  31910. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  31911. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  31912. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  31913. #else
  31914. #if defined(SQLITE_WIN32_HAS_ANSI)
  31915. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  31916. DWORD, DWORD, DWORD, LPCSTR);
  31917. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  31918. #if defined(SQLITE_WIN32_HAS_WIDE)
  31919. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  31920. DWORD, DWORD, DWORD, LPCWSTR);
  31921. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  31922. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  31923. #endif /* SQLITE_OS_WINRT */
  31924. /*
  31925. ** These file mapping APIs are common to both Win32 and WinRT.
  31926. */
  31927. WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
  31928. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  31929. #endif /* SQLITE_WIN32_FILEMAPPING_API */
  31930. /*
  31931. ** Some Microsoft compilers lack this definition.
  31932. */
  31933. #ifndef INVALID_FILE_ATTRIBUTES
  31934. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  31935. #endif
  31936. #ifndef FILE_FLAG_MASK
  31937. # define FILE_FLAG_MASK (0xFF3C0000)
  31938. #endif
  31939. #ifndef FILE_ATTRIBUTE_MASK
  31940. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  31941. #endif
  31942. #ifndef SQLITE_OMIT_WAL
  31943. /* Forward references to structures used for WAL */
  31944. typedef struct winShm winShm; /* A connection to shared-memory */
  31945. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  31946. #endif
  31947. /*
  31948. ** WinCE lacks native support for file locking so we have to fake it
  31949. ** with some code of our own.
  31950. */
  31951. #if SQLITE_OS_WINCE
  31952. typedef struct winceLock {
  31953. int nReaders; /* Number of reader locks obtained */
  31954. BOOL bPending; /* Indicates a pending lock has been obtained */
  31955. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  31956. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  31957. } winceLock;
  31958. #endif
  31959. /*
  31960. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  31961. ** portability layer.
  31962. */
  31963. typedef struct winFile winFile;
  31964. struct winFile {
  31965. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  31966. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  31967. HANDLE h; /* Handle for accessing the file */
  31968. u8 locktype; /* Type of lock currently held on this file */
  31969. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  31970. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  31971. DWORD lastErrno; /* The Windows errno from the last I/O error */
  31972. #ifndef SQLITE_OMIT_WAL
  31973. winShm *pShm; /* Instance of shared memory on this file */
  31974. #endif
  31975. const char *zPath; /* Full pathname of this file */
  31976. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  31977. #if SQLITE_OS_WINCE
  31978. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  31979. HANDLE hMutex; /* Mutex used to control access to shared lock */
  31980. HANDLE hShared; /* Shared memory segment used for locking */
  31981. winceLock local; /* Locks obtained by this instance of winFile */
  31982. winceLock *shared; /* Global shared lock memory for the file */
  31983. #endif
  31984. #if SQLITE_MAX_MMAP_SIZE>0
  31985. int nFetchOut; /* Number of outstanding xFetch references */
  31986. HANDLE hMap; /* Handle for accessing memory mapping */
  31987. void *pMapRegion; /* Area memory mapped */
  31988. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  31989. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  31990. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  31991. #endif
  31992. };
  31993. /*
  31994. ** Allowed values for winFile.ctrlFlags
  31995. */
  31996. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  31997. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  31998. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  31999. /*
  32000. * The size of the buffer used by sqlite3_win32_write_debug().
  32001. */
  32002. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  32003. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  32004. #endif
  32005. /*
  32006. * The value used with sqlite3_win32_set_directory() to specify that
  32007. * the data directory should be changed.
  32008. */
  32009. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  32010. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  32011. #endif
  32012. /*
  32013. * The value used with sqlite3_win32_set_directory() to specify that
  32014. * the temporary directory should be changed.
  32015. */
  32016. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  32017. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  32018. #endif
  32019. /*
  32020. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  32021. * various Win32 API heap functions instead of our own.
  32022. */
  32023. #ifdef SQLITE_WIN32_MALLOC
  32024. /*
  32025. * If this is non-zero, an isolated heap will be created by the native Win32
  32026. * allocator subsystem; otherwise, the default process heap will be used. This
  32027. * setting has no effect when compiling for WinRT. By default, this is enabled
  32028. * and an isolated heap will be created to store all allocated data.
  32029. *
  32030. ******************************************************************************
  32031. * WARNING: It is important to note that when this setting is non-zero and the
  32032. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  32033. * function), all data that was allocated using the isolated heap will
  32034. * be freed immediately and any attempt to access any of that freed
  32035. * data will almost certainly result in an immediate access violation.
  32036. ******************************************************************************
  32037. */
  32038. #ifndef SQLITE_WIN32_HEAP_CREATE
  32039. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  32040. #endif
  32041. /*
  32042. * The initial size of the Win32-specific heap. This value may be zero.
  32043. */
  32044. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  32045. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  32046. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  32047. #endif
  32048. /*
  32049. * The maximum size of the Win32-specific heap. This value may be zero.
  32050. */
  32051. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  32052. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  32053. #endif
  32054. /*
  32055. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  32056. * zero for the default behavior.
  32057. */
  32058. #ifndef SQLITE_WIN32_HEAP_FLAGS
  32059. # define SQLITE_WIN32_HEAP_FLAGS (0)
  32060. #endif
  32061. /*
  32062. ** The winMemData structure stores information required by the Win32-specific
  32063. ** sqlite3_mem_methods implementation.
  32064. */
  32065. typedef struct winMemData winMemData;
  32066. struct winMemData {
  32067. #ifndef NDEBUG
  32068. u32 magic1; /* Magic number to detect structure corruption. */
  32069. #endif
  32070. HANDLE hHeap; /* The handle to our heap. */
  32071. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  32072. #ifndef NDEBUG
  32073. u32 magic2; /* Magic number to detect structure corruption. */
  32074. #endif
  32075. };
  32076. #ifndef NDEBUG
  32077. #define WINMEM_MAGIC1 0x42b2830b
  32078. #define WINMEM_MAGIC2 0xbd4d7cf4
  32079. #endif
  32080. static struct winMemData win_mem_data = {
  32081. #ifndef NDEBUG
  32082. WINMEM_MAGIC1,
  32083. #endif
  32084. NULL, FALSE
  32085. #ifndef NDEBUG
  32086. ,WINMEM_MAGIC2
  32087. #endif
  32088. };
  32089. #ifndef NDEBUG
  32090. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  32091. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  32092. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  32093. #else
  32094. #define winMemAssertMagic()
  32095. #endif
  32096. #define winMemGetDataPtr() &win_mem_data
  32097. #define winMemGetHeap() win_mem_data.hHeap
  32098. #define winMemGetOwned() win_mem_data.bOwned
  32099. static void *winMemMalloc(int nBytes);
  32100. static void winMemFree(void *pPrior);
  32101. static void *winMemRealloc(void *pPrior, int nBytes);
  32102. static int winMemSize(void *p);
  32103. static int winMemRoundup(int n);
  32104. static int winMemInit(void *pAppData);
  32105. static void winMemShutdown(void *pAppData);
  32106. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  32107. #endif /* SQLITE_WIN32_MALLOC */
  32108. /*
  32109. ** The following variable is (normally) set once and never changes
  32110. ** thereafter. It records whether the operating system is Win9x
  32111. ** or WinNT.
  32112. **
  32113. ** 0: Operating system unknown.
  32114. ** 1: Operating system is Win9x.
  32115. ** 2: Operating system is WinNT.
  32116. **
  32117. ** In order to facilitate testing on a WinNT system, the test fixture
  32118. ** can manually set this value to 1 to emulate Win98 behavior.
  32119. */
  32120. #ifdef SQLITE_TEST
  32121. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  32122. #else
  32123. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  32124. #endif
  32125. #ifndef SYSCALL
  32126. # define SYSCALL sqlite3_syscall_ptr
  32127. #endif
  32128. /*
  32129. ** This function is not available on Windows CE or WinRT.
  32130. */
  32131. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  32132. # define osAreFileApisANSI() 1
  32133. #endif
  32134. /*
  32135. ** Many system calls are accessed through pointer-to-functions so that
  32136. ** they may be overridden at runtime to facilitate fault injection during
  32137. ** testing and sandboxing. The following array holds the names and pointers
  32138. ** to all overrideable system calls.
  32139. */
  32140. static struct win_syscall {
  32141. const char *zName; /* Name of the system call */
  32142. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  32143. sqlite3_syscall_ptr pDefault; /* Default value */
  32144. } aSyscall[] = {
  32145. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  32146. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  32147. #else
  32148. { "AreFileApisANSI", (SYSCALL)0, 0 },
  32149. #endif
  32150. #ifndef osAreFileApisANSI
  32151. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  32152. #endif
  32153. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  32154. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  32155. #else
  32156. { "CharLowerW", (SYSCALL)0, 0 },
  32157. #endif
  32158. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  32159. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  32160. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  32161. #else
  32162. { "CharUpperW", (SYSCALL)0, 0 },
  32163. #endif
  32164. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  32165. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  32166. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  32167. #if defined(SQLITE_WIN32_HAS_ANSI)
  32168. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  32169. #else
  32170. { "CreateFileA", (SYSCALL)0, 0 },
  32171. #endif
  32172. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  32173. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  32174. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32175. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  32176. #else
  32177. { "CreateFileW", (SYSCALL)0, 0 },
  32178. #endif
  32179. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  32180. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  32181. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  32182. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  32183. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  32184. #else
  32185. { "CreateFileMappingA", (SYSCALL)0, 0 },
  32186. #endif
  32187. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  32188. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  32189. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  32190. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  32191. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  32192. #else
  32193. { "CreateFileMappingW", (SYSCALL)0, 0 },
  32194. #endif
  32195. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  32196. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  32197. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32198. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  32199. #else
  32200. { "CreateMutexW", (SYSCALL)0, 0 },
  32201. #endif
  32202. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  32203. LPCWSTR))aSyscall[8].pCurrent)
  32204. #if defined(SQLITE_WIN32_HAS_ANSI)
  32205. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  32206. #else
  32207. { "DeleteFileA", (SYSCALL)0, 0 },
  32208. #endif
  32209. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  32210. #if defined(SQLITE_WIN32_HAS_WIDE)
  32211. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  32212. #else
  32213. { "DeleteFileW", (SYSCALL)0, 0 },
  32214. #endif
  32215. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  32216. #if SQLITE_OS_WINCE
  32217. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  32218. #else
  32219. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  32220. #endif
  32221. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  32222. LPFILETIME))aSyscall[11].pCurrent)
  32223. #if SQLITE_OS_WINCE
  32224. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  32225. #else
  32226. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  32227. #endif
  32228. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  32229. LPSYSTEMTIME))aSyscall[12].pCurrent)
  32230. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  32231. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  32232. #if defined(SQLITE_WIN32_HAS_ANSI)
  32233. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  32234. #else
  32235. { "FormatMessageA", (SYSCALL)0, 0 },
  32236. #endif
  32237. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  32238. DWORD,va_list*))aSyscall[14].pCurrent)
  32239. #if defined(SQLITE_WIN32_HAS_WIDE)
  32240. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  32241. #else
  32242. { "FormatMessageW", (SYSCALL)0, 0 },
  32243. #endif
  32244. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  32245. DWORD,va_list*))aSyscall[15].pCurrent)
  32246. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32247. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  32248. #else
  32249. { "FreeLibrary", (SYSCALL)0, 0 },
  32250. #endif
  32251. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  32252. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  32253. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  32254. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  32255. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  32256. #else
  32257. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  32258. #endif
  32259. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  32260. LPDWORD))aSyscall[18].pCurrent)
  32261. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32262. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  32263. #else
  32264. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  32265. #endif
  32266. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  32267. LPDWORD))aSyscall[19].pCurrent)
  32268. #if defined(SQLITE_WIN32_HAS_ANSI)
  32269. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  32270. #else
  32271. { "GetFileAttributesA", (SYSCALL)0, 0 },
  32272. #endif
  32273. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  32274. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32275. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  32276. #else
  32277. { "GetFileAttributesW", (SYSCALL)0, 0 },
  32278. #endif
  32279. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  32280. #if defined(SQLITE_WIN32_HAS_WIDE)
  32281. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  32282. #else
  32283. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  32284. #endif
  32285. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  32286. LPVOID))aSyscall[22].pCurrent)
  32287. #if !SQLITE_OS_WINRT
  32288. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  32289. #else
  32290. { "GetFileSize", (SYSCALL)0, 0 },
  32291. #endif
  32292. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  32293. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  32294. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  32295. #else
  32296. { "GetFullPathNameA", (SYSCALL)0, 0 },
  32297. #endif
  32298. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  32299. LPSTR*))aSyscall[24].pCurrent)
  32300. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32301. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  32302. #else
  32303. { "GetFullPathNameW", (SYSCALL)0, 0 },
  32304. #endif
  32305. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  32306. LPWSTR*))aSyscall[25].pCurrent)
  32307. { "GetLastError", (SYSCALL)GetLastError, 0 },
  32308. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  32309. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32310. #if SQLITE_OS_WINCE
  32311. /* The GetProcAddressA() routine is only available on Windows CE. */
  32312. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  32313. #else
  32314. /* All other Windows platforms expect GetProcAddress() to take
  32315. ** an ANSI string regardless of the _UNICODE setting */
  32316. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  32317. #endif
  32318. #else
  32319. { "GetProcAddressA", (SYSCALL)0, 0 },
  32320. #endif
  32321. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  32322. LPCSTR))aSyscall[27].pCurrent)
  32323. #if !SQLITE_OS_WINRT
  32324. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  32325. #else
  32326. { "GetSystemInfo", (SYSCALL)0, 0 },
  32327. #endif
  32328. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  32329. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  32330. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  32331. #if !SQLITE_OS_WINCE
  32332. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  32333. #else
  32334. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  32335. #endif
  32336. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  32337. LPFILETIME))aSyscall[30].pCurrent)
  32338. #if defined(SQLITE_WIN32_HAS_ANSI)
  32339. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  32340. #else
  32341. { "GetTempPathA", (SYSCALL)0, 0 },
  32342. #endif
  32343. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  32344. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  32345. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  32346. #else
  32347. { "GetTempPathW", (SYSCALL)0, 0 },
  32348. #endif
  32349. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  32350. #if !SQLITE_OS_WINRT
  32351. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  32352. #else
  32353. { "GetTickCount", (SYSCALL)0, 0 },
  32354. #endif
  32355. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  32356. #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
  32357. SQLITE_WIN32_GETVERSIONEX
  32358. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  32359. #else
  32360. { "GetVersionExA", (SYSCALL)0, 0 },
  32361. #endif
  32362. #define osGetVersionExA ((BOOL(WINAPI*)( \
  32363. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  32364. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  32365. defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  32366. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  32367. #else
  32368. { "GetVersionExW", (SYSCALL)0, 0 },
  32369. #endif
  32370. #define osGetVersionExW ((BOOL(WINAPI*)( \
  32371. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  32372. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  32373. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  32374. SIZE_T))aSyscall[36].pCurrent)
  32375. #if !SQLITE_OS_WINRT
  32376. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  32377. #else
  32378. { "HeapCreate", (SYSCALL)0, 0 },
  32379. #endif
  32380. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  32381. SIZE_T))aSyscall[37].pCurrent)
  32382. #if !SQLITE_OS_WINRT
  32383. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  32384. #else
  32385. { "HeapDestroy", (SYSCALL)0, 0 },
  32386. #endif
  32387. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  32388. { "HeapFree", (SYSCALL)HeapFree, 0 },
  32389. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  32390. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  32391. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  32392. SIZE_T))aSyscall[40].pCurrent)
  32393. { "HeapSize", (SYSCALL)HeapSize, 0 },
  32394. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  32395. LPCVOID))aSyscall[41].pCurrent)
  32396. #if !SQLITE_OS_WINRT
  32397. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  32398. #else
  32399. { "HeapValidate", (SYSCALL)0, 0 },
  32400. #endif
  32401. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  32402. LPCVOID))aSyscall[42].pCurrent)
  32403. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  32404. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  32405. #else
  32406. { "HeapCompact", (SYSCALL)0, 0 },
  32407. #endif
  32408. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  32409. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32410. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  32411. #else
  32412. { "LoadLibraryA", (SYSCALL)0, 0 },
  32413. #endif
  32414. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  32415. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  32416. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32417. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  32418. #else
  32419. { "LoadLibraryW", (SYSCALL)0, 0 },
  32420. #endif
  32421. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  32422. #if !SQLITE_OS_WINRT
  32423. { "LocalFree", (SYSCALL)LocalFree, 0 },
  32424. #else
  32425. { "LocalFree", (SYSCALL)0, 0 },
  32426. #endif
  32427. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  32428. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  32429. { "LockFile", (SYSCALL)LockFile, 0 },
  32430. #else
  32431. { "LockFile", (SYSCALL)0, 0 },
  32432. #endif
  32433. #ifndef osLockFile
  32434. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  32435. DWORD))aSyscall[47].pCurrent)
  32436. #endif
  32437. #if !SQLITE_OS_WINCE
  32438. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  32439. #else
  32440. { "LockFileEx", (SYSCALL)0, 0 },
  32441. #endif
  32442. #ifndef osLockFileEx
  32443. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  32444. LPOVERLAPPED))aSyscall[48].pCurrent)
  32445. #endif
  32446. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
  32447. (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
  32448. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  32449. #else
  32450. { "MapViewOfFile", (SYSCALL)0, 0 },
  32451. #endif
  32452. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  32453. SIZE_T))aSyscall[49].pCurrent)
  32454. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  32455. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  32456. int))aSyscall[50].pCurrent)
  32457. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  32458. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  32459. LARGE_INTEGER*))aSyscall[51].pCurrent)
  32460. { "ReadFile", (SYSCALL)ReadFile, 0 },
  32461. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  32462. LPOVERLAPPED))aSyscall[52].pCurrent)
  32463. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  32464. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  32465. #if !SQLITE_OS_WINRT
  32466. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  32467. #else
  32468. { "SetFilePointer", (SYSCALL)0, 0 },
  32469. #endif
  32470. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  32471. DWORD))aSyscall[54].pCurrent)
  32472. #if !SQLITE_OS_WINRT
  32473. { "Sleep", (SYSCALL)Sleep, 0 },
  32474. #else
  32475. { "Sleep", (SYSCALL)0, 0 },
  32476. #endif
  32477. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  32478. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  32479. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  32480. LPFILETIME))aSyscall[56].pCurrent)
  32481. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  32482. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  32483. #else
  32484. { "UnlockFile", (SYSCALL)0, 0 },
  32485. #endif
  32486. #ifndef osUnlockFile
  32487. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  32488. DWORD))aSyscall[57].pCurrent)
  32489. #endif
  32490. #if !SQLITE_OS_WINCE
  32491. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  32492. #else
  32493. { "UnlockFileEx", (SYSCALL)0, 0 },
  32494. #endif
  32495. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  32496. LPOVERLAPPED))aSyscall[58].pCurrent)
  32497. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  32498. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  32499. #else
  32500. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  32501. #endif
  32502. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  32503. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  32504. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  32505. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  32506. { "WriteFile", (SYSCALL)WriteFile, 0 },
  32507. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  32508. LPOVERLAPPED))aSyscall[61].pCurrent)
  32509. #if SQLITE_OS_WINRT
  32510. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  32511. #else
  32512. { "CreateEventExW", (SYSCALL)0, 0 },
  32513. #endif
  32514. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  32515. DWORD,DWORD))aSyscall[62].pCurrent)
  32516. #if !SQLITE_OS_WINRT
  32517. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  32518. #else
  32519. { "WaitForSingleObject", (SYSCALL)0, 0 },
  32520. #endif
  32521. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  32522. DWORD))aSyscall[63].pCurrent)
  32523. #if !SQLITE_OS_WINCE
  32524. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  32525. #else
  32526. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  32527. #endif
  32528. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  32529. BOOL))aSyscall[64].pCurrent)
  32530. #if SQLITE_OS_WINRT
  32531. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  32532. #else
  32533. { "SetFilePointerEx", (SYSCALL)0, 0 },
  32534. #endif
  32535. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  32536. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  32537. #if SQLITE_OS_WINRT
  32538. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  32539. #else
  32540. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  32541. #endif
  32542. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  32543. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  32544. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  32545. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  32546. #else
  32547. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  32548. #endif
  32549. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  32550. SIZE_T))aSyscall[67].pCurrent)
  32551. #if SQLITE_OS_WINRT
  32552. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  32553. #else
  32554. { "CreateFile2", (SYSCALL)0, 0 },
  32555. #endif
  32556. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  32557. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  32558. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  32559. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  32560. #else
  32561. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  32562. #endif
  32563. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  32564. DWORD))aSyscall[69].pCurrent)
  32565. #if SQLITE_OS_WINRT
  32566. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  32567. #else
  32568. { "GetTickCount64", (SYSCALL)0, 0 },
  32569. #endif
  32570. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  32571. #if SQLITE_OS_WINRT
  32572. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  32573. #else
  32574. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  32575. #endif
  32576. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  32577. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  32578. #if defined(SQLITE_WIN32_HAS_ANSI)
  32579. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  32580. #else
  32581. { "OutputDebugStringA", (SYSCALL)0, 0 },
  32582. #endif
  32583. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  32584. #if defined(SQLITE_WIN32_HAS_WIDE)
  32585. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  32586. #else
  32587. { "OutputDebugStringW", (SYSCALL)0, 0 },
  32588. #endif
  32589. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  32590. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  32591. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  32592. #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
  32593. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  32594. #else
  32595. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  32596. #endif
  32597. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  32598. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  32599. /*
  32600. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  32601. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  32602. ** So do not try to make this is into a redefinable interface.
  32603. */
  32604. #if defined(InterlockedCompareExchange)
  32605. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  32606. #define osInterlockedCompareExchange InterlockedCompareExchange
  32607. #else
  32608. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  32609. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  32610. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  32611. #endif /* defined(InterlockedCompareExchange) */
  32612. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  32613. { "UuidCreate", (SYSCALL)UuidCreate, 0 },
  32614. #else
  32615. { "UuidCreate", (SYSCALL)0, 0 },
  32616. #endif
  32617. #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
  32618. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  32619. { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
  32620. #else
  32621. { "UuidCreateSequential", (SYSCALL)0, 0 },
  32622. #endif
  32623. #define osUuidCreateSequential \
  32624. ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
  32625. #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
  32626. { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
  32627. #else
  32628. { "FlushViewOfFile", (SYSCALL)0, 0 },
  32629. #endif
  32630. #define osFlushViewOfFile \
  32631. ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
  32632. }; /* End of the overrideable system calls */
  32633. /*
  32634. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  32635. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  32636. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  32637. ** system call named zName.
  32638. */
  32639. static int winSetSystemCall(
  32640. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  32641. const char *zName, /* Name of system call to override */
  32642. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  32643. ){
  32644. unsigned int i;
  32645. int rc = SQLITE_NOTFOUND;
  32646. UNUSED_PARAMETER(pNotUsed);
  32647. if( zName==0 ){
  32648. /* If no zName is given, restore all system calls to their default
  32649. ** settings and return NULL
  32650. */
  32651. rc = SQLITE_OK;
  32652. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32653. if( aSyscall[i].pDefault ){
  32654. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  32655. }
  32656. }
  32657. }else{
  32658. /* If zName is specified, operate on only the one system call
  32659. ** specified.
  32660. */
  32661. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32662. if( strcmp(zName, aSyscall[i].zName)==0 ){
  32663. if( aSyscall[i].pDefault==0 ){
  32664. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  32665. }
  32666. rc = SQLITE_OK;
  32667. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  32668. aSyscall[i].pCurrent = pNewFunc;
  32669. break;
  32670. }
  32671. }
  32672. }
  32673. return rc;
  32674. }
  32675. /*
  32676. ** Return the value of a system call. Return NULL if zName is not a
  32677. ** recognized system call name. NULL is also returned if the system call
  32678. ** is currently undefined.
  32679. */
  32680. static sqlite3_syscall_ptr winGetSystemCall(
  32681. sqlite3_vfs *pNotUsed,
  32682. const char *zName
  32683. ){
  32684. unsigned int i;
  32685. UNUSED_PARAMETER(pNotUsed);
  32686. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  32687. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  32688. }
  32689. return 0;
  32690. }
  32691. /*
  32692. ** Return the name of the first system call after zName. If zName==NULL
  32693. ** then return the name of the first system call. Return NULL if zName
  32694. ** is the last system call or if zName is not the name of a valid
  32695. ** system call.
  32696. */
  32697. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  32698. int i = -1;
  32699. UNUSED_PARAMETER(p);
  32700. if( zName ){
  32701. for(i=0; i<ArraySize(aSyscall)-1; i++){
  32702. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  32703. }
  32704. }
  32705. for(i++; i<ArraySize(aSyscall); i++){
  32706. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  32707. }
  32708. return 0;
  32709. }
  32710. #ifdef SQLITE_WIN32_MALLOC
  32711. /*
  32712. ** If a Win32 native heap has been configured, this function will attempt to
  32713. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  32714. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  32715. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  32716. ** largest committed free block in the heap, in bytes.
  32717. */
  32718. SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
  32719. int rc = SQLITE_OK;
  32720. UINT nLargest = 0;
  32721. HANDLE hHeap;
  32722. winMemAssertMagic();
  32723. hHeap = winMemGetHeap();
  32724. assert( hHeap!=0 );
  32725. assert( hHeap!=INVALID_HANDLE_VALUE );
  32726. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32727. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  32728. #endif
  32729. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  32730. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  32731. DWORD lastErrno = osGetLastError();
  32732. if( lastErrno==NO_ERROR ){
  32733. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  32734. (void*)hHeap);
  32735. rc = SQLITE_NOMEM;
  32736. }else{
  32737. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  32738. osGetLastError(), (void*)hHeap);
  32739. rc = SQLITE_ERROR;
  32740. }
  32741. }
  32742. #else
  32743. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  32744. (void*)hHeap);
  32745. rc = SQLITE_NOTFOUND;
  32746. #endif
  32747. if( pnLargest ) *pnLargest = nLargest;
  32748. return rc;
  32749. }
  32750. /*
  32751. ** If a Win32 native heap has been configured, this function will attempt to
  32752. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  32753. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  32754. ** be returned and no changes will be made to the Win32 native heap.
  32755. */
  32756. SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
  32757. int rc;
  32758. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  32759. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  32760. MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
  32761. MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
  32762. sqlite3_mutex_enter(pMaster);
  32763. sqlite3_mutex_enter(pMem);
  32764. winMemAssertMagic();
  32765. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  32766. /*
  32767. ** At this point, there should be no outstanding memory allocations on
  32768. ** the heap. Also, since both the master and memsys locks are currently
  32769. ** being held by us, no other function (i.e. from another thread) should
  32770. ** be able to even access the heap. Attempt to destroy and recreate our
  32771. ** isolated Win32 native heap now.
  32772. */
  32773. assert( winMemGetHeap()!=NULL );
  32774. assert( winMemGetOwned() );
  32775. assert( sqlite3_memory_used()==0 );
  32776. winMemShutdown(winMemGetDataPtr());
  32777. assert( winMemGetHeap()==NULL );
  32778. assert( !winMemGetOwned() );
  32779. assert( sqlite3_memory_used()==0 );
  32780. rc = winMemInit(winMemGetDataPtr());
  32781. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  32782. assert( rc!=SQLITE_OK || winMemGetOwned() );
  32783. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  32784. }else{
  32785. /*
  32786. ** The Win32 native heap cannot be modified because it may be in use.
  32787. */
  32788. rc = SQLITE_BUSY;
  32789. }
  32790. sqlite3_mutex_leave(pMem);
  32791. sqlite3_mutex_leave(pMaster);
  32792. return rc;
  32793. }
  32794. #endif /* SQLITE_WIN32_MALLOC */
  32795. /*
  32796. ** This function outputs the specified (ANSI) string to the Win32 debugger
  32797. ** (if available).
  32798. */
  32799. SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  32800. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  32801. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  32802. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  32803. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  32804. #if defined(SQLITE_WIN32_HAS_ANSI)
  32805. if( nMin>0 ){
  32806. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  32807. memcpy(zDbgBuf, zBuf, nMin);
  32808. osOutputDebugStringA(zDbgBuf);
  32809. }else{
  32810. osOutputDebugStringA(zBuf);
  32811. }
  32812. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32813. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  32814. if ( osMultiByteToWideChar(
  32815. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  32816. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  32817. return;
  32818. }
  32819. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  32820. #else
  32821. if( nMin>0 ){
  32822. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  32823. memcpy(zDbgBuf, zBuf, nMin);
  32824. fprintf(stderr, "%s", zDbgBuf);
  32825. }else{
  32826. fprintf(stderr, "%s", zBuf);
  32827. }
  32828. #endif
  32829. }
  32830. /*
  32831. ** The following routine suspends the current thread for at least ms
  32832. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  32833. */
  32834. #if SQLITE_OS_WINRT
  32835. static HANDLE sleepObj = NULL;
  32836. #endif
  32837. SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
  32838. #if SQLITE_OS_WINRT
  32839. if ( sleepObj==NULL ){
  32840. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  32841. SYNCHRONIZE);
  32842. }
  32843. assert( sleepObj!=NULL );
  32844. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  32845. #else
  32846. osSleep(milliseconds);
  32847. #endif
  32848. }
  32849. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  32850. SQLITE_THREADSAFE>0
  32851. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  32852. DWORD rc;
  32853. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  32854. TRUE))==WAIT_IO_COMPLETION ){}
  32855. return rc;
  32856. }
  32857. #endif
  32858. /*
  32859. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  32860. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  32861. **
  32862. ** Here is an interesting observation: Win95, Win98, and WinME lack
  32863. ** the LockFileEx() API. But we can still statically link against that
  32864. ** API as long as we don't call it when running Win95/98/ME. A call to
  32865. ** this routine is used to determine if the host is Win95/98/ME or
  32866. ** WinNT/2K/XP so that we will know whether or not we can safely call
  32867. ** the LockFileEx() API.
  32868. */
  32869. #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
  32870. # define osIsNT() (1)
  32871. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  32872. # define osIsNT() (1)
  32873. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  32874. # define osIsNT() (0)
  32875. #else
  32876. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  32877. #endif
  32878. /*
  32879. ** This function determines if the machine is running a version of Windows
  32880. ** based on the NT kernel.
  32881. */
  32882. SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
  32883. #if SQLITE_OS_WINRT
  32884. /*
  32885. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  32886. ** kernel.
  32887. */
  32888. return 1;
  32889. #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  32890. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  32891. #if defined(SQLITE_WIN32_HAS_ANSI)
  32892. OSVERSIONINFOA sInfo;
  32893. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  32894. osGetVersionExA(&sInfo);
  32895. osInterlockedCompareExchange(&sqlite3_os_type,
  32896. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  32897. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32898. OSVERSIONINFOW sInfo;
  32899. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  32900. osGetVersionExW(&sInfo);
  32901. osInterlockedCompareExchange(&sqlite3_os_type,
  32902. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  32903. #endif
  32904. }
  32905. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  32906. #elif SQLITE_TEST
  32907. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  32908. #else
  32909. /*
  32910. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  32911. ** deprecated are always assumed to be based on the NT kernel.
  32912. */
  32913. return 1;
  32914. #endif
  32915. }
  32916. #ifdef SQLITE_WIN32_MALLOC
  32917. /*
  32918. ** Allocate nBytes of memory.
  32919. */
  32920. static void *winMemMalloc(int nBytes){
  32921. HANDLE hHeap;
  32922. void *p;
  32923. winMemAssertMagic();
  32924. hHeap = winMemGetHeap();
  32925. assert( hHeap!=0 );
  32926. assert( hHeap!=INVALID_HANDLE_VALUE );
  32927. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32928. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  32929. #endif
  32930. assert( nBytes>=0 );
  32931. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  32932. if( !p ){
  32933. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  32934. nBytes, osGetLastError(), (void*)hHeap);
  32935. }
  32936. return p;
  32937. }
  32938. /*
  32939. ** Free memory.
  32940. */
  32941. static void winMemFree(void *pPrior){
  32942. HANDLE hHeap;
  32943. winMemAssertMagic();
  32944. hHeap = winMemGetHeap();
  32945. assert( hHeap!=0 );
  32946. assert( hHeap!=INVALID_HANDLE_VALUE );
  32947. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32948. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  32949. #endif
  32950. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  32951. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  32952. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  32953. pPrior, osGetLastError(), (void*)hHeap);
  32954. }
  32955. }
  32956. /*
  32957. ** Change the size of an existing memory allocation
  32958. */
  32959. static void *winMemRealloc(void *pPrior, int nBytes){
  32960. HANDLE hHeap;
  32961. void *p;
  32962. winMemAssertMagic();
  32963. hHeap = winMemGetHeap();
  32964. assert( hHeap!=0 );
  32965. assert( hHeap!=INVALID_HANDLE_VALUE );
  32966. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32967. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  32968. #endif
  32969. assert( nBytes>=0 );
  32970. if( !pPrior ){
  32971. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  32972. }else{
  32973. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  32974. }
  32975. if( !p ){
  32976. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  32977. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  32978. (void*)hHeap);
  32979. }
  32980. return p;
  32981. }
  32982. /*
  32983. ** Return the size of an outstanding allocation, in bytes.
  32984. */
  32985. static int winMemSize(void *p){
  32986. HANDLE hHeap;
  32987. SIZE_T n;
  32988. winMemAssertMagic();
  32989. hHeap = winMemGetHeap();
  32990. assert( hHeap!=0 );
  32991. assert( hHeap!=INVALID_HANDLE_VALUE );
  32992. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  32993. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  32994. #endif
  32995. if( !p ) return 0;
  32996. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  32997. if( n==(SIZE_T)-1 ){
  32998. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  32999. p, osGetLastError(), (void*)hHeap);
  33000. return 0;
  33001. }
  33002. return (int)n;
  33003. }
  33004. /*
  33005. ** Round up a request size to the next valid allocation size.
  33006. */
  33007. static int winMemRoundup(int n){
  33008. return n;
  33009. }
  33010. /*
  33011. ** Initialize this module.
  33012. */
  33013. static int winMemInit(void *pAppData){
  33014. winMemData *pWinMemData = (winMemData *)pAppData;
  33015. if( !pWinMemData ) return SQLITE_ERROR;
  33016. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  33017. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  33018. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  33019. if( !pWinMemData->hHeap ){
  33020. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  33021. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  33022. if( dwMaximumSize==0 ){
  33023. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  33024. }else if( dwInitialSize>dwMaximumSize ){
  33025. dwInitialSize = dwMaximumSize;
  33026. }
  33027. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  33028. dwInitialSize, dwMaximumSize);
  33029. if( !pWinMemData->hHeap ){
  33030. sqlite3_log(SQLITE_NOMEM,
  33031. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  33032. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  33033. dwMaximumSize);
  33034. return SQLITE_NOMEM;
  33035. }
  33036. pWinMemData->bOwned = TRUE;
  33037. assert( pWinMemData->bOwned );
  33038. }
  33039. #else
  33040. pWinMemData->hHeap = osGetProcessHeap();
  33041. if( !pWinMemData->hHeap ){
  33042. sqlite3_log(SQLITE_NOMEM,
  33043. "failed to GetProcessHeap (%lu)", osGetLastError());
  33044. return SQLITE_NOMEM;
  33045. }
  33046. pWinMemData->bOwned = FALSE;
  33047. assert( !pWinMemData->bOwned );
  33048. #endif
  33049. assert( pWinMemData->hHeap!=0 );
  33050. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  33051. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33052. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33053. #endif
  33054. return SQLITE_OK;
  33055. }
  33056. /*
  33057. ** Deinitialize this module.
  33058. */
  33059. static void winMemShutdown(void *pAppData){
  33060. winMemData *pWinMemData = (winMemData *)pAppData;
  33061. if( !pWinMemData ) return;
  33062. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  33063. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  33064. if( pWinMemData->hHeap ){
  33065. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  33066. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  33067. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  33068. #endif
  33069. if( pWinMemData->bOwned ){
  33070. if( !osHeapDestroy(pWinMemData->hHeap) ){
  33071. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  33072. osGetLastError(), (void*)pWinMemData->hHeap);
  33073. }
  33074. pWinMemData->bOwned = FALSE;
  33075. }
  33076. pWinMemData->hHeap = NULL;
  33077. }
  33078. }
  33079. /*
  33080. ** Populate the low-level memory allocation function pointers in
  33081. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  33082. ** arguments specify the block of memory to manage.
  33083. **
  33084. ** This routine is only called by sqlite3_config(), and therefore
  33085. ** is not required to be threadsafe (it is not).
  33086. */
  33087. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  33088. static const sqlite3_mem_methods winMemMethods = {
  33089. winMemMalloc,
  33090. winMemFree,
  33091. winMemRealloc,
  33092. winMemSize,
  33093. winMemRoundup,
  33094. winMemInit,
  33095. winMemShutdown,
  33096. &win_mem_data
  33097. };
  33098. return &winMemMethods;
  33099. }
  33100. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  33101. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  33102. }
  33103. #endif /* SQLITE_WIN32_MALLOC */
  33104. /*
  33105. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  33106. **
  33107. ** Space to hold the returned string is obtained from malloc.
  33108. */
  33109. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  33110. int nChar;
  33111. LPWSTR zWideFilename;
  33112. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  33113. if( nChar==0 ){
  33114. return 0;
  33115. }
  33116. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  33117. if( zWideFilename==0 ){
  33118. return 0;
  33119. }
  33120. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  33121. nChar);
  33122. if( nChar==0 ){
  33123. sqlite3_free(zWideFilename);
  33124. zWideFilename = 0;
  33125. }
  33126. return zWideFilename;
  33127. }
  33128. /*
  33129. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  33130. ** obtained from sqlite3_malloc().
  33131. */
  33132. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  33133. int nByte;
  33134. char *zFilename;
  33135. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  33136. if( nByte == 0 ){
  33137. return 0;
  33138. }
  33139. zFilename = sqlite3MallocZero( nByte );
  33140. if( zFilename==0 ){
  33141. return 0;
  33142. }
  33143. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  33144. 0, 0);
  33145. if( nByte == 0 ){
  33146. sqlite3_free(zFilename);
  33147. zFilename = 0;
  33148. }
  33149. return zFilename;
  33150. }
  33151. /*
  33152. ** Convert an ANSI string to Microsoft Unicode, based on the
  33153. ** current codepage settings for file apis.
  33154. **
  33155. ** Space to hold the returned string is obtained
  33156. ** from sqlite3_malloc.
  33157. */
  33158. static LPWSTR winMbcsToUnicode(const char *zFilename){
  33159. int nByte;
  33160. LPWSTR zMbcsFilename;
  33161. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  33162. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  33163. 0)*sizeof(WCHAR);
  33164. if( nByte==0 ){
  33165. return 0;
  33166. }
  33167. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  33168. if( zMbcsFilename==0 ){
  33169. return 0;
  33170. }
  33171. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  33172. nByte);
  33173. if( nByte==0 ){
  33174. sqlite3_free(zMbcsFilename);
  33175. zMbcsFilename = 0;
  33176. }
  33177. return zMbcsFilename;
  33178. }
  33179. /*
  33180. ** Convert Microsoft Unicode to multi-byte character string, based on the
  33181. ** user's ANSI codepage.
  33182. **
  33183. ** Space to hold the returned string is obtained from
  33184. ** sqlite3_malloc().
  33185. */
  33186. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  33187. int nByte;
  33188. char *zFilename;
  33189. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  33190. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  33191. if( nByte == 0 ){
  33192. return 0;
  33193. }
  33194. zFilename = sqlite3MallocZero( nByte );
  33195. if( zFilename==0 ){
  33196. return 0;
  33197. }
  33198. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  33199. nByte, 0, 0);
  33200. if( nByte == 0 ){
  33201. sqlite3_free(zFilename);
  33202. zFilename = 0;
  33203. }
  33204. return zFilename;
  33205. }
  33206. /*
  33207. ** Convert multibyte character string to UTF-8. Space to hold the
  33208. ** returned string is obtained from sqlite3_malloc().
  33209. */
  33210. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  33211. char *zFilenameUtf8;
  33212. LPWSTR zTmpWide;
  33213. zTmpWide = winMbcsToUnicode(zFilename);
  33214. if( zTmpWide==0 ){
  33215. return 0;
  33216. }
  33217. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  33218. sqlite3_free(zTmpWide);
  33219. return zFilenameUtf8;
  33220. }
  33221. /*
  33222. ** Convert UTF-8 to multibyte character string. Space to hold the
  33223. ** returned string is obtained from sqlite3_malloc().
  33224. */
  33225. SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  33226. char *zFilenameMbcs;
  33227. LPWSTR zTmpWide;
  33228. zTmpWide = winUtf8ToUnicode(zFilename);
  33229. if( zTmpWide==0 ){
  33230. return 0;
  33231. }
  33232. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  33233. sqlite3_free(zTmpWide);
  33234. return zFilenameMbcs;
  33235. }
  33236. /*
  33237. ** This function sets the data directory or the temporary directory based on
  33238. ** the provided arguments. The type argument must be 1 in order to set the
  33239. ** data directory or 2 in order to set the temporary directory. The zValue
  33240. ** argument is the name of the directory to use. The return value will be
  33241. ** SQLITE_OK if successful.
  33242. */
  33243. SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  33244. char **ppDirectory = 0;
  33245. #ifndef SQLITE_OMIT_AUTOINIT
  33246. int rc = sqlite3_initialize();
  33247. if( rc ) return rc;
  33248. #endif
  33249. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  33250. ppDirectory = &sqlite3_data_directory;
  33251. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  33252. ppDirectory = &sqlite3_temp_directory;
  33253. }
  33254. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  33255. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  33256. );
  33257. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  33258. if( ppDirectory ){
  33259. char *zValueUtf8 = 0;
  33260. if( zValue && zValue[0] ){
  33261. zValueUtf8 = winUnicodeToUtf8(zValue);
  33262. if ( zValueUtf8==0 ){
  33263. return SQLITE_NOMEM;
  33264. }
  33265. }
  33266. sqlite3_free(*ppDirectory);
  33267. *ppDirectory = zValueUtf8;
  33268. return SQLITE_OK;
  33269. }
  33270. return SQLITE_ERROR;
  33271. }
  33272. /*
  33273. ** The return value of winGetLastErrorMsg
  33274. ** is zero if the error message fits in the buffer, or non-zero
  33275. ** otherwise (if the message was truncated).
  33276. */
  33277. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  33278. /* FormatMessage returns 0 on failure. Otherwise it
  33279. ** returns the number of TCHARs written to the output
  33280. ** buffer, excluding the terminating null char.
  33281. */
  33282. DWORD dwLen = 0;
  33283. char *zOut = 0;
  33284. if( osIsNT() ){
  33285. #if SQLITE_OS_WINRT
  33286. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  33287. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  33288. FORMAT_MESSAGE_IGNORE_INSERTS,
  33289. NULL,
  33290. lastErrno,
  33291. 0,
  33292. zTempWide,
  33293. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  33294. 0);
  33295. #else
  33296. LPWSTR zTempWide = NULL;
  33297. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  33298. FORMAT_MESSAGE_FROM_SYSTEM |
  33299. FORMAT_MESSAGE_IGNORE_INSERTS,
  33300. NULL,
  33301. lastErrno,
  33302. 0,
  33303. (LPWSTR) &zTempWide,
  33304. 0,
  33305. 0);
  33306. #endif
  33307. if( dwLen > 0 ){
  33308. /* allocate a buffer and convert to UTF8 */
  33309. sqlite3BeginBenignMalloc();
  33310. zOut = winUnicodeToUtf8(zTempWide);
  33311. sqlite3EndBenignMalloc();
  33312. #if !SQLITE_OS_WINRT
  33313. /* free the system buffer allocated by FormatMessage */
  33314. osLocalFree(zTempWide);
  33315. #endif
  33316. }
  33317. }
  33318. #ifdef SQLITE_WIN32_HAS_ANSI
  33319. else{
  33320. char *zTemp = NULL;
  33321. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  33322. FORMAT_MESSAGE_FROM_SYSTEM |
  33323. FORMAT_MESSAGE_IGNORE_INSERTS,
  33324. NULL,
  33325. lastErrno,
  33326. 0,
  33327. (LPSTR) &zTemp,
  33328. 0,
  33329. 0);
  33330. if( dwLen > 0 ){
  33331. /* allocate a buffer and convert to UTF8 */
  33332. sqlite3BeginBenignMalloc();
  33333. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  33334. sqlite3EndBenignMalloc();
  33335. /* free the system buffer allocated by FormatMessage */
  33336. osLocalFree(zTemp);
  33337. }
  33338. }
  33339. #endif
  33340. if( 0 == dwLen ){
  33341. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  33342. }else{
  33343. /* copy a maximum of nBuf chars to output buffer */
  33344. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  33345. /* free the UTF8 buffer */
  33346. sqlite3_free(zOut);
  33347. }
  33348. return 0;
  33349. }
  33350. /*
  33351. **
  33352. ** This function - winLogErrorAtLine() - is only ever called via the macro
  33353. ** winLogError().
  33354. **
  33355. ** This routine is invoked after an error occurs in an OS function.
  33356. ** It logs a message using sqlite3_log() containing the current value of
  33357. ** error code and, if possible, the human-readable equivalent from
  33358. ** FormatMessage.
  33359. **
  33360. ** The first argument passed to the macro should be the error code that
  33361. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  33362. ** The two subsequent arguments should be the name of the OS function that
  33363. ** failed and the associated file-system path, if any.
  33364. */
  33365. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  33366. static int winLogErrorAtLine(
  33367. int errcode, /* SQLite error code */
  33368. DWORD lastErrno, /* Win32 last error */
  33369. const char *zFunc, /* Name of OS function that failed */
  33370. const char *zPath, /* File path associated with error */
  33371. int iLine /* Source line number where error occurred */
  33372. ){
  33373. char zMsg[500]; /* Human readable error text */
  33374. int i; /* Loop counter */
  33375. zMsg[0] = 0;
  33376. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  33377. assert( errcode!=SQLITE_OK );
  33378. if( zPath==0 ) zPath = "";
  33379. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  33380. zMsg[i] = 0;
  33381. sqlite3_log(errcode,
  33382. "os_win.c:%d: (%lu) %s(%s) - %s",
  33383. iLine, lastErrno, zFunc, zPath, zMsg
  33384. );
  33385. return errcode;
  33386. }
  33387. /*
  33388. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  33389. ** will be retried following a locking error - probably caused by
  33390. ** antivirus software. Also the initial delay before the first retry.
  33391. ** The delay increases linearly with each retry.
  33392. */
  33393. #ifndef SQLITE_WIN32_IOERR_RETRY
  33394. # define SQLITE_WIN32_IOERR_RETRY 10
  33395. #endif
  33396. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  33397. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  33398. #endif
  33399. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  33400. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  33401. /*
  33402. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  33403. ** error code obtained via GetLastError() is eligible to be retried. It
  33404. ** must accept the error code DWORD as its only argument and should return
  33405. ** non-zero if the error code is transient in nature and the operation
  33406. ** responsible for generating the original error might succeed upon being
  33407. ** retried. The argument to this macro should be a variable.
  33408. **
  33409. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  33410. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  33411. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  33412. ** may be used to include additional error codes in the set that should
  33413. ** result in the failing I/O operation being retried by the caller. If
  33414. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  33415. ** identical to those of the "winIoerrCanRetry1" macro.
  33416. */
  33417. #if !defined(winIoerrCanRetry1)
  33418. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  33419. ((a)==ERROR_SHARING_VIOLATION) || \
  33420. ((a)==ERROR_LOCK_VIOLATION) || \
  33421. ((a)==ERROR_DEV_NOT_EXIST) || \
  33422. ((a)==ERROR_NETNAME_DELETED) || \
  33423. ((a)==ERROR_SEM_TIMEOUT) || \
  33424. ((a)==ERROR_NETWORK_UNREACHABLE))
  33425. #endif
  33426. /*
  33427. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  33428. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  33429. ** to give up with an error.
  33430. */
  33431. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  33432. DWORD e = osGetLastError();
  33433. if( *pnRetry>=winIoerrRetry ){
  33434. if( pError ){
  33435. *pError = e;
  33436. }
  33437. return 0;
  33438. }
  33439. if( winIoerrCanRetry1(e) ){
  33440. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  33441. ++*pnRetry;
  33442. return 1;
  33443. }
  33444. #if defined(winIoerrCanRetry2)
  33445. else if( winIoerrCanRetry2(e) ){
  33446. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  33447. ++*pnRetry;
  33448. return 1;
  33449. }
  33450. #endif
  33451. if( pError ){
  33452. *pError = e;
  33453. }
  33454. return 0;
  33455. }
  33456. /*
  33457. ** Log a I/O error retry episode.
  33458. */
  33459. static void winLogIoerr(int nRetry, int lineno){
  33460. if( nRetry ){
  33461. sqlite3_log(SQLITE_NOTICE,
  33462. "delayed %dms for lock/sharing conflict at line %d",
  33463. winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
  33464. );
  33465. }
  33466. }
  33467. #if SQLITE_OS_WINCE
  33468. /*************************************************************************
  33469. ** This section contains code for WinCE only.
  33470. */
  33471. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  33472. /*
  33473. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  33474. ** create a substitute.
  33475. */
  33476. /* #include <time.h> */
  33477. struct tm *__cdecl localtime(const time_t *t)
  33478. {
  33479. static struct tm y;
  33480. FILETIME uTm, lTm;
  33481. SYSTEMTIME pTm;
  33482. sqlite3_int64 t64;
  33483. t64 = *t;
  33484. t64 = (t64 + 11644473600)*10000000;
  33485. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  33486. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  33487. osFileTimeToLocalFileTime(&uTm,&lTm);
  33488. osFileTimeToSystemTime(&lTm,&pTm);
  33489. y.tm_year = pTm.wYear - 1900;
  33490. y.tm_mon = pTm.wMonth - 1;
  33491. y.tm_wday = pTm.wDayOfWeek;
  33492. y.tm_mday = pTm.wDay;
  33493. y.tm_hour = pTm.wHour;
  33494. y.tm_min = pTm.wMinute;
  33495. y.tm_sec = pTm.wSecond;
  33496. return &y;
  33497. }
  33498. #endif
  33499. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  33500. /*
  33501. ** Acquire a lock on the handle h
  33502. */
  33503. static void winceMutexAcquire(HANDLE h){
  33504. DWORD dwErr;
  33505. do {
  33506. dwErr = osWaitForSingleObject(h, INFINITE);
  33507. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  33508. }
  33509. /*
  33510. ** Release a lock acquired by winceMutexAcquire()
  33511. */
  33512. #define winceMutexRelease(h) ReleaseMutex(h)
  33513. /*
  33514. ** Create the mutex and shared memory used for locking in the file
  33515. ** descriptor pFile
  33516. */
  33517. static int winceCreateLock(const char *zFilename, winFile *pFile){
  33518. LPWSTR zTok;
  33519. LPWSTR zName;
  33520. DWORD lastErrno;
  33521. BOOL bLogged = FALSE;
  33522. BOOL bInit = TRUE;
  33523. zName = winUtf8ToUnicode(zFilename);
  33524. if( zName==0 ){
  33525. /* out of memory */
  33526. return SQLITE_IOERR_NOMEM;
  33527. }
  33528. /* Initialize the local lockdata */
  33529. memset(&pFile->local, 0, sizeof(pFile->local));
  33530. /* Replace the backslashes from the filename and lowercase it
  33531. ** to derive a mutex name. */
  33532. zTok = osCharLowerW(zName);
  33533. for (;*zTok;zTok++){
  33534. if (*zTok == '\\') *zTok = '_';
  33535. }
  33536. /* Create/open the named mutex */
  33537. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  33538. if (!pFile->hMutex){
  33539. pFile->lastErrno = osGetLastError();
  33540. sqlite3_free(zName);
  33541. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  33542. "winceCreateLock1", zFilename);
  33543. }
  33544. /* Acquire the mutex before continuing */
  33545. winceMutexAcquire(pFile->hMutex);
  33546. /* Since the names of named mutexes, semaphores, file mappings etc are
  33547. ** case-sensitive, take advantage of that by uppercasing the mutex name
  33548. ** and using that as the shared filemapping name.
  33549. */
  33550. osCharUpperW(zName);
  33551. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  33552. PAGE_READWRITE, 0, sizeof(winceLock),
  33553. zName);
  33554. /* Set a flag that indicates we're the first to create the memory so it
  33555. ** must be zero-initialized */
  33556. lastErrno = osGetLastError();
  33557. if (lastErrno == ERROR_ALREADY_EXISTS){
  33558. bInit = FALSE;
  33559. }
  33560. sqlite3_free(zName);
  33561. /* If we succeeded in making the shared memory handle, map it. */
  33562. if( pFile->hShared ){
  33563. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  33564. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  33565. /* If mapping failed, close the shared memory handle and erase it */
  33566. if( !pFile->shared ){
  33567. pFile->lastErrno = osGetLastError();
  33568. winLogError(SQLITE_IOERR, pFile->lastErrno,
  33569. "winceCreateLock2", zFilename);
  33570. bLogged = TRUE;
  33571. osCloseHandle(pFile->hShared);
  33572. pFile->hShared = NULL;
  33573. }
  33574. }
  33575. /* If shared memory could not be created, then close the mutex and fail */
  33576. if( pFile->hShared==NULL ){
  33577. if( !bLogged ){
  33578. pFile->lastErrno = lastErrno;
  33579. winLogError(SQLITE_IOERR, pFile->lastErrno,
  33580. "winceCreateLock3", zFilename);
  33581. bLogged = TRUE;
  33582. }
  33583. winceMutexRelease(pFile->hMutex);
  33584. osCloseHandle(pFile->hMutex);
  33585. pFile->hMutex = NULL;
  33586. return SQLITE_IOERR;
  33587. }
  33588. /* Initialize the shared memory if we're supposed to */
  33589. if( bInit ){
  33590. memset(pFile->shared, 0, sizeof(winceLock));
  33591. }
  33592. winceMutexRelease(pFile->hMutex);
  33593. return SQLITE_OK;
  33594. }
  33595. /*
  33596. ** Destroy the part of winFile that deals with wince locks
  33597. */
  33598. static void winceDestroyLock(winFile *pFile){
  33599. if (pFile->hMutex){
  33600. /* Acquire the mutex */
  33601. winceMutexAcquire(pFile->hMutex);
  33602. /* The following blocks should probably assert in debug mode, but they
  33603. are to cleanup in case any locks remained open */
  33604. if (pFile->local.nReaders){
  33605. pFile->shared->nReaders --;
  33606. }
  33607. if (pFile->local.bReserved){
  33608. pFile->shared->bReserved = FALSE;
  33609. }
  33610. if (pFile->local.bPending){
  33611. pFile->shared->bPending = FALSE;
  33612. }
  33613. if (pFile->local.bExclusive){
  33614. pFile->shared->bExclusive = FALSE;
  33615. }
  33616. /* De-reference and close our copy of the shared memory handle */
  33617. osUnmapViewOfFile(pFile->shared);
  33618. osCloseHandle(pFile->hShared);
  33619. /* Done with the mutex */
  33620. winceMutexRelease(pFile->hMutex);
  33621. osCloseHandle(pFile->hMutex);
  33622. pFile->hMutex = NULL;
  33623. }
  33624. }
  33625. /*
  33626. ** An implementation of the LockFile() API of Windows for CE
  33627. */
  33628. static BOOL winceLockFile(
  33629. LPHANDLE phFile,
  33630. DWORD dwFileOffsetLow,
  33631. DWORD dwFileOffsetHigh,
  33632. DWORD nNumberOfBytesToLockLow,
  33633. DWORD nNumberOfBytesToLockHigh
  33634. ){
  33635. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  33636. BOOL bReturn = FALSE;
  33637. UNUSED_PARAMETER(dwFileOffsetHigh);
  33638. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  33639. if (!pFile->hMutex) return TRUE;
  33640. winceMutexAcquire(pFile->hMutex);
  33641. /* Wanting an exclusive lock? */
  33642. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  33643. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  33644. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  33645. pFile->shared->bExclusive = TRUE;
  33646. pFile->local.bExclusive = TRUE;
  33647. bReturn = TRUE;
  33648. }
  33649. }
  33650. /* Want a read-only lock? */
  33651. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  33652. nNumberOfBytesToLockLow == 1){
  33653. if (pFile->shared->bExclusive == 0){
  33654. pFile->local.nReaders ++;
  33655. if (pFile->local.nReaders == 1){
  33656. pFile->shared->nReaders ++;
  33657. }
  33658. bReturn = TRUE;
  33659. }
  33660. }
  33661. /* Want a pending lock? */
  33662. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  33663. && nNumberOfBytesToLockLow == 1){
  33664. /* If no pending lock has been acquired, then acquire it */
  33665. if (pFile->shared->bPending == 0) {
  33666. pFile->shared->bPending = TRUE;
  33667. pFile->local.bPending = TRUE;
  33668. bReturn = TRUE;
  33669. }
  33670. }
  33671. /* Want a reserved lock? */
  33672. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  33673. && nNumberOfBytesToLockLow == 1){
  33674. if (pFile->shared->bReserved == 0) {
  33675. pFile->shared->bReserved = TRUE;
  33676. pFile->local.bReserved = TRUE;
  33677. bReturn = TRUE;
  33678. }
  33679. }
  33680. winceMutexRelease(pFile->hMutex);
  33681. return bReturn;
  33682. }
  33683. /*
  33684. ** An implementation of the UnlockFile API of Windows for CE
  33685. */
  33686. static BOOL winceUnlockFile(
  33687. LPHANDLE phFile,
  33688. DWORD dwFileOffsetLow,
  33689. DWORD dwFileOffsetHigh,
  33690. DWORD nNumberOfBytesToUnlockLow,
  33691. DWORD nNumberOfBytesToUnlockHigh
  33692. ){
  33693. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  33694. BOOL bReturn = FALSE;
  33695. UNUSED_PARAMETER(dwFileOffsetHigh);
  33696. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  33697. if (!pFile->hMutex) return TRUE;
  33698. winceMutexAcquire(pFile->hMutex);
  33699. /* Releasing a reader lock or an exclusive lock */
  33700. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  33701. /* Did we have an exclusive lock? */
  33702. if (pFile->local.bExclusive){
  33703. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  33704. pFile->local.bExclusive = FALSE;
  33705. pFile->shared->bExclusive = FALSE;
  33706. bReturn = TRUE;
  33707. }
  33708. /* Did we just have a reader lock? */
  33709. else if (pFile->local.nReaders){
  33710. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  33711. || nNumberOfBytesToUnlockLow == 1);
  33712. pFile->local.nReaders --;
  33713. if (pFile->local.nReaders == 0)
  33714. {
  33715. pFile->shared->nReaders --;
  33716. }
  33717. bReturn = TRUE;
  33718. }
  33719. }
  33720. /* Releasing a pending lock */
  33721. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  33722. && nNumberOfBytesToUnlockLow == 1){
  33723. if (pFile->local.bPending){
  33724. pFile->local.bPending = FALSE;
  33725. pFile->shared->bPending = FALSE;
  33726. bReturn = TRUE;
  33727. }
  33728. }
  33729. /* Releasing a reserved lock */
  33730. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  33731. && nNumberOfBytesToUnlockLow == 1){
  33732. if (pFile->local.bReserved) {
  33733. pFile->local.bReserved = FALSE;
  33734. pFile->shared->bReserved = FALSE;
  33735. bReturn = TRUE;
  33736. }
  33737. }
  33738. winceMutexRelease(pFile->hMutex);
  33739. return bReturn;
  33740. }
  33741. /*
  33742. ** End of the special code for wince
  33743. *****************************************************************************/
  33744. #endif /* SQLITE_OS_WINCE */
  33745. /*
  33746. ** Lock a file region.
  33747. */
  33748. static BOOL winLockFile(
  33749. LPHANDLE phFile,
  33750. DWORD flags,
  33751. DWORD offsetLow,
  33752. DWORD offsetHigh,
  33753. DWORD numBytesLow,
  33754. DWORD numBytesHigh
  33755. ){
  33756. #if SQLITE_OS_WINCE
  33757. /*
  33758. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  33759. ** API LockFile.
  33760. */
  33761. return winceLockFile(phFile, offsetLow, offsetHigh,
  33762. numBytesLow, numBytesHigh);
  33763. #else
  33764. if( osIsNT() ){
  33765. OVERLAPPED ovlp;
  33766. memset(&ovlp, 0, sizeof(OVERLAPPED));
  33767. ovlp.Offset = offsetLow;
  33768. ovlp.OffsetHigh = offsetHigh;
  33769. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  33770. }else{
  33771. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  33772. numBytesHigh);
  33773. }
  33774. #endif
  33775. }
  33776. /*
  33777. ** Unlock a file region.
  33778. */
  33779. static BOOL winUnlockFile(
  33780. LPHANDLE phFile,
  33781. DWORD offsetLow,
  33782. DWORD offsetHigh,
  33783. DWORD numBytesLow,
  33784. DWORD numBytesHigh
  33785. ){
  33786. #if SQLITE_OS_WINCE
  33787. /*
  33788. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  33789. ** API UnlockFile.
  33790. */
  33791. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  33792. numBytesLow, numBytesHigh);
  33793. #else
  33794. if( osIsNT() ){
  33795. OVERLAPPED ovlp;
  33796. memset(&ovlp, 0, sizeof(OVERLAPPED));
  33797. ovlp.Offset = offsetLow;
  33798. ovlp.OffsetHigh = offsetHigh;
  33799. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  33800. }else{
  33801. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  33802. numBytesHigh);
  33803. }
  33804. #endif
  33805. }
  33806. /*****************************************************************************
  33807. ** The next group of routines implement the I/O methods specified
  33808. ** by the sqlite3_io_methods object.
  33809. ******************************************************************************/
  33810. /*
  33811. ** Some Microsoft compilers lack this definition.
  33812. */
  33813. #ifndef INVALID_SET_FILE_POINTER
  33814. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  33815. #endif
  33816. /*
  33817. ** Move the current position of the file handle passed as the first
  33818. ** argument to offset iOffset within the file. If successful, return 0.
  33819. ** Otherwise, set pFile->lastErrno and return non-zero.
  33820. */
  33821. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  33822. #if !SQLITE_OS_WINRT
  33823. LONG upperBits; /* Most sig. 32 bits of new offset */
  33824. LONG lowerBits; /* Least sig. 32 bits of new offset */
  33825. DWORD dwRet; /* Value returned by SetFilePointer() */
  33826. DWORD lastErrno; /* Value returned by GetLastError() */
  33827. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  33828. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  33829. lowerBits = (LONG)(iOffset & 0xffffffff);
  33830. /* API oddity: If successful, SetFilePointer() returns a dword
  33831. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  33832. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  33833. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  33834. ** whether an error has actually occurred, it is also necessary to call
  33835. ** GetLastError().
  33836. */
  33837. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  33838. if( (dwRet==INVALID_SET_FILE_POINTER
  33839. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  33840. pFile->lastErrno = lastErrno;
  33841. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  33842. "winSeekFile", pFile->zPath);
  33843. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  33844. return 1;
  33845. }
  33846. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  33847. return 0;
  33848. #else
  33849. /*
  33850. ** Same as above, except that this implementation works for WinRT.
  33851. */
  33852. LARGE_INTEGER x; /* The new offset */
  33853. BOOL bRet; /* Value returned by SetFilePointerEx() */
  33854. x.QuadPart = iOffset;
  33855. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  33856. if(!bRet){
  33857. pFile->lastErrno = osGetLastError();
  33858. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  33859. "winSeekFile", pFile->zPath);
  33860. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  33861. return 1;
  33862. }
  33863. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  33864. return 0;
  33865. #endif
  33866. }
  33867. #if SQLITE_MAX_MMAP_SIZE>0
  33868. /* Forward references to VFS helper methods used for memory mapped files */
  33869. static int winMapfile(winFile*, sqlite3_int64);
  33870. static int winUnmapfile(winFile*);
  33871. #endif
  33872. /*
  33873. ** Close a file.
  33874. **
  33875. ** It is reported that an attempt to close a handle might sometimes
  33876. ** fail. This is a very unreasonable result, but Windows is notorious
  33877. ** for being unreasonable so I do not doubt that it might happen. If
  33878. ** the close fails, we pause for 100 milliseconds and try again. As
  33879. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  33880. ** giving up and returning an error.
  33881. */
  33882. #define MX_CLOSE_ATTEMPT 3
  33883. static int winClose(sqlite3_file *id){
  33884. int rc, cnt = 0;
  33885. winFile *pFile = (winFile*)id;
  33886. assert( id!=0 );
  33887. #ifndef SQLITE_OMIT_WAL
  33888. assert( pFile->pShm==0 );
  33889. #endif
  33890. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  33891. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
  33892. osGetCurrentProcessId(), pFile, pFile->h));
  33893. #if SQLITE_MAX_MMAP_SIZE>0
  33894. winUnmapfile(pFile);
  33895. #endif
  33896. do{
  33897. rc = osCloseHandle(pFile->h);
  33898. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  33899. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  33900. #if SQLITE_OS_WINCE
  33901. #define WINCE_DELETION_ATTEMPTS 3
  33902. winceDestroyLock(pFile);
  33903. if( pFile->zDeleteOnClose ){
  33904. int cnt = 0;
  33905. while(
  33906. osDeleteFileW(pFile->zDeleteOnClose)==0
  33907. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  33908. && cnt++ < WINCE_DELETION_ATTEMPTS
  33909. ){
  33910. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  33911. }
  33912. sqlite3_free(pFile->zDeleteOnClose);
  33913. }
  33914. #endif
  33915. if( rc ){
  33916. pFile->h = NULL;
  33917. }
  33918. OpenCounter(-1);
  33919. OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  33920. osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
  33921. return rc ? SQLITE_OK
  33922. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  33923. "winClose", pFile->zPath);
  33924. }
  33925. /*
  33926. ** Read data from a file into a buffer. Return SQLITE_OK if all
  33927. ** bytes were read successfully and SQLITE_IOERR if anything goes
  33928. ** wrong.
  33929. */
  33930. static int winRead(
  33931. sqlite3_file *id, /* File to read from */
  33932. void *pBuf, /* Write content into this buffer */
  33933. int amt, /* Number of bytes to read */
  33934. sqlite3_int64 offset /* Begin reading at this offset */
  33935. ){
  33936. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  33937. OVERLAPPED overlapped; /* The offset for ReadFile. */
  33938. #endif
  33939. winFile *pFile = (winFile*)id; /* file handle */
  33940. DWORD nRead; /* Number of bytes actually read from file */
  33941. int nRetry = 0; /* Number of retrys */
  33942. assert( id!=0 );
  33943. assert( amt>0 );
  33944. assert( offset>=0 );
  33945. SimulateIOError(return SQLITE_IOERR_READ);
  33946. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  33947. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  33948. pFile->h, pBuf, amt, offset, pFile->locktype));
  33949. #if SQLITE_MAX_MMAP_SIZE>0
  33950. /* Deal with as much of this read request as possible by transfering
  33951. ** data from the memory mapping using memcpy(). */
  33952. if( offset<pFile->mmapSize ){
  33953. if( offset+amt <= pFile->mmapSize ){
  33954. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  33955. OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33956. osGetCurrentProcessId(), pFile, pFile->h));
  33957. return SQLITE_OK;
  33958. }else{
  33959. int nCopy = (int)(pFile->mmapSize - offset);
  33960. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  33961. pBuf = &((u8 *)pBuf)[nCopy];
  33962. amt -= nCopy;
  33963. offset += nCopy;
  33964. }
  33965. }
  33966. #endif
  33967. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  33968. if( winSeekFile(pFile, offset) ){
  33969. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  33970. osGetCurrentProcessId(), pFile, pFile->h));
  33971. return SQLITE_FULL;
  33972. }
  33973. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  33974. #else
  33975. memset(&overlapped, 0, sizeof(OVERLAPPED));
  33976. overlapped.Offset = (LONG)(offset & 0xffffffff);
  33977. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  33978. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  33979. osGetLastError()!=ERROR_HANDLE_EOF ){
  33980. #endif
  33981. DWORD lastErrno;
  33982. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  33983. pFile->lastErrno = lastErrno;
  33984. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
  33985. osGetCurrentProcessId(), pFile, pFile->h));
  33986. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  33987. "winRead", pFile->zPath);
  33988. }
  33989. winLogIoerr(nRetry, __LINE__);
  33990. if( nRead<(DWORD)amt ){
  33991. /* Unread parts of the buffer must be zero-filled */
  33992. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  33993. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
  33994. osGetCurrentProcessId(), pFile, pFile->h));
  33995. return SQLITE_IOERR_SHORT_READ;
  33996. }
  33997. OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  33998. osGetCurrentProcessId(), pFile, pFile->h));
  33999. return SQLITE_OK;
  34000. }
  34001. /*
  34002. ** Write data from a buffer into a file. Return SQLITE_OK on success
  34003. ** or some other error code on failure.
  34004. */
  34005. static int winWrite(
  34006. sqlite3_file *id, /* File to write into */
  34007. const void *pBuf, /* The bytes to be written */
  34008. int amt, /* Number of bytes to write */
  34009. sqlite3_int64 offset /* Offset into the file to begin writing at */
  34010. ){
  34011. int rc = 0; /* True if error has occurred, else false */
  34012. winFile *pFile = (winFile*)id; /* File handle */
  34013. int nRetry = 0; /* Number of retries */
  34014. assert( amt>0 );
  34015. assert( pFile );
  34016. SimulateIOError(return SQLITE_IOERR_WRITE);
  34017. SimulateDiskfullError(return SQLITE_FULL);
  34018. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
  34019. "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
  34020. pFile->h, pBuf, amt, offset, pFile->locktype));
  34021. #if SQLITE_MAX_MMAP_SIZE>0
  34022. /* Deal with as much of this write request as possible by transfering
  34023. ** data from the memory mapping using memcpy(). */
  34024. if( offset<pFile->mmapSize ){
  34025. if( offset+amt <= pFile->mmapSize ){
  34026. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  34027. OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34028. osGetCurrentProcessId(), pFile, pFile->h));
  34029. return SQLITE_OK;
  34030. }else{
  34031. int nCopy = (int)(pFile->mmapSize - offset);
  34032. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  34033. pBuf = &((u8 *)pBuf)[nCopy];
  34034. amt -= nCopy;
  34035. offset += nCopy;
  34036. }
  34037. }
  34038. #endif
  34039. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  34040. rc = winSeekFile(pFile, offset);
  34041. if( rc==0 ){
  34042. #else
  34043. {
  34044. #endif
  34045. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34046. OVERLAPPED overlapped; /* The offset for WriteFile. */
  34047. #endif
  34048. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  34049. int nRem = amt; /* Number of bytes yet to be written */
  34050. DWORD nWrite; /* Bytes written by each WriteFile() call */
  34051. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  34052. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34053. memset(&overlapped, 0, sizeof(OVERLAPPED));
  34054. overlapped.Offset = (LONG)(offset & 0xffffffff);
  34055. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  34056. #endif
  34057. while( nRem>0 ){
  34058. #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
  34059. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  34060. #else
  34061. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  34062. #endif
  34063. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  34064. break;
  34065. }
  34066. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  34067. if( nWrite==0 || nWrite>(DWORD)nRem ){
  34068. lastErrno = osGetLastError();
  34069. break;
  34070. }
  34071. #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
  34072. offset += nWrite;
  34073. overlapped.Offset = (LONG)(offset & 0xffffffff);
  34074. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  34075. #endif
  34076. aRem += nWrite;
  34077. nRem -= nWrite;
  34078. }
  34079. if( nRem>0 ){
  34080. pFile->lastErrno = lastErrno;
  34081. rc = 1;
  34082. }
  34083. }
  34084. if( rc ){
  34085. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  34086. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  34087. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
  34088. osGetCurrentProcessId(), pFile, pFile->h));
  34089. return winLogError(SQLITE_FULL, pFile->lastErrno,
  34090. "winWrite1", pFile->zPath);
  34091. }
  34092. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
  34093. osGetCurrentProcessId(), pFile, pFile->h));
  34094. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  34095. "winWrite2", pFile->zPath);
  34096. }else{
  34097. winLogIoerr(nRetry, __LINE__);
  34098. }
  34099. OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34100. osGetCurrentProcessId(), pFile, pFile->h));
  34101. return SQLITE_OK;
  34102. }
  34103. /*
  34104. ** Truncate an open file to a specified size
  34105. */
  34106. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  34107. winFile *pFile = (winFile*)id; /* File handle object */
  34108. int rc = SQLITE_OK; /* Return code for this function */
  34109. DWORD lastErrno;
  34110. assert( pFile );
  34111. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  34112. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
  34113. osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
  34114. /* If the user has configured a chunk-size for this file, truncate the
  34115. ** file so that it consists of an integer number of chunks (i.e. the
  34116. ** actual file size after the operation may be larger than the requested
  34117. ** size).
  34118. */
  34119. if( pFile->szChunk>0 ){
  34120. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  34121. }
  34122. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  34123. if( winSeekFile(pFile, nByte) ){
  34124. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  34125. "winTruncate1", pFile->zPath);
  34126. }else if( 0==osSetEndOfFile(pFile->h) &&
  34127. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  34128. pFile->lastErrno = lastErrno;
  34129. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  34130. "winTruncate2", pFile->zPath);
  34131. }
  34132. #if SQLITE_MAX_MMAP_SIZE>0
  34133. /* If the file was truncated to a size smaller than the currently
  34134. ** mapped region, reduce the effective mapping size as well. SQLite will
  34135. ** use read() and write() to access data beyond this point from now on.
  34136. */
  34137. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  34138. pFile->mmapSize = nByte;
  34139. }
  34140. #endif
  34141. OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
  34142. osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
  34143. return rc;
  34144. }
  34145. #ifdef SQLITE_TEST
  34146. /*
  34147. ** Count the number of fullsyncs and normal syncs. This is used to test
  34148. ** that syncs and fullsyncs are occuring at the right times.
  34149. */
  34150. SQLITE_API int sqlite3_sync_count = 0;
  34151. SQLITE_API int sqlite3_fullsync_count = 0;
  34152. #endif
  34153. /*
  34154. ** Make sure all writes to a particular file are committed to disk.
  34155. */
  34156. static int winSync(sqlite3_file *id, int flags){
  34157. #ifndef SQLITE_NO_SYNC
  34158. /*
  34159. ** Used only when SQLITE_NO_SYNC is not defined.
  34160. */
  34161. BOOL rc;
  34162. #endif
  34163. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  34164. defined(SQLITE_HAVE_OS_TRACE)
  34165. /*
  34166. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  34167. ** OSTRACE() macros.
  34168. */
  34169. winFile *pFile = (winFile*)id;
  34170. #else
  34171. UNUSED_PARAMETER(id);
  34172. #endif
  34173. assert( pFile );
  34174. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  34175. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  34176. || (flags&0x0F)==SQLITE_SYNC_FULL
  34177. );
  34178. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  34179. ** line is to test that doing so does not cause any problems.
  34180. */
  34181. SimulateDiskfullError( return SQLITE_FULL );
  34182. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
  34183. osGetCurrentProcessId(), pFile, pFile->h, flags,
  34184. pFile->locktype));
  34185. #ifndef SQLITE_TEST
  34186. UNUSED_PARAMETER(flags);
  34187. #else
  34188. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  34189. sqlite3_fullsync_count++;
  34190. }
  34191. sqlite3_sync_count++;
  34192. #endif
  34193. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  34194. ** no-op
  34195. */
  34196. #ifdef SQLITE_NO_SYNC
  34197. OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34198. osGetCurrentProcessId(), pFile, pFile->h));
  34199. return SQLITE_OK;
  34200. #else
  34201. #if SQLITE_MAX_MMAP_SIZE>0
  34202. if( pFile->pMapRegion ){
  34203. if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
  34204. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  34205. "rc=SQLITE_OK\n", osGetCurrentProcessId(),
  34206. pFile, pFile->pMapRegion));
  34207. }else{
  34208. pFile->lastErrno = osGetLastError();
  34209. OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
  34210. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
  34211. pFile, pFile->pMapRegion));
  34212. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34213. "winSync1", pFile->zPath);
  34214. }
  34215. }
  34216. #endif
  34217. rc = osFlushFileBuffers(pFile->h);
  34218. SimulateIOError( rc=FALSE );
  34219. if( rc ){
  34220. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
  34221. osGetCurrentProcessId(), pFile, pFile->h));
  34222. return SQLITE_OK;
  34223. }else{
  34224. pFile->lastErrno = osGetLastError();
  34225. OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
  34226. osGetCurrentProcessId(), pFile, pFile->h));
  34227. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  34228. "winSync2", pFile->zPath);
  34229. }
  34230. #endif
  34231. }
  34232. /*
  34233. ** Determine the current size of a file in bytes
  34234. */
  34235. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  34236. winFile *pFile = (winFile*)id;
  34237. int rc = SQLITE_OK;
  34238. assert( id!=0 );
  34239. assert( pSize!=0 );
  34240. SimulateIOError(return SQLITE_IOERR_FSTAT);
  34241. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  34242. #if SQLITE_OS_WINRT
  34243. {
  34244. FILE_STANDARD_INFO info;
  34245. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  34246. &info, sizeof(info)) ){
  34247. *pSize = info.EndOfFile.QuadPart;
  34248. }else{
  34249. pFile->lastErrno = osGetLastError();
  34250. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  34251. "winFileSize", pFile->zPath);
  34252. }
  34253. }
  34254. #else
  34255. {
  34256. DWORD upperBits;
  34257. DWORD lowerBits;
  34258. DWORD lastErrno;
  34259. lowerBits = osGetFileSize(pFile->h, &upperBits);
  34260. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  34261. if( (lowerBits == INVALID_FILE_SIZE)
  34262. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  34263. pFile->lastErrno = lastErrno;
  34264. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  34265. "winFileSize", pFile->zPath);
  34266. }
  34267. }
  34268. #endif
  34269. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  34270. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  34271. return rc;
  34272. }
  34273. /*
  34274. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  34275. */
  34276. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  34277. # define LOCKFILE_FAIL_IMMEDIATELY 1
  34278. #endif
  34279. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  34280. # define LOCKFILE_EXCLUSIVE_LOCK 2
  34281. #endif
  34282. /*
  34283. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  34284. ** When the LockFile function was used, it was always expected to fail
  34285. ** immediately if the lock could not be obtained. Also, it always expected to
  34286. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  34287. ** and reflect those expectations; therefore, they should not be changed.
  34288. */
  34289. #ifndef SQLITE_LOCKFILE_FLAGS
  34290. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  34291. LOCKFILE_EXCLUSIVE_LOCK)
  34292. #endif
  34293. /*
  34294. ** Currently, SQLite never calls the LockFileEx function without wanting the
  34295. ** call to fail immediately if the lock cannot be obtained.
  34296. */
  34297. #ifndef SQLITE_LOCKFILEEX_FLAGS
  34298. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  34299. #endif
  34300. /*
  34301. ** Acquire a reader lock.
  34302. ** Different API routines are called depending on whether or not this
  34303. ** is Win9x or WinNT.
  34304. */
  34305. static int winGetReadLock(winFile *pFile){
  34306. int res;
  34307. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  34308. if( osIsNT() ){
  34309. #if SQLITE_OS_WINCE
  34310. /*
  34311. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  34312. ** API LockFileEx.
  34313. */
  34314. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  34315. #else
  34316. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  34317. SHARED_SIZE, 0);
  34318. #endif
  34319. }
  34320. #ifdef SQLITE_WIN32_HAS_ANSI
  34321. else{
  34322. int lk;
  34323. sqlite3_randomness(sizeof(lk), &lk);
  34324. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  34325. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  34326. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  34327. }
  34328. #endif
  34329. if( res == 0 ){
  34330. pFile->lastErrno = osGetLastError();
  34331. /* No need to log a failure to lock */
  34332. }
  34333. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  34334. return res;
  34335. }
  34336. /*
  34337. ** Undo a readlock
  34338. */
  34339. static int winUnlockReadLock(winFile *pFile){
  34340. int res;
  34341. DWORD lastErrno;
  34342. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  34343. if( osIsNT() ){
  34344. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  34345. }
  34346. #ifdef SQLITE_WIN32_HAS_ANSI
  34347. else{
  34348. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  34349. }
  34350. #endif
  34351. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  34352. pFile->lastErrno = lastErrno;
  34353. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  34354. "winUnlockReadLock", pFile->zPath);
  34355. }
  34356. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  34357. return res;
  34358. }
  34359. /*
  34360. ** Lock the file with the lock specified by parameter locktype - one
  34361. ** of the following:
  34362. **
  34363. ** (1) SHARED_LOCK
  34364. ** (2) RESERVED_LOCK
  34365. ** (3) PENDING_LOCK
  34366. ** (4) EXCLUSIVE_LOCK
  34367. **
  34368. ** Sometimes when requesting one lock state, additional lock states
  34369. ** are inserted in between. The locking might fail on one of the later
  34370. ** transitions leaving the lock state different from what it started but
  34371. ** still short of its goal. The following chart shows the allowed
  34372. ** transitions and the inserted intermediate states:
  34373. **
  34374. ** UNLOCKED -> SHARED
  34375. ** SHARED -> RESERVED
  34376. ** SHARED -> (PENDING) -> EXCLUSIVE
  34377. ** RESERVED -> (PENDING) -> EXCLUSIVE
  34378. ** PENDING -> EXCLUSIVE
  34379. **
  34380. ** This routine will only increase a lock. The winUnlock() routine
  34381. ** erases all locks at once and returns us immediately to locking level 0.
  34382. ** It is not possible to lower the locking level one step at a time. You
  34383. ** must go straight to locking level 0.
  34384. */
  34385. static int winLock(sqlite3_file *id, int locktype){
  34386. int rc = SQLITE_OK; /* Return code from subroutines */
  34387. int res = 1; /* Result of a Windows lock call */
  34388. int newLocktype; /* Set pFile->locktype to this value before exiting */
  34389. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  34390. winFile *pFile = (winFile*)id;
  34391. DWORD lastErrno = NO_ERROR;
  34392. assert( id!=0 );
  34393. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  34394. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  34395. /* If there is already a lock of this type or more restrictive on the
  34396. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  34397. ** sqlite3OsEnterMutex() hasn't been called yet.
  34398. */
  34399. if( pFile->locktype>=locktype ){
  34400. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  34401. return SQLITE_OK;
  34402. }
  34403. /* Do not allow any kind of write-lock on a read-only database
  34404. */
  34405. if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
  34406. return SQLITE_IOERR_LOCK;
  34407. }
  34408. /* Make sure the locking sequence is correct
  34409. */
  34410. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  34411. assert( locktype!=PENDING_LOCK );
  34412. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  34413. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  34414. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  34415. ** the PENDING_LOCK byte is temporary.
  34416. */
  34417. newLocktype = pFile->locktype;
  34418. if( (pFile->locktype==NO_LOCK)
  34419. || ( (locktype==EXCLUSIVE_LOCK)
  34420. && (pFile->locktype==RESERVED_LOCK))
  34421. ){
  34422. int cnt = 3;
  34423. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  34424. PENDING_BYTE, 0, 1, 0))==0 ){
  34425. /* Try 3 times to get the pending lock. This is needed to work
  34426. ** around problems caused by indexing and/or anti-virus software on
  34427. ** Windows systems.
  34428. ** If you are using this code as a model for alternative VFSes, do not
  34429. ** copy this retry logic. It is a hack intended for Windows only.
  34430. */
  34431. lastErrno = osGetLastError();
  34432. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  34433. pFile->h, cnt, res));
  34434. if( lastErrno==ERROR_INVALID_HANDLE ){
  34435. pFile->lastErrno = lastErrno;
  34436. rc = SQLITE_IOERR_LOCK;
  34437. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  34438. pFile->h, cnt, sqlite3ErrName(rc)));
  34439. return rc;
  34440. }
  34441. if( cnt ) sqlite3_win32_sleep(1);
  34442. }
  34443. gotPendingLock = res;
  34444. if( !res ){
  34445. lastErrno = osGetLastError();
  34446. }
  34447. }
  34448. /* Acquire a shared lock
  34449. */
  34450. if( locktype==SHARED_LOCK && res ){
  34451. assert( pFile->locktype==NO_LOCK );
  34452. res = winGetReadLock(pFile);
  34453. if( res ){
  34454. newLocktype = SHARED_LOCK;
  34455. }else{
  34456. lastErrno = osGetLastError();
  34457. }
  34458. }
  34459. /* Acquire a RESERVED lock
  34460. */
  34461. if( locktype==RESERVED_LOCK && res ){
  34462. assert( pFile->locktype==SHARED_LOCK );
  34463. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  34464. if( res ){
  34465. newLocktype = RESERVED_LOCK;
  34466. }else{
  34467. lastErrno = osGetLastError();
  34468. }
  34469. }
  34470. /* Acquire a PENDING lock
  34471. */
  34472. if( locktype==EXCLUSIVE_LOCK && res ){
  34473. newLocktype = PENDING_LOCK;
  34474. gotPendingLock = 0;
  34475. }
  34476. /* Acquire an EXCLUSIVE lock
  34477. */
  34478. if( locktype==EXCLUSIVE_LOCK && res ){
  34479. assert( pFile->locktype>=SHARED_LOCK );
  34480. res = winUnlockReadLock(pFile);
  34481. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  34482. SHARED_SIZE, 0);
  34483. if( res ){
  34484. newLocktype = EXCLUSIVE_LOCK;
  34485. }else{
  34486. lastErrno = osGetLastError();
  34487. winGetReadLock(pFile);
  34488. }
  34489. }
  34490. /* If we are holding a PENDING lock that ought to be released, then
  34491. ** release it now.
  34492. */
  34493. if( gotPendingLock && locktype==SHARED_LOCK ){
  34494. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  34495. }
  34496. /* Update the state of the lock has held in the file descriptor then
  34497. ** return the appropriate result code.
  34498. */
  34499. if( res ){
  34500. rc = SQLITE_OK;
  34501. }else{
  34502. pFile->lastErrno = lastErrno;
  34503. rc = SQLITE_BUSY;
  34504. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  34505. pFile->h, locktype, newLocktype));
  34506. }
  34507. pFile->locktype = (u8)newLocktype;
  34508. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  34509. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  34510. return rc;
  34511. }
  34512. /*
  34513. ** This routine checks if there is a RESERVED lock held on the specified
  34514. ** file by this or any other process. If such a lock is held, return
  34515. ** non-zero, otherwise zero.
  34516. */
  34517. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  34518. int res;
  34519. winFile *pFile = (winFile*)id;
  34520. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  34521. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  34522. assert( id!=0 );
  34523. if( pFile->locktype>=RESERVED_LOCK ){
  34524. res = 1;
  34525. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  34526. }else{
  34527. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  34528. if( res ){
  34529. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  34530. }
  34531. res = !res;
  34532. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  34533. }
  34534. *pResOut = res;
  34535. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  34536. pFile->h, pResOut, *pResOut));
  34537. return SQLITE_OK;
  34538. }
  34539. /*
  34540. ** Lower the locking level on file descriptor id to locktype. locktype
  34541. ** must be either NO_LOCK or SHARED_LOCK.
  34542. **
  34543. ** If the locking level of the file descriptor is already at or below
  34544. ** the requested locking level, this routine is a no-op.
  34545. **
  34546. ** It is not possible for this routine to fail if the second argument
  34547. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  34548. ** might return SQLITE_IOERR;
  34549. */
  34550. static int winUnlock(sqlite3_file *id, int locktype){
  34551. int type;
  34552. winFile *pFile = (winFile*)id;
  34553. int rc = SQLITE_OK;
  34554. assert( pFile!=0 );
  34555. assert( locktype<=SHARED_LOCK );
  34556. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  34557. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  34558. type = pFile->locktype;
  34559. if( type>=EXCLUSIVE_LOCK ){
  34560. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  34561. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  34562. /* This should never happen. We should always be able to
  34563. ** reacquire the read lock */
  34564. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  34565. "winUnlock", pFile->zPath);
  34566. }
  34567. }
  34568. if( type>=RESERVED_LOCK ){
  34569. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  34570. }
  34571. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  34572. winUnlockReadLock(pFile);
  34573. }
  34574. if( type>=PENDING_LOCK ){
  34575. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  34576. }
  34577. pFile->locktype = (u8)locktype;
  34578. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  34579. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  34580. return rc;
  34581. }
  34582. /*
  34583. ** If *pArg is initially negative then this is a query. Set *pArg to
  34584. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  34585. **
  34586. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  34587. */
  34588. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  34589. if( *pArg<0 ){
  34590. *pArg = (pFile->ctrlFlags & mask)!=0;
  34591. }else if( (*pArg)==0 ){
  34592. pFile->ctrlFlags &= ~mask;
  34593. }else{
  34594. pFile->ctrlFlags |= mask;
  34595. }
  34596. }
  34597. /* Forward references to VFS helper methods used for temporary files */
  34598. static int winGetTempname(sqlite3_vfs *, char **);
  34599. static int winIsDir(const void *);
  34600. static BOOL winIsDriveLetterAndColon(const char *);
  34601. /*
  34602. ** Control and query of the open file handle.
  34603. */
  34604. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  34605. winFile *pFile = (winFile*)id;
  34606. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  34607. switch( op ){
  34608. case SQLITE_FCNTL_LOCKSTATE: {
  34609. *(int*)pArg = pFile->locktype;
  34610. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34611. return SQLITE_OK;
  34612. }
  34613. case SQLITE_LAST_ERRNO: {
  34614. *(int*)pArg = (int)pFile->lastErrno;
  34615. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34616. return SQLITE_OK;
  34617. }
  34618. case SQLITE_FCNTL_CHUNK_SIZE: {
  34619. pFile->szChunk = *(int *)pArg;
  34620. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34621. return SQLITE_OK;
  34622. }
  34623. case SQLITE_FCNTL_SIZE_HINT: {
  34624. if( pFile->szChunk>0 ){
  34625. sqlite3_int64 oldSz;
  34626. int rc = winFileSize(id, &oldSz);
  34627. if( rc==SQLITE_OK ){
  34628. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  34629. if( newSz>oldSz ){
  34630. SimulateIOErrorBenign(1);
  34631. rc = winTruncate(id, newSz);
  34632. SimulateIOErrorBenign(0);
  34633. }
  34634. }
  34635. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  34636. return rc;
  34637. }
  34638. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34639. return SQLITE_OK;
  34640. }
  34641. case SQLITE_FCNTL_PERSIST_WAL: {
  34642. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  34643. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34644. return SQLITE_OK;
  34645. }
  34646. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  34647. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  34648. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34649. return SQLITE_OK;
  34650. }
  34651. case SQLITE_FCNTL_VFSNAME: {
  34652. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  34653. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34654. return SQLITE_OK;
  34655. }
  34656. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  34657. int *a = (int*)pArg;
  34658. if( a[0]>0 ){
  34659. winIoerrRetry = a[0];
  34660. }else{
  34661. a[0] = winIoerrRetry;
  34662. }
  34663. if( a[1]>0 ){
  34664. winIoerrRetryDelay = a[1];
  34665. }else{
  34666. a[1] = winIoerrRetryDelay;
  34667. }
  34668. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  34669. return SQLITE_OK;
  34670. }
  34671. #ifdef SQLITE_TEST
  34672. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  34673. LPHANDLE phFile = (LPHANDLE)pArg;
  34674. HANDLE hOldFile = pFile->h;
  34675. pFile->h = *phFile;
  34676. *phFile = hOldFile;
  34677. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  34678. hOldFile, pFile->h));
  34679. return SQLITE_OK;
  34680. }
  34681. #endif
  34682. case SQLITE_FCNTL_TEMPFILENAME: {
  34683. char *zTFile = 0;
  34684. int rc = winGetTempname(pFile->pVfs, &zTFile);
  34685. if( rc==SQLITE_OK ){
  34686. *(char**)pArg = zTFile;
  34687. }
  34688. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  34689. return rc;
  34690. }
  34691. #if SQLITE_MAX_MMAP_SIZE>0
  34692. case SQLITE_FCNTL_MMAP_SIZE: {
  34693. i64 newLimit = *(i64*)pArg;
  34694. int rc = SQLITE_OK;
  34695. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  34696. newLimit = sqlite3GlobalConfig.mxMmap;
  34697. }
  34698. *(i64*)pArg = pFile->mmapSizeMax;
  34699. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  34700. pFile->mmapSizeMax = newLimit;
  34701. if( pFile->mmapSize>0 ){
  34702. winUnmapfile(pFile);
  34703. rc = winMapfile(pFile, -1);
  34704. }
  34705. }
  34706. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  34707. return rc;
  34708. }
  34709. #endif
  34710. }
  34711. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  34712. return SQLITE_NOTFOUND;
  34713. }
  34714. /*
  34715. ** Return the sector size in bytes of the underlying block device for
  34716. ** the specified file. This is almost always 512 bytes, but may be
  34717. ** larger for some devices.
  34718. **
  34719. ** SQLite code assumes this function cannot fail. It also assumes that
  34720. ** if two files are created in the same file-system directory (i.e.
  34721. ** a database and its journal file) that the sector size will be the
  34722. ** same for both.
  34723. */
  34724. static int winSectorSize(sqlite3_file *id){
  34725. (void)id;
  34726. return SQLITE_DEFAULT_SECTOR_SIZE;
  34727. }
  34728. /*
  34729. ** Return a vector of device characteristics.
  34730. */
  34731. static int winDeviceCharacteristics(sqlite3_file *id){
  34732. winFile *p = (winFile*)id;
  34733. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  34734. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  34735. }
  34736. /*
  34737. ** Windows will only let you create file view mappings
  34738. ** on allocation size granularity boundaries.
  34739. ** During sqlite3_os_init() we do a GetSystemInfo()
  34740. ** to get the granularity size.
  34741. */
  34742. static SYSTEM_INFO winSysInfo;
  34743. #ifndef SQLITE_OMIT_WAL
  34744. /*
  34745. ** Helper functions to obtain and relinquish the global mutex. The
  34746. ** global mutex is used to protect the winLockInfo objects used by
  34747. ** this file, all of which may be shared by multiple threads.
  34748. **
  34749. ** Function winShmMutexHeld() is used to assert() that the global mutex
  34750. ** is held when required. This function is only used as part of assert()
  34751. ** statements. e.g.
  34752. **
  34753. ** winShmEnterMutex()
  34754. ** assert( winShmMutexHeld() );
  34755. ** winShmLeaveMutex()
  34756. */
  34757. static void winShmEnterMutex(void){
  34758. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  34759. }
  34760. static void winShmLeaveMutex(void){
  34761. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  34762. }
  34763. #ifndef NDEBUG
  34764. static int winShmMutexHeld(void) {
  34765. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_VFS1));
  34766. }
  34767. #endif
  34768. /*
  34769. ** Object used to represent a single file opened and mmapped to provide
  34770. ** shared memory. When multiple threads all reference the same
  34771. ** log-summary, each thread has its own winFile object, but they all
  34772. ** point to a single instance of this object. In other words, each
  34773. ** log-summary is opened only once per process.
  34774. **
  34775. ** winShmMutexHeld() must be true when creating or destroying
  34776. ** this object or while reading or writing the following fields:
  34777. **
  34778. ** nRef
  34779. ** pNext
  34780. **
  34781. ** The following fields are read-only after the object is created:
  34782. **
  34783. ** fid
  34784. ** zFilename
  34785. **
  34786. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  34787. ** winShmMutexHeld() is true when reading or writing any other field
  34788. ** in this structure.
  34789. **
  34790. */
  34791. struct winShmNode {
  34792. sqlite3_mutex *mutex; /* Mutex to access this object */
  34793. char *zFilename; /* Name of the file */
  34794. winFile hFile; /* File handle from winOpen */
  34795. int szRegion; /* Size of shared-memory regions */
  34796. int nRegion; /* Size of array apRegion */
  34797. struct ShmRegion {
  34798. HANDLE hMap; /* File handle from CreateFileMapping */
  34799. void *pMap;
  34800. } *aRegion;
  34801. DWORD lastErrno; /* The Windows errno from the last I/O error */
  34802. int nRef; /* Number of winShm objects pointing to this */
  34803. winShm *pFirst; /* All winShm objects pointing to this */
  34804. winShmNode *pNext; /* Next in list of all winShmNode objects */
  34805. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  34806. u8 nextShmId; /* Next available winShm.id value */
  34807. #endif
  34808. };
  34809. /*
  34810. ** A global array of all winShmNode objects.
  34811. **
  34812. ** The winShmMutexHeld() must be true while reading or writing this list.
  34813. */
  34814. static winShmNode *winShmNodeList = 0;
  34815. /*
  34816. ** Structure used internally by this VFS to record the state of an
  34817. ** open shared memory connection.
  34818. **
  34819. ** The following fields are initialized when this object is created and
  34820. ** are read-only thereafter:
  34821. **
  34822. ** winShm.pShmNode
  34823. ** winShm.id
  34824. **
  34825. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  34826. ** while accessing any read/write fields.
  34827. */
  34828. struct winShm {
  34829. winShmNode *pShmNode; /* The underlying winShmNode object */
  34830. winShm *pNext; /* Next winShm with the same winShmNode */
  34831. u8 hasMutex; /* True if holding the winShmNode mutex */
  34832. u16 sharedMask; /* Mask of shared locks held */
  34833. u16 exclMask; /* Mask of exclusive locks held */
  34834. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  34835. u8 id; /* Id of this connection with its winShmNode */
  34836. #endif
  34837. };
  34838. /*
  34839. ** Constants used for locking
  34840. */
  34841. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  34842. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  34843. /*
  34844. ** Apply advisory locks for all n bytes beginning at ofst.
  34845. */
  34846. #define _SHM_UNLCK 1
  34847. #define _SHM_RDLCK 2
  34848. #define _SHM_WRLCK 3
  34849. static int winShmSystemLock(
  34850. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  34851. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  34852. int ofst, /* Offset to first byte to be locked/unlocked */
  34853. int nByte /* Number of bytes to lock or unlock */
  34854. ){
  34855. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  34856. /* Access to the winShmNode object is serialized by the caller */
  34857. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  34858. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  34859. pFile->hFile.h, lockType, ofst, nByte));
  34860. /* Release/Acquire the system-level lock */
  34861. if( lockType==_SHM_UNLCK ){
  34862. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  34863. }else{
  34864. /* Initialize the locking parameters */
  34865. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  34866. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  34867. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  34868. }
  34869. if( rc!= 0 ){
  34870. rc = SQLITE_OK;
  34871. }else{
  34872. pFile->lastErrno = osGetLastError();
  34873. rc = SQLITE_BUSY;
  34874. }
  34875. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  34876. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  34877. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  34878. return rc;
  34879. }
  34880. /* Forward references to VFS methods */
  34881. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  34882. static int winDelete(sqlite3_vfs *,const char*,int);
  34883. /*
  34884. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  34885. **
  34886. ** This is not a VFS shared-memory method; it is a utility function called
  34887. ** by VFS shared-memory methods.
  34888. */
  34889. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  34890. winShmNode **pp;
  34891. winShmNode *p;
  34892. assert( winShmMutexHeld() );
  34893. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  34894. osGetCurrentProcessId(), deleteFlag));
  34895. pp = &winShmNodeList;
  34896. while( (p = *pp)!=0 ){
  34897. if( p->nRef==0 ){
  34898. int i;
  34899. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  34900. for(i=0; i<p->nRegion; i++){
  34901. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  34902. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  34903. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  34904. UNUSED_VARIABLE_VALUE(bRc);
  34905. bRc = osCloseHandle(p->aRegion[i].hMap);
  34906. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  34907. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  34908. UNUSED_VARIABLE_VALUE(bRc);
  34909. }
  34910. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  34911. SimulateIOErrorBenign(1);
  34912. winClose((sqlite3_file *)&p->hFile);
  34913. SimulateIOErrorBenign(0);
  34914. }
  34915. if( deleteFlag ){
  34916. SimulateIOErrorBenign(1);
  34917. sqlite3BeginBenignMalloc();
  34918. winDelete(pVfs, p->zFilename, 0);
  34919. sqlite3EndBenignMalloc();
  34920. SimulateIOErrorBenign(0);
  34921. }
  34922. *pp = p->pNext;
  34923. sqlite3_free(p->aRegion);
  34924. sqlite3_free(p);
  34925. }else{
  34926. pp = &p->pNext;
  34927. }
  34928. }
  34929. }
  34930. /*
  34931. ** Open the shared-memory area associated with database file pDbFd.
  34932. **
  34933. ** When opening a new shared-memory file, if no other instances of that
  34934. ** file are currently open, in this process or in other processes, then
  34935. ** the file must be truncated to zero length or have its header cleared.
  34936. */
  34937. static int winOpenSharedMemory(winFile *pDbFd){
  34938. struct winShm *p; /* The connection to be opened */
  34939. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  34940. int rc; /* Result code */
  34941. struct winShmNode *pNew; /* Newly allocated winShmNode */
  34942. int nName; /* Size of zName in bytes */
  34943. assert( pDbFd->pShm==0 ); /* Not previously opened */
  34944. /* Allocate space for the new sqlite3_shm object. Also speculatively
  34945. ** allocate space for a new winShmNode and filename.
  34946. */
  34947. p = sqlite3MallocZero( sizeof(*p) );
  34948. if( p==0 ) return SQLITE_IOERR_NOMEM;
  34949. nName = sqlite3Strlen30(pDbFd->zPath);
  34950. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  34951. if( pNew==0 ){
  34952. sqlite3_free(p);
  34953. return SQLITE_IOERR_NOMEM;
  34954. }
  34955. pNew->zFilename = (char*)&pNew[1];
  34956. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  34957. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  34958. /* Look to see if there is an existing winShmNode that can be used.
  34959. ** If no matching winShmNode currently exists, create a new one.
  34960. */
  34961. winShmEnterMutex();
  34962. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  34963. /* TBD need to come up with better match here. Perhaps
  34964. ** use FILE_ID_BOTH_DIR_INFO Structure.
  34965. */
  34966. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  34967. }
  34968. if( pShmNode ){
  34969. sqlite3_free(pNew);
  34970. }else{
  34971. pShmNode = pNew;
  34972. pNew = 0;
  34973. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  34974. pShmNode->pNext = winShmNodeList;
  34975. winShmNodeList = pShmNode;
  34976. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  34977. if( pShmNode->mutex==0 ){
  34978. rc = SQLITE_IOERR_NOMEM;
  34979. goto shm_open_err;
  34980. }
  34981. rc = winOpen(pDbFd->pVfs,
  34982. pShmNode->zFilename, /* Name of the file (UTF-8) */
  34983. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  34984. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  34985. 0);
  34986. if( SQLITE_OK!=rc ){
  34987. goto shm_open_err;
  34988. }
  34989. /* Check to see if another process is holding the dead-man switch.
  34990. ** If not, truncate the file to zero length.
  34991. */
  34992. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  34993. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  34994. if( rc!=SQLITE_OK ){
  34995. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  34996. "winOpenShm", pDbFd->zPath);
  34997. }
  34998. }
  34999. if( rc==SQLITE_OK ){
  35000. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  35001. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  35002. }
  35003. if( rc ) goto shm_open_err;
  35004. }
  35005. /* Make the new connection a child of the winShmNode */
  35006. p->pShmNode = pShmNode;
  35007. #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
  35008. p->id = pShmNode->nextShmId++;
  35009. #endif
  35010. pShmNode->nRef++;
  35011. pDbFd->pShm = p;
  35012. winShmLeaveMutex();
  35013. /* The reference count on pShmNode has already been incremented under
  35014. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  35015. ** new (struct winShm) object to the pShmNode has been set. All that is
  35016. ** left to do is to link the new object into the linked list starting
  35017. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  35018. ** mutex.
  35019. */
  35020. sqlite3_mutex_enter(pShmNode->mutex);
  35021. p->pNext = pShmNode->pFirst;
  35022. pShmNode->pFirst = p;
  35023. sqlite3_mutex_leave(pShmNode->mutex);
  35024. return SQLITE_OK;
  35025. /* Jump here on any error */
  35026. shm_open_err:
  35027. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  35028. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  35029. sqlite3_free(p);
  35030. sqlite3_free(pNew);
  35031. winShmLeaveMutex();
  35032. return rc;
  35033. }
  35034. /*
  35035. ** Close a connection to shared-memory. Delete the underlying
  35036. ** storage if deleteFlag is true.
  35037. */
  35038. static int winShmUnmap(
  35039. sqlite3_file *fd, /* Database holding shared memory */
  35040. int deleteFlag /* Delete after closing if true */
  35041. ){
  35042. winFile *pDbFd; /* Database holding shared-memory */
  35043. winShm *p; /* The connection to be closed */
  35044. winShmNode *pShmNode; /* The underlying shared-memory file */
  35045. winShm **pp; /* For looping over sibling connections */
  35046. pDbFd = (winFile*)fd;
  35047. p = pDbFd->pShm;
  35048. if( p==0 ) return SQLITE_OK;
  35049. pShmNode = p->pShmNode;
  35050. /* Remove connection p from the set of connections associated
  35051. ** with pShmNode */
  35052. sqlite3_mutex_enter(pShmNode->mutex);
  35053. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  35054. *pp = p->pNext;
  35055. /* Free the connection p */
  35056. sqlite3_free(p);
  35057. pDbFd->pShm = 0;
  35058. sqlite3_mutex_leave(pShmNode->mutex);
  35059. /* If pShmNode->nRef has reached 0, then close the underlying
  35060. ** shared-memory file, too */
  35061. winShmEnterMutex();
  35062. assert( pShmNode->nRef>0 );
  35063. pShmNode->nRef--;
  35064. if( pShmNode->nRef==0 ){
  35065. winShmPurge(pDbFd->pVfs, deleteFlag);
  35066. }
  35067. winShmLeaveMutex();
  35068. return SQLITE_OK;
  35069. }
  35070. /*
  35071. ** Change the lock state for a shared-memory segment.
  35072. */
  35073. static int winShmLock(
  35074. sqlite3_file *fd, /* Database file holding the shared memory */
  35075. int ofst, /* First lock to acquire or release */
  35076. int n, /* Number of locks to acquire or release */
  35077. int flags /* What to do with the lock */
  35078. ){
  35079. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  35080. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  35081. winShm *pX; /* For looping over all siblings */
  35082. winShmNode *pShmNode = p->pShmNode;
  35083. int rc = SQLITE_OK; /* Result code */
  35084. u16 mask; /* Mask of locks to take or release */
  35085. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  35086. assert( n>=1 );
  35087. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  35088. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  35089. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  35090. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  35091. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  35092. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  35093. assert( n>1 || mask==(1<<ofst) );
  35094. sqlite3_mutex_enter(pShmNode->mutex);
  35095. if( flags & SQLITE_SHM_UNLOCK ){
  35096. u16 allMask = 0; /* Mask of locks held by siblings */
  35097. /* See if any siblings hold this same lock */
  35098. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35099. if( pX==p ) continue;
  35100. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  35101. allMask |= pX->sharedMask;
  35102. }
  35103. /* Unlock the system-level locks */
  35104. if( (mask & allMask)==0 ){
  35105. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  35106. }else{
  35107. rc = SQLITE_OK;
  35108. }
  35109. /* Undo the local locks */
  35110. if( rc==SQLITE_OK ){
  35111. p->exclMask &= ~mask;
  35112. p->sharedMask &= ~mask;
  35113. }
  35114. }else if( flags & SQLITE_SHM_SHARED ){
  35115. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  35116. /* Find out which shared locks are already held by sibling connections.
  35117. ** If any sibling already holds an exclusive lock, go ahead and return
  35118. ** SQLITE_BUSY.
  35119. */
  35120. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35121. if( (pX->exclMask & mask)!=0 ){
  35122. rc = SQLITE_BUSY;
  35123. break;
  35124. }
  35125. allShared |= pX->sharedMask;
  35126. }
  35127. /* Get shared locks at the system level, if necessary */
  35128. if( rc==SQLITE_OK ){
  35129. if( (allShared & mask)==0 ){
  35130. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  35131. }else{
  35132. rc = SQLITE_OK;
  35133. }
  35134. }
  35135. /* Get the local shared locks */
  35136. if( rc==SQLITE_OK ){
  35137. p->sharedMask |= mask;
  35138. }
  35139. }else{
  35140. /* Make sure no sibling connections hold locks that will block this
  35141. ** lock. If any do, return SQLITE_BUSY right away.
  35142. */
  35143. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  35144. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  35145. rc = SQLITE_BUSY;
  35146. break;
  35147. }
  35148. }
  35149. /* Get the exclusive locks at the system level. Then if successful
  35150. ** also mark the local connection as being locked.
  35151. */
  35152. if( rc==SQLITE_OK ){
  35153. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  35154. if( rc==SQLITE_OK ){
  35155. assert( (p->sharedMask & mask)==0 );
  35156. p->exclMask |= mask;
  35157. }
  35158. }
  35159. }
  35160. sqlite3_mutex_leave(pShmNode->mutex);
  35161. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  35162. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  35163. sqlite3ErrName(rc)));
  35164. return rc;
  35165. }
  35166. /*
  35167. ** Implement a memory barrier or memory fence on shared memory.
  35168. **
  35169. ** All loads and stores begun before the barrier must complete before
  35170. ** any load or store begun after the barrier.
  35171. */
  35172. static void winShmBarrier(
  35173. sqlite3_file *fd /* Database holding the shared memory */
  35174. ){
  35175. UNUSED_PARAMETER(fd);
  35176. /* MemoryBarrier(); // does not work -- do not know why not */
  35177. winShmEnterMutex();
  35178. winShmLeaveMutex();
  35179. }
  35180. /*
  35181. ** This function is called to obtain a pointer to region iRegion of the
  35182. ** shared-memory associated with the database file fd. Shared-memory regions
  35183. ** are numbered starting from zero. Each shared-memory region is szRegion
  35184. ** bytes in size.
  35185. **
  35186. ** If an error occurs, an error code is returned and *pp is set to NULL.
  35187. **
  35188. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  35189. ** region has not been allocated (by any client, including one running in a
  35190. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  35191. ** isWrite is non-zero and the requested shared-memory region has not yet
  35192. ** been allocated, it is allocated by this function.
  35193. **
  35194. ** If the shared-memory region has already been allocated or is allocated by
  35195. ** this call as described above, then it is mapped into this processes
  35196. ** address space (if it is not already), *pp is set to point to the mapped
  35197. ** memory and SQLITE_OK returned.
  35198. */
  35199. static int winShmMap(
  35200. sqlite3_file *fd, /* Handle open on database file */
  35201. int iRegion, /* Region to retrieve */
  35202. int szRegion, /* Size of regions */
  35203. int isWrite, /* True to extend file if necessary */
  35204. void volatile **pp /* OUT: Mapped memory */
  35205. ){
  35206. winFile *pDbFd = (winFile*)fd;
  35207. winShm *pShm = pDbFd->pShm;
  35208. winShmNode *pShmNode;
  35209. int rc = SQLITE_OK;
  35210. if( !pShm ){
  35211. rc = winOpenSharedMemory(pDbFd);
  35212. if( rc!=SQLITE_OK ) return rc;
  35213. pShm = pDbFd->pShm;
  35214. }
  35215. pShmNode = pShm->pShmNode;
  35216. sqlite3_mutex_enter(pShmNode->mutex);
  35217. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  35218. if( pShmNode->nRegion<=iRegion ){
  35219. struct ShmRegion *apNew; /* New aRegion[] array */
  35220. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  35221. sqlite3_int64 sz; /* Current size of wal-index file */
  35222. pShmNode->szRegion = szRegion;
  35223. /* The requested region is not mapped into this processes address space.
  35224. ** Check to see if it has been allocated (i.e. if the wal-index file is
  35225. ** large enough to contain the requested region).
  35226. */
  35227. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  35228. if( rc!=SQLITE_OK ){
  35229. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  35230. "winShmMap1", pDbFd->zPath);
  35231. goto shmpage_out;
  35232. }
  35233. if( sz<nByte ){
  35234. /* The requested memory region does not exist. If isWrite is set to
  35235. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  35236. **
  35237. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  35238. ** the requested memory region.
  35239. */
  35240. if( !isWrite ) goto shmpage_out;
  35241. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  35242. if( rc!=SQLITE_OK ){
  35243. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  35244. "winShmMap2", pDbFd->zPath);
  35245. goto shmpage_out;
  35246. }
  35247. }
  35248. /* Map the requested memory region into this processes address space. */
  35249. apNew = (struct ShmRegion *)sqlite3_realloc64(
  35250. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  35251. );
  35252. if( !apNew ){
  35253. rc = SQLITE_IOERR_NOMEM;
  35254. goto shmpage_out;
  35255. }
  35256. pShmNode->aRegion = apNew;
  35257. while( pShmNode->nRegion<=iRegion ){
  35258. HANDLE hMap = NULL; /* file-mapping handle */
  35259. void *pMap = 0; /* Mapped memory region */
  35260. #if SQLITE_OS_WINRT
  35261. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  35262. NULL, PAGE_READWRITE, nByte, NULL
  35263. );
  35264. #elif defined(SQLITE_WIN32_HAS_WIDE)
  35265. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  35266. NULL, PAGE_READWRITE, 0, nByte, NULL
  35267. );
  35268. #elif defined(SQLITE_WIN32_HAS_ANSI)
  35269. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  35270. NULL, PAGE_READWRITE, 0, nByte, NULL
  35271. );
  35272. #endif
  35273. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  35274. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  35275. hMap ? "ok" : "failed"));
  35276. if( hMap ){
  35277. int iOffset = pShmNode->nRegion*szRegion;
  35278. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  35279. #if SQLITE_OS_WINRT
  35280. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  35281. iOffset - iOffsetShift, szRegion + iOffsetShift
  35282. );
  35283. #else
  35284. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  35285. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  35286. );
  35287. #endif
  35288. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  35289. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  35290. szRegion, pMap ? "ok" : "failed"));
  35291. }
  35292. if( !pMap ){
  35293. pShmNode->lastErrno = osGetLastError();
  35294. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  35295. "winShmMap3", pDbFd->zPath);
  35296. if( hMap ) osCloseHandle(hMap);
  35297. goto shmpage_out;
  35298. }
  35299. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  35300. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  35301. pShmNode->nRegion++;
  35302. }
  35303. }
  35304. shmpage_out:
  35305. if( pShmNode->nRegion>iRegion ){
  35306. int iOffset = iRegion*szRegion;
  35307. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  35308. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  35309. *pp = (void *)&p[iOffsetShift];
  35310. }else{
  35311. *pp = 0;
  35312. }
  35313. sqlite3_mutex_leave(pShmNode->mutex);
  35314. return rc;
  35315. }
  35316. #else
  35317. # define winShmMap 0
  35318. # define winShmLock 0
  35319. # define winShmBarrier 0
  35320. # define winShmUnmap 0
  35321. #endif /* #ifndef SQLITE_OMIT_WAL */
  35322. /*
  35323. ** Cleans up the mapped region of the specified file, if any.
  35324. */
  35325. #if SQLITE_MAX_MMAP_SIZE>0
  35326. static int winUnmapfile(winFile *pFile){
  35327. assert( pFile!=0 );
  35328. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  35329. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  35330. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  35331. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  35332. if( pFile->pMapRegion ){
  35333. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  35334. pFile->lastErrno = osGetLastError();
  35335. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  35336. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  35337. pFile->pMapRegion));
  35338. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  35339. "winUnmapfile1", pFile->zPath);
  35340. }
  35341. pFile->pMapRegion = 0;
  35342. pFile->mmapSize = 0;
  35343. pFile->mmapSizeActual = 0;
  35344. }
  35345. if( pFile->hMap!=NULL ){
  35346. if( !osCloseHandle(pFile->hMap) ){
  35347. pFile->lastErrno = osGetLastError();
  35348. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  35349. osGetCurrentProcessId(), pFile, pFile->hMap));
  35350. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  35351. "winUnmapfile2", pFile->zPath);
  35352. }
  35353. pFile->hMap = NULL;
  35354. }
  35355. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  35356. osGetCurrentProcessId(), pFile));
  35357. return SQLITE_OK;
  35358. }
  35359. /*
  35360. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  35361. ** is already mapped, the existing mapping is replaced by the new). Or, if
  35362. ** there already exists a mapping for this file, and there are still
  35363. ** outstanding xFetch() references to it, this function is a no-op.
  35364. **
  35365. ** If parameter nByte is non-negative, then it is the requested size of
  35366. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  35367. ** requested size is the size of the file on disk. The actual size of the
  35368. ** created mapping is either the requested size or the value configured
  35369. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  35370. **
  35371. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  35372. ** recreated as a result of outstanding references) or an SQLite error
  35373. ** code otherwise.
  35374. */
  35375. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  35376. sqlite3_int64 nMap = nByte;
  35377. int rc;
  35378. assert( nMap>=0 || pFd->nFetchOut==0 );
  35379. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  35380. osGetCurrentProcessId(), pFd, nByte));
  35381. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  35382. if( nMap<0 ){
  35383. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  35384. if( rc ){
  35385. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  35386. osGetCurrentProcessId(), pFd));
  35387. return SQLITE_IOERR_FSTAT;
  35388. }
  35389. }
  35390. if( nMap>pFd->mmapSizeMax ){
  35391. nMap = pFd->mmapSizeMax;
  35392. }
  35393. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  35394. if( nMap==0 && pFd->mmapSize>0 ){
  35395. winUnmapfile(pFd);
  35396. }
  35397. if( nMap!=pFd->mmapSize ){
  35398. void *pNew = 0;
  35399. DWORD protect = PAGE_READONLY;
  35400. DWORD flags = FILE_MAP_READ;
  35401. winUnmapfile(pFd);
  35402. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  35403. protect = PAGE_READWRITE;
  35404. flags |= FILE_MAP_WRITE;
  35405. }
  35406. #if SQLITE_OS_WINRT
  35407. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  35408. #elif defined(SQLITE_WIN32_HAS_WIDE)
  35409. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  35410. (DWORD)((nMap>>32) & 0xffffffff),
  35411. (DWORD)(nMap & 0xffffffff), NULL);
  35412. #elif defined(SQLITE_WIN32_HAS_ANSI)
  35413. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  35414. (DWORD)((nMap>>32) & 0xffffffff),
  35415. (DWORD)(nMap & 0xffffffff), NULL);
  35416. #endif
  35417. if( pFd->hMap==NULL ){
  35418. pFd->lastErrno = osGetLastError();
  35419. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  35420. "winMapfile1", pFd->zPath);
  35421. /* Log the error, but continue normal operation using xRead/xWrite */
  35422. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  35423. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  35424. return SQLITE_OK;
  35425. }
  35426. assert( (nMap % winSysInfo.dwPageSize)==0 );
  35427. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  35428. #if SQLITE_OS_WINRT
  35429. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  35430. #else
  35431. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  35432. #endif
  35433. if( pNew==NULL ){
  35434. osCloseHandle(pFd->hMap);
  35435. pFd->hMap = NULL;
  35436. pFd->lastErrno = osGetLastError();
  35437. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  35438. "winMapfile2", pFd->zPath);
  35439. /* Log the error, but continue normal operation using xRead/xWrite */
  35440. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  35441. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  35442. return SQLITE_OK;
  35443. }
  35444. pFd->pMapRegion = pNew;
  35445. pFd->mmapSize = nMap;
  35446. pFd->mmapSizeActual = nMap;
  35447. }
  35448. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  35449. osGetCurrentProcessId(), pFd));
  35450. return SQLITE_OK;
  35451. }
  35452. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  35453. /*
  35454. ** If possible, return a pointer to a mapping of file fd starting at offset
  35455. ** iOff. The mapping must be valid for at least nAmt bytes.
  35456. **
  35457. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  35458. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  35459. ** Finally, if an error does occur, return an SQLite error code. The final
  35460. ** value of *pp is undefined in this case.
  35461. **
  35462. ** If this function does return a pointer, the caller must eventually
  35463. ** release the reference by calling winUnfetch().
  35464. */
  35465. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  35466. #if SQLITE_MAX_MMAP_SIZE>0
  35467. winFile *pFd = (winFile*)fd; /* The underlying database file */
  35468. #endif
  35469. *pp = 0;
  35470. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  35471. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  35472. #if SQLITE_MAX_MMAP_SIZE>0
  35473. if( pFd->mmapSizeMax>0 ){
  35474. if( pFd->pMapRegion==0 ){
  35475. int rc = winMapfile(pFd, -1);
  35476. if( rc!=SQLITE_OK ){
  35477. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  35478. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  35479. return rc;
  35480. }
  35481. }
  35482. if( pFd->mmapSize >= iOff+nAmt ){
  35483. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  35484. pFd->nFetchOut++;
  35485. }
  35486. }
  35487. #endif
  35488. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  35489. osGetCurrentProcessId(), fd, pp, *pp));
  35490. return SQLITE_OK;
  35491. }
  35492. /*
  35493. ** If the third argument is non-NULL, then this function releases a
  35494. ** reference obtained by an earlier call to winFetch(). The second
  35495. ** argument passed to this function must be the same as the corresponding
  35496. ** argument that was passed to the winFetch() invocation.
  35497. **
  35498. ** Or, if the third argument is NULL, then this function is being called
  35499. ** to inform the VFS layer that, according to POSIX, any existing mapping
  35500. ** may now be invalid and should be unmapped.
  35501. */
  35502. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  35503. #if SQLITE_MAX_MMAP_SIZE>0
  35504. winFile *pFd = (winFile*)fd; /* The underlying database file */
  35505. /* If p==0 (unmap the entire file) then there must be no outstanding
  35506. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  35507. ** then there must be at least one outstanding. */
  35508. assert( (p==0)==(pFd->nFetchOut==0) );
  35509. /* If p!=0, it must match the iOff value. */
  35510. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  35511. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  35512. osGetCurrentProcessId(), pFd, iOff, p));
  35513. if( p ){
  35514. pFd->nFetchOut--;
  35515. }else{
  35516. /* FIXME: If Windows truly always prevents truncating or deleting a
  35517. ** file while a mapping is held, then the following winUnmapfile() call
  35518. ** is unnecessary can be omitted - potentially improving
  35519. ** performance. */
  35520. winUnmapfile(pFd);
  35521. }
  35522. assert( pFd->nFetchOut>=0 );
  35523. #endif
  35524. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  35525. osGetCurrentProcessId(), fd));
  35526. return SQLITE_OK;
  35527. }
  35528. /*
  35529. ** Here ends the implementation of all sqlite3_file methods.
  35530. **
  35531. ********************** End sqlite3_file Methods *******************************
  35532. ******************************************************************************/
  35533. /*
  35534. ** This vector defines all the methods that can operate on an
  35535. ** sqlite3_file for win32.
  35536. */
  35537. static const sqlite3_io_methods winIoMethod = {
  35538. 3, /* iVersion */
  35539. winClose, /* xClose */
  35540. winRead, /* xRead */
  35541. winWrite, /* xWrite */
  35542. winTruncate, /* xTruncate */
  35543. winSync, /* xSync */
  35544. winFileSize, /* xFileSize */
  35545. winLock, /* xLock */
  35546. winUnlock, /* xUnlock */
  35547. winCheckReservedLock, /* xCheckReservedLock */
  35548. winFileControl, /* xFileControl */
  35549. winSectorSize, /* xSectorSize */
  35550. winDeviceCharacteristics, /* xDeviceCharacteristics */
  35551. winShmMap, /* xShmMap */
  35552. winShmLock, /* xShmLock */
  35553. winShmBarrier, /* xShmBarrier */
  35554. winShmUnmap, /* xShmUnmap */
  35555. winFetch, /* xFetch */
  35556. winUnfetch /* xUnfetch */
  35557. };
  35558. /****************************************************************************
  35559. **************************** sqlite3_vfs methods ****************************
  35560. **
  35561. ** This division contains the implementation of methods on the
  35562. ** sqlite3_vfs object.
  35563. */
  35564. #if defined(__CYGWIN__)
  35565. /*
  35566. ** Convert a filename from whatever the underlying operating system
  35567. ** supports for filenames into UTF-8. Space to hold the result is
  35568. ** obtained from malloc and must be freed by the calling function.
  35569. */
  35570. static char *winConvertToUtf8Filename(const void *zFilename){
  35571. char *zConverted = 0;
  35572. if( osIsNT() ){
  35573. zConverted = winUnicodeToUtf8(zFilename);
  35574. }
  35575. #ifdef SQLITE_WIN32_HAS_ANSI
  35576. else{
  35577. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  35578. }
  35579. #endif
  35580. /* caller will handle out of memory */
  35581. return zConverted;
  35582. }
  35583. #endif
  35584. /*
  35585. ** Convert a UTF-8 filename into whatever form the underlying
  35586. ** operating system wants filenames in. Space to hold the result
  35587. ** is obtained from malloc and must be freed by the calling
  35588. ** function.
  35589. */
  35590. static void *winConvertFromUtf8Filename(const char *zFilename){
  35591. void *zConverted = 0;
  35592. if( osIsNT() ){
  35593. zConverted = winUtf8ToUnicode(zFilename);
  35594. }
  35595. #ifdef SQLITE_WIN32_HAS_ANSI
  35596. else{
  35597. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  35598. }
  35599. #endif
  35600. /* caller will handle out of memory */
  35601. return zConverted;
  35602. }
  35603. /*
  35604. ** This function returns non-zero if the specified UTF-8 string buffer
  35605. ** ends with a directory separator character or one was successfully
  35606. ** added to it.
  35607. */
  35608. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  35609. if( zBuf ){
  35610. int nLen = sqlite3Strlen30(zBuf);
  35611. if( nLen>0 ){
  35612. if( winIsDirSep(zBuf[nLen-1]) ){
  35613. return 1;
  35614. }else if( nLen+1<nBuf ){
  35615. zBuf[nLen] = winGetDirSep();
  35616. zBuf[nLen+1] = '\0';
  35617. return 1;
  35618. }
  35619. }
  35620. }
  35621. return 0;
  35622. }
  35623. /*
  35624. ** Create a temporary file name and store the resulting pointer into pzBuf.
  35625. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  35626. */
  35627. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  35628. static char zChars[] =
  35629. "abcdefghijklmnopqrstuvwxyz"
  35630. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  35631. "0123456789";
  35632. size_t i, j;
  35633. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  35634. int nMax, nBuf, nDir, nLen;
  35635. char *zBuf;
  35636. /* It's odd to simulate an io-error here, but really this is just
  35637. ** using the io-error infrastructure to test that SQLite handles this
  35638. ** function failing.
  35639. */
  35640. SimulateIOError( return SQLITE_IOERR );
  35641. /* Allocate a temporary buffer to store the fully qualified file
  35642. ** name for the temporary file. If this fails, we cannot continue.
  35643. */
  35644. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  35645. zBuf = sqlite3MallocZero( nBuf );
  35646. if( !zBuf ){
  35647. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35648. return SQLITE_IOERR_NOMEM;
  35649. }
  35650. /* Figure out the effective temporary directory. First, check if one
  35651. ** has been explicitly set by the application; otherwise, use the one
  35652. ** configured by the operating system.
  35653. */
  35654. nDir = nMax - (nPre + 15);
  35655. assert( nDir>0 );
  35656. if( sqlite3_temp_directory ){
  35657. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  35658. if( nDirLen>0 ){
  35659. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  35660. nDirLen++;
  35661. }
  35662. if( nDirLen>nDir ){
  35663. sqlite3_free(zBuf);
  35664. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  35665. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  35666. }
  35667. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  35668. }
  35669. }
  35670. #if defined(__CYGWIN__)
  35671. else{
  35672. static const char *azDirs[] = {
  35673. 0, /* getenv("SQLITE_TMPDIR") */
  35674. 0, /* getenv("TMPDIR") */
  35675. 0, /* getenv("TMP") */
  35676. 0, /* getenv("TEMP") */
  35677. 0, /* getenv("USERPROFILE") */
  35678. "/var/tmp",
  35679. "/usr/tmp",
  35680. "/tmp",
  35681. ".",
  35682. 0 /* List terminator */
  35683. };
  35684. unsigned int i;
  35685. const char *zDir = 0;
  35686. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  35687. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  35688. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  35689. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  35690. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  35691. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  35692. void *zConverted;
  35693. if( zDir==0 ) continue;
  35694. /* If the path starts with a drive letter followed by the colon
  35695. ** character, assume it is already a native Win32 path; otherwise,
  35696. ** it must be converted to a native Win32 path via the Cygwin API
  35697. ** prior to using it.
  35698. */
  35699. if( winIsDriveLetterAndColon(zDir) ){
  35700. zConverted = winConvertFromUtf8Filename(zDir);
  35701. if( !zConverted ){
  35702. sqlite3_free(zBuf);
  35703. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35704. return SQLITE_IOERR_NOMEM;
  35705. }
  35706. if( winIsDir(zConverted) ){
  35707. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  35708. sqlite3_free(zConverted);
  35709. break;
  35710. }
  35711. sqlite3_free(zConverted);
  35712. }else{
  35713. zConverted = sqlite3MallocZero( nMax+1 );
  35714. if( !zConverted ){
  35715. sqlite3_free(zBuf);
  35716. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35717. return SQLITE_IOERR_NOMEM;
  35718. }
  35719. if( cygwin_conv_path(
  35720. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  35721. zConverted, nMax+1)<0 ){
  35722. sqlite3_free(zConverted);
  35723. sqlite3_free(zBuf);
  35724. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  35725. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  35726. "winGetTempname2", zDir);
  35727. }
  35728. if( winIsDir(zConverted) ){
  35729. /* At this point, we know the candidate directory exists and should
  35730. ** be used. However, we may need to convert the string containing
  35731. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  35732. */
  35733. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  35734. if( !zUtf8 ){
  35735. sqlite3_free(zConverted);
  35736. sqlite3_free(zBuf);
  35737. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35738. return SQLITE_IOERR_NOMEM;
  35739. }
  35740. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  35741. sqlite3_free(zUtf8);
  35742. sqlite3_free(zConverted);
  35743. break;
  35744. }
  35745. sqlite3_free(zConverted);
  35746. }
  35747. }
  35748. }
  35749. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  35750. else if( osIsNT() ){
  35751. char *zMulti;
  35752. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  35753. if( !zWidePath ){
  35754. sqlite3_free(zBuf);
  35755. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35756. return SQLITE_IOERR_NOMEM;
  35757. }
  35758. if( osGetTempPathW(nMax, zWidePath)==0 ){
  35759. sqlite3_free(zWidePath);
  35760. sqlite3_free(zBuf);
  35761. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  35762. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  35763. "winGetTempname2", 0);
  35764. }
  35765. zMulti = winUnicodeToUtf8(zWidePath);
  35766. if( zMulti ){
  35767. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  35768. sqlite3_free(zMulti);
  35769. sqlite3_free(zWidePath);
  35770. }else{
  35771. sqlite3_free(zWidePath);
  35772. sqlite3_free(zBuf);
  35773. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35774. return SQLITE_IOERR_NOMEM;
  35775. }
  35776. }
  35777. #ifdef SQLITE_WIN32_HAS_ANSI
  35778. else{
  35779. char *zUtf8;
  35780. char *zMbcsPath = sqlite3MallocZero( nMax );
  35781. if( !zMbcsPath ){
  35782. sqlite3_free(zBuf);
  35783. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35784. return SQLITE_IOERR_NOMEM;
  35785. }
  35786. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  35787. sqlite3_free(zBuf);
  35788. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  35789. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  35790. "winGetTempname3", 0);
  35791. }
  35792. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  35793. if( zUtf8 ){
  35794. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  35795. sqlite3_free(zUtf8);
  35796. }else{
  35797. sqlite3_free(zBuf);
  35798. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  35799. return SQLITE_IOERR_NOMEM;
  35800. }
  35801. }
  35802. #endif /* SQLITE_WIN32_HAS_ANSI */
  35803. #endif /* !SQLITE_OS_WINRT */
  35804. /*
  35805. ** Check to make sure the temporary directory ends with an appropriate
  35806. ** separator. If it does not and there is not enough space left to add
  35807. ** one, fail.
  35808. */
  35809. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  35810. sqlite3_free(zBuf);
  35811. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  35812. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  35813. }
  35814. /*
  35815. ** Check that the output buffer is large enough for the temporary file
  35816. ** name in the following format:
  35817. **
  35818. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  35819. **
  35820. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  35821. ** account for the space used by the 15 character random suffix and the
  35822. ** two trailing NUL characters. The final directory separator character
  35823. ** has already added if it was not already present.
  35824. */
  35825. nLen = sqlite3Strlen30(zBuf);
  35826. if( (nLen + nPre + 17) > nBuf ){
  35827. sqlite3_free(zBuf);
  35828. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  35829. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  35830. }
  35831. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  35832. j = sqlite3Strlen30(zBuf);
  35833. sqlite3_randomness(15, &zBuf[j]);
  35834. for(i=0; i<15; i++, j++){
  35835. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  35836. }
  35837. zBuf[j] = 0;
  35838. zBuf[j+1] = 0;
  35839. *pzBuf = zBuf;
  35840. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  35841. return SQLITE_OK;
  35842. }
  35843. /*
  35844. ** Return TRUE if the named file is really a directory. Return false if
  35845. ** it is something other than a directory, or if there is any kind of memory
  35846. ** allocation failure.
  35847. */
  35848. static int winIsDir(const void *zConverted){
  35849. DWORD attr;
  35850. int rc = 0;
  35851. DWORD lastErrno;
  35852. if( osIsNT() ){
  35853. int cnt = 0;
  35854. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  35855. memset(&sAttrData, 0, sizeof(sAttrData));
  35856. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  35857. GetFileExInfoStandard,
  35858. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  35859. if( !rc ){
  35860. return 0; /* Invalid name? */
  35861. }
  35862. attr = sAttrData.dwFileAttributes;
  35863. #if SQLITE_OS_WINCE==0
  35864. }else{
  35865. attr = osGetFileAttributesA((char*)zConverted);
  35866. #endif
  35867. }
  35868. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  35869. }
  35870. /*
  35871. ** Open a file.
  35872. */
  35873. static int winOpen(
  35874. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  35875. const char *zName, /* Name of the file (UTF-8) */
  35876. sqlite3_file *id, /* Write the SQLite file handle here */
  35877. int flags, /* Open mode flags */
  35878. int *pOutFlags /* Status return flags */
  35879. ){
  35880. HANDLE h;
  35881. DWORD lastErrno = 0;
  35882. DWORD dwDesiredAccess;
  35883. DWORD dwShareMode;
  35884. DWORD dwCreationDisposition;
  35885. DWORD dwFlagsAndAttributes = 0;
  35886. #if SQLITE_OS_WINCE
  35887. int isTemp = 0;
  35888. #endif
  35889. winFile *pFile = (winFile*)id;
  35890. void *zConverted; /* Filename in OS encoding */
  35891. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  35892. int cnt = 0;
  35893. /* If argument zPath is a NULL pointer, this function is required to open
  35894. ** a temporary file. Use this buffer to store the file name in.
  35895. */
  35896. char *zTmpname = 0; /* For temporary filename, if necessary. */
  35897. int rc = SQLITE_OK; /* Function Return Code */
  35898. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  35899. int eType = flags&0xFFFFFF00; /* Type of file to open */
  35900. #endif
  35901. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  35902. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  35903. int isCreate = (flags & SQLITE_OPEN_CREATE);
  35904. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  35905. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  35906. #ifndef NDEBUG
  35907. int isOpenJournal = (isCreate && (
  35908. eType==SQLITE_OPEN_MASTER_JOURNAL
  35909. || eType==SQLITE_OPEN_MAIN_JOURNAL
  35910. || eType==SQLITE_OPEN_WAL
  35911. ));
  35912. #endif
  35913. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  35914. zUtf8Name, id, flags, pOutFlags));
  35915. /* Check the following statements are true:
  35916. **
  35917. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  35918. ** (b) if CREATE is set, then READWRITE must also be set, and
  35919. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  35920. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  35921. */
  35922. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  35923. assert(isCreate==0 || isReadWrite);
  35924. assert(isExclusive==0 || isCreate);
  35925. assert(isDelete==0 || isCreate);
  35926. /* The main DB, main journal, WAL file and master journal are never
  35927. ** automatically deleted. Nor are they ever temporary files. */
  35928. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  35929. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  35930. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  35931. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  35932. /* Assert that the upper layer has set one of the "file-type" flags. */
  35933. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  35934. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  35935. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  35936. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  35937. );
  35938. assert( pFile!=0 );
  35939. memset(pFile, 0, sizeof(winFile));
  35940. pFile->h = INVALID_HANDLE_VALUE;
  35941. #if SQLITE_OS_WINRT
  35942. if( !zUtf8Name && !sqlite3_temp_directory ){
  35943. sqlite3_log(SQLITE_ERROR,
  35944. "sqlite3_temp_directory variable should be set for WinRT");
  35945. }
  35946. #endif
  35947. /* If the second argument to this function is NULL, generate a
  35948. ** temporary file name to use
  35949. */
  35950. if( !zUtf8Name ){
  35951. assert( isDelete && !isOpenJournal );
  35952. rc = winGetTempname(pVfs, &zTmpname);
  35953. if( rc!=SQLITE_OK ){
  35954. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  35955. return rc;
  35956. }
  35957. zUtf8Name = zTmpname;
  35958. }
  35959. /* Database filenames are double-zero terminated if they are not
  35960. ** URIs with parameters. Hence, they can always be passed into
  35961. ** sqlite3_uri_parameter().
  35962. */
  35963. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  35964. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  35965. /* Convert the filename to the system encoding. */
  35966. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  35967. if( zConverted==0 ){
  35968. sqlite3_free(zTmpname);
  35969. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  35970. return SQLITE_IOERR_NOMEM;
  35971. }
  35972. if( winIsDir(zConverted) ){
  35973. sqlite3_free(zConverted);
  35974. sqlite3_free(zTmpname);
  35975. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  35976. return SQLITE_CANTOPEN_ISDIR;
  35977. }
  35978. if( isReadWrite ){
  35979. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  35980. }else{
  35981. dwDesiredAccess = GENERIC_READ;
  35982. }
  35983. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  35984. ** created. SQLite doesn't use it to indicate "exclusive access"
  35985. ** as it is usually understood.
  35986. */
  35987. if( isExclusive ){
  35988. /* Creates a new file, only if it does not already exist. */
  35989. /* If the file exists, it fails. */
  35990. dwCreationDisposition = CREATE_NEW;
  35991. }else if( isCreate ){
  35992. /* Open existing file, or create if it doesn't exist */
  35993. dwCreationDisposition = OPEN_ALWAYS;
  35994. }else{
  35995. /* Opens a file, only if it exists. */
  35996. dwCreationDisposition = OPEN_EXISTING;
  35997. }
  35998. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  35999. if( isDelete ){
  36000. #if SQLITE_OS_WINCE
  36001. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  36002. isTemp = 1;
  36003. #else
  36004. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  36005. | FILE_ATTRIBUTE_HIDDEN
  36006. | FILE_FLAG_DELETE_ON_CLOSE;
  36007. #endif
  36008. }else{
  36009. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  36010. }
  36011. /* Reports from the internet are that performance is always
  36012. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  36013. #if SQLITE_OS_WINCE
  36014. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  36015. #endif
  36016. if( osIsNT() ){
  36017. #if SQLITE_OS_WINRT
  36018. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  36019. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  36020. extendedParameters.dwFileAttributes =
  36021. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  36022. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  36023. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  36024. extendedParameters.lpSecurityAttributes = NULL;
  36025. extendedParameters.hTemplateFile = NULL;
  36026. while( (h = osCreateFile2((LPCWSTR)zConverted,
  36027. dwDesiredAccess,
  36028. dwShareMode,
  36029. dwCreationDisposition,
  36030. &extendedParameters))==INVALID_HANDLE_VALUE &&
  36031. winRetryIoerr(&cnt, &lastErrno) ){
  36032. /* Noop */
  36033. }
  36034. #else
  36035. while( (h = osCreateFileW((LPCWSTR)zConverted,
  36036. dwDesiredAccess,
  36037. dwShareMode, NULL,
  36038. dwCreationDisposition,
  36039. dwFlagsAndAttributes,
  36040. NULL))==INVALID_HANDLE_VALUE &&
  36041. winRetryIoerr(&cnt, &lastErrno) ){
  36042. /* Noop */
  36043. }
  36044. #endif
  36045. }
  36046. #ifdef SQLITE_WIN32_HAS_ANSI
  36047. else{
  36048. while( (h = osCreateFileA((LPCSTR)zConverted,
  36049. dwDesiredAccess,
  36050. dwShareMode, NULL,
  36051. dwCreationDisposition,
  36052. dwFlagsAndAttributes,
  36053. NULL))==INVALID_HANDLE_VALUE &&
  36054. winRetryIoerr(&cnt, &lastErrno) ){
  36055. /* Noop */
  36056. }
  36057. }
  36058. #endif
  36059. winLogIoerr(cnt, __LINE__);
  36060. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  36061. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  36062. if( h==INVALID_HANDLE_VALUE ){
  36063. pFile->lastErrno = lastErrno;
  36064. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  36065. sqlite3_free(zConverted);
  36066. sqlite3_free(zTmpname);
  36067. if( isReadWrite && !isExclusive ){
  36068. return winOpen(pVfs, zName, id,
  36069. ((flags|SQLITE_OPEN_READONLY) &
  36070. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  36071. pOutFlags);
  36072. }else{
  36073. return SQLITE_CANTOPEN_BKPT;
  36074. }
  36075. }
  36076. if( pOutFlags ){
  36077. if( isReadWrite ){
  36078. *pOutFlags = SQLITE_OPEN_READWRITE;
  36079. }else{
  36080. *pOutFlags = SQLITE_OPEN_READONLY;
  36081. }
  36082. }
  36083. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  36084. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  36085. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  36086. #if SQLITE_OS_WINCE
  36087. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  36088. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  36089. ){
  36090. osCloseHandle(h);
  36091. sqlite3_free(zConverted);
  36092. sqlite3_free(zTmpname);
  36093. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  36094. return rc;
  36095. }
  36096. if( isTemp ){
  36097. pFile->zDeleteOnClose = zConverted;
  36098. }else
  36099. #endif
  36100. {
  36101. sqlite3_free(zConverted);
  36102. }
  36103. sqlite3_free(zTmpname);
  36104. pFile->pMethod = &winIoMethod;
  36105. pFile->pVfs = pVfs;
  36106. pFile->h = h;
  36107. if( isReadonly ){
  36108. pFile->ctrlFlags |= WINFILE_RDONLY;
  36109. }
  36110. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  36111. pFile->ctrlFlags |= WINFILE_PSOW;
  36112. }
  36113. pFile->lastErrno = NO_ERROR;
  36114. pFile->zPath = zName;
  36115. #if SQLITE_MAX_MMAP_SIZE>0
  36116. pFile->hMap = NULL;
  36117. pFile->pMapRegion = 0;
  36118. pFile->mmapSize = 0;
  36119. pFile->mmapSizeActual = 0;
  36120. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  36121. #endif
  36122. OpenCounter(+1);
  36123. return rc;
  36124. }
  36125. /*
  36126. ** Delete the named file.
  36127. **
  36128. ** Note that Windows does not allow a file to be deleted if some other
  36129. ** process has it open. Sometimes a virus scanner or indexing program
  36130. ** will open a journal file shortly after it is created in order to do
  36131. ** whatever it does. While this other process is holding the
  36132. ** file open, we will be unable to delete it. To work around this
  36133. ** problem, we delay 100 milliseconds and try to delete again. Up
  36134. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  36135. ** up and returning an error.
  36136. */
  36137. static int winDelete(
  36138. sqlite3_vfs *pVfs, /* Not used on win32 */
  36139. const char *zFilename, /* Name of file to delete */
  36140. int syncDir /* Not used on win32 */
  36141. ){
  36142. int cnt = 0;
  36143. int rc;
  36144. DWORD attr;
  36145. DWORD lastErrno = 0;
  36146. void *zConverted;
  36147. UNUSED_PARAMETER(pVfs);
  36148. UNUSED_PARAMETER(syncDir);
  36149. SimulateIOError(return SQLITE_IOERR_DELETE);
  36150. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  36151. zConverted = winConvertFromUtf8Filename(zFilename);
  36152. if( zConverted==0 ){
  36153. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  36154. return SQLITE_IOERR_NOMEM;
  36155. }
  36156. if( osIsNT() ){
  36157. do {
  36158. #if SQLITE_OS_WINRT
  36159. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  36160. memset(&sAttrData, 0, sizeof(sAttrData));
  36161. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  36162. &sAttrData) ){
  36163. attr = sAttrData.dwFileAttributes;
  36164. }else{
  36165. lastErrno = osGetLastError();
  36166. if( lastErrno==ERROR_FILE_NOT_FOUND
  36167. || lastErrno==ERROR_PATH_NOT_FOUND ){
  36168. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  36169. }else{
  36170. rc = SQLITE_ERROR;
  36171. }
  36172. break;
  36173. }
  36174. #else
  36175. attr = osGetFileAttributesW(zConverted);
  36176. #endif
  36177. if ( attr==INVALID_FILE_ATTRIBUTES ){
  36178. lastErrno = osGetLastError();
  36179. if( lastErrno==ERROR_FILE_NOT_FOUND
  36180. || lastErrno==ERROR_PATH_NOT_FOUND ){
  36181. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  36182. }else{
  36183. rc = SQLITE_ERROR;
  36184. }
  36185. break;
  36186. }
  36187. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  36188. rc = SQLITE_ERROR; /* Files only. */
  36189. break;
  36190. }
  36191. if ( osDeleteFileW(zConverted) ){
  36192. rc = SQLITE_OK; /* Deleted OK. */
  36193. break;
  36194. }
  36195. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  36196. rc = SQLITE_ERROR; /* No more retries. */
  36197. break;
  36198. }
  36199. } while(1);
  36200. }
  36201. #ifdef SQLITE_WIN32_HAS_ANSI
  36202. else{
  36203. do {
  36204. attr = osGetFileAttributesA(zConverted);
  36205. if ( attr==INVALID_FILE_ATTRIBUTES ){
  36206. lastErrno = osGetLastError();
  36207. if( lastErrno==ERROR_FILE_NOT_FOUND
  36208. || lastErrno==ERROR_PATH_NOT_FOUND ){
  36209. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  36210. }else{
  36211. rc = SQLITE_ERROR;
  36212. }
  36213. break;
  36214. }
  36215. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  36216. rc = SQLITE_ERROR; /* Files only. */
  36217. break;
  36218. }
  36219. if ( osDeleteFileA(zConverted) ){
  36220. rc = SQLITE_OK; /* Deleted OK. */
  36221. break;
  36222. }
  36223. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  36224. rc = SQLITE_ERROR; /* No more retries. */
  36225. break;
  36226. }
  36227. } while(1);
  36228. }
  36229. #endif
  36230. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  36231. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  36232. }else{
  36233. winLogIoerr(cnt, __LINE__);
  36234. }
  36235. sqlite3_free(zConverted);
  36236. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  36237. return rc;
  36238. }
  36239. /*
  36240. ** Check the existence and status of a file.
  36241. */
  36242. static int winAccess(
  36243. sqlite3_vfs *pVfs, /* Not used on win32 */
  36244. const char *zFilename, /* Name of file to check */
  36245. int flags, /* Type of test to make on this file */
  36246. int *pResOut /* OUT: Result */
  36247. ){
  36248. DWORD attr;
  36249. int rc = 0;
  36250. DWORD lastErrno = 0;
  36251. void *zConverted;
  36252. UNUSED_PARAMETER(pVfs);
  36253. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  36254. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  36255. zFilename, flags, pResOut));
  36256. zConverted = winConvertFromUtf8Filename(zFilename);
  36257. if( zConverted==0 ){
  36258. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  36259. return SQLITE_IOERR_NOMEM;
  36260. }
  36261. if( osIsNT() ){
  36262. int cnt = 0;
  36263. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  36264. memset(&sAttrData, 0, sizeof(sAttrData));
  36265. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  36266. GetFileExInfoStandard,
  36267. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  36268. if( rc ){
  36269. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  36270. ** as if it does not exist.
  36271. */
  36272. if( flags==SQLITE_ACCESS_EXISTS
  36273. && sAttrData.nFileSizeHigh==0
  36274. && sAttrData.nFileSizeLow==0 ){
  36275. attr = INVALID_FILE_ATTRIBUTES;
  36276. }else{
  36277. attr = sAttrData.dwFileAttributes;
  36278. }
  36279. }else{
  36280. winLogIoerr(cnt, __LINE__);
  36281. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  36282. sqlite3_free(zConverted);
  36283. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  36284. zFilename);
  36285. }else{
  36286. attr = INVALID_FILE_ATTRIBUTES;
  36287. }
  36288. }
  36289. }
  36290. #ifdef SQLITE_WIN32_HAS_ANSI
  36291. else{
  36292. attr = osGetFileAttributesA((char*)zConverted);
  36293. }
  36294. #endif
  36295. sqlite3_free(zConverted);
  36296. switch( flags ){
  36297. case SQLITE_ACCESS_READ:
  36298. case SQLITE_ACCESS_EXISTS:
  36299. rc = attr!=INVALID_FILE_ATTRIBUTES;
  36300. break;
  36301. case SQLITE_ACCESS_READWRITE:
  36302. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  36303. (attr & FILE_ATTRIBUTE_READONLY)==0;
  36304. break;
  36305. default:
  36306. assert(!"Invalid flags argument");
  36307. }
  36308. *pResOut = rc;
  36309. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  36310. zFilename, pResOut, *pResOut));
  36311. return SQLITE_OK;
  36312. }
  36313. /*
  36314. ** Returns non-zero if the specified path name starts with a drive letter
  36315. ** followed by a colon character.
  36316. */
  36317. static BOOL winIsDriveLetterAndColon(
  36318. const char *zPathname
  36319. ){
  36320. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  36321. }
  36322. /*
  36323. ** Returns non-zero if the specified path name should be used verbatim. If
  36324. ** non-zero is returned from this function, the calling function must simply
  36325. ** use the provided path name verbatim -OR- resolve it into a full path name
  36326. ** using the GetFullPathName Win32 API function (if available).
  36327. */
  36328. static BOOL winIsVerbatimPathname(
  36329. const char *zPathname
  36330. ){
  36331. /*
  36332. ** If the path name starts with a forward slash or a backslash, it is either
  36333. ** a legal UNC name, a volume relative path, or an absolute path name in the
  36334. ** "Unix" format on Windows. There is no easy way to differentiate between
  36335. ** the final two cases; therefore, we return the safer return value of TRUE
  36336. ** so that callers of this function will simply use it verbatim.
  36337. */
  36338. if ( winIsDirSep(zPathname[0]) ){
  36339. return TRUE;
  36340. }
  36341. /*
  36342. ** If the path name starts with a letter and a colon it is either a volume
  36343. ** relative path or an absolute path. Callers of this function must not
  36344. ** attempt to treat it as a relative path name (i.e. they should simply use
  36345. ** it verbatim).
  36346. */
  36347. if ( winIsDriveLetterAndColon(zPathname) ){
  36348. return TRUE;
  36349. }
  36350. /*
  36351. ** If we get to this point, the path name should almost certainly be a purely
  36352. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  36353. */
  36354. return FALSE;
  36355. }
  36356. /*
  36357. ** Turn a relative pathname into a full pathname. Write the full
  36358. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  36359. ** bytes in size.
  36360. */
  36361. static int winFullPathname(
  36362. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36363. const char *zRelative, /* Possibly relative input path */
  36364. int nFull, /* Size of output buffer in bytes */
  36365. char *zFull /* Output buffer */
  36366. ){
  36367. #if defined(__CYGWIN__)
  36368. SimulateIOError( return SQLITE_ERROR );
  36369. UNUSED_PARAMETER(nFull);
  36370. assert( nFull>=pVfs->mxPathname );
  36371. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  36372. /*
  36373. ** NOTE: We are dealing with a relative path name and the data
  36374. ** directory has been set. Therefore, use it as the basis
  36375. ** for converting the relative path name to an absolute
  36376. ** one by prepending the data directory and a slash.
  36377. */
  36378. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  36379. if( !zOut ){
  36380. return SQLITE_IOERR_NOMEM;
  36381. }
  36382. if( cygwin_conv_path(
  36383. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  36384. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  36385. sqlite3_free(zOut);
  36386. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  36387. "winFullPathname1", zRelative);
  36388. }else{
  36389. char *zUtf8 = winConvertToUtf8Filename(zOut);
  36390. if( !zUtf8 ){
  36391. sqlite3_free(zOut);
  36392. return SQLITE_IOERR_NOMEM;
  36393. }
  36394. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  36395. sqlite3_data_directory, winGetDirSep(), zUtf8);
  36396. sqlite3_free(zUtf8);
  36397. sqlite3_free(zOut);
  36398. }
  36399. }else{
  36400. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  36401. if( !zOut ){
  36402. return SQLITE_IOERR_NOMEM;
  36403. }
  36404. if( cygwin_conv_path(
  36405. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  36406. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  36407. sqlite3_free(zOut);
  36408. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  36409. "winFullPathname2", zRelative);
  36410. }else{
  36411. char *zUtf8 = winConvertToUtf8Filename(zOut);
  36412. if( !zUtf8 ){
  36413. sqlite3_free(zOut);
  36414. return SQLITE_IOERR_NOMEM;
  36415. }
  36416. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  36417. sqlite3_free(zUtf8);
  36418. sqlite3_free(zOut);
  36419. }
  36420. }
  36421. return SQLITE_OK;
  36422. #endif
  36423. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  36424. SimulateIOError( return SQLITE_ERROR );
  36425. /* WinCE has no concept of a relative pathname, or so I am told. */
  36426. /* WinRT has no way to convert a relative path to an absolute one. */
  36427. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  36428. /*
  36429. ** NOTE: We are dealing with a relative path name and the data
  36430. ** directory has been set. Therefore, use it as the basis
  36431. ** for converting the relative path name to an absolute
  36432. ** one by prepending the data directory and a backslash.
  36433. */
  36434. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  36435. sqlite3_data_directory, winGetDirSep(), zRelative);
  36436. }else{
  36437. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  36438. }
  36439. return SQLITE_OK;
  36440. #endif
  36441. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  36442. DWORD nByte;
  36443. void *zConverted;
  36444. char *zOut;
  36445. /* If this path name begins with "/X:", where "X" is any alphabetic
  36446. ** character, discard the initial "/" from the pathname.
  36447. */
  36448. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  36449. zRelative++;
  36450. }
  36451. /* It's odd to simulate an io-error here, but really this is just
  36452. ** using the io-error infrastructure to test that SQLite handles this
  36453. ** function failing. This function could fail if, for example, the
  36454. ** current working directory has been unlinked.
  36455. */
  36456. SimulateIOError( return SQLITE_ERROR );
  36457. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  36458. /*
  36459. ** NOTE: We are dealing with a relative path name and the data
  36460. ** directory has been set. Therefore, use it as the basis
  36461. ** for converting the relative path name to an absolute
  36462. ** one by prepending the data directory and a backslash.
  36463. */
  36464. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  36465. sqlite3_data_directory, winGetDirSep(), zRelative);
  36466. return SQLITE_OK;
  36467. }
  36468. zConverted = winConvertFromUtf8Filename(zRelative);
  36469. if( zConverted==0 ){
  36470. return SQLITE_IOERR_NOMEM;
  36471. }
  36472. if( osIsNT() ){
  36473. LPWSTR zTemp;
  36474. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  36475. if( nByte==0 ){
  36476. sqlite3_free(zConverted);
  36477. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  36478. "winFullPathname1", zRelative);
  36479. }
  36480. nByte += 3;
  36481. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  36482. if( zTemp==0 ){
  36483. sqlite3_free(zConverted);
  36484. return SQLITE_IOERR_NOMEM;
  36485. }
  36486. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  36487. if( nByte==0 ){
  36488. sqlite3_free(zConverted);
  36489. sqlite3_free(zTemp);
  36490. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  36491. "winFullPathname2", zRelative);
  36492. }
  36493. sqlite3_free(zConverted);
  36494. zOut = winUnicodeToUtf8(zTemp);
  36495. sqlite3_free(zTemp);
  36496. }
  36497. #ifdef SQLITE_WIN32_HAS_ANSI
  36498. else{
  36499. char *zTemp;
  36500. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  36501. if( nByte==0 ){
  36502. sqlite3_free(zConverted);
  36503. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  36504. "winFullPathname3", zRelative);
  36505. }
  36506. nByte += 3;
  36507. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  36508. if( zTemp==0 ){
  36509. sqlite3_free(zConverted);
  36510. return SQLITE_IOERR_NOMEM;
  36511. }
  36512. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  36513. if( nByte==0 ){
  36514. sqlite3_free(zConverted);
  36515. sqlite3_free(zTemp);
  36516. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  36517. "winFullPathname4", zRelative);
  36518. }
  36519. sqlite3_free(zConverted);
  36520. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  36521. sqlite3_free(zTemp);
  36522. }
  36523. #endif
  36524. if( zOut ){
  36525. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  36526. sqlite3_free(zOut);
  36527. return SQLITE_OK;
  36528. }else{
  36529. return SQLITE_IOERR_NOMEM;
  36530. }
  36531. #endif
  36532. }
  36533. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36534. /*
  36535. ** Interfaces for opening a shared library, finding entry points
  36536. ** within the shared library, and closing the shared library.
  36537. */
  36538. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  36539. HANDLE h;
  36540. #if defined(__CYGWIN__)
  36541. int nFull = pVfs->mxPathname+1;
  36542. char *zFull = sqlite3MallocZero( nFull );
  36543. void *zConverted = 0;
  36544. if( zFull==0 ){
  36545. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  36546. return 0;
  36547. }
  36548. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  36549. sqlite3_free(zFull);
  36550. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  36551. return 0;
  36552. }
  36553. zConverted = winConvertFromUtf8Filename(zFull);
  36554. sqlite3_free(zFull);
  36555. #else
  36556. void *zConverted = winConvertFromUtf8Filename(zFilename);
  36557. UNUSED_PARAMETER(pVfs);
  36558. #endif
  36559. if( zConverted==0 ){
  36560. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  36561. return 0;
  36562. }
  36563. if( osIsNT() ){
  36564. #if SQLITE_OS_WINRT
  36565. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  36566. #else
  36567. h = osLoadLibraryW((LPCWSTR)zConverted);
  36568. #endif
  36569. }
  36570. #ifdef SQLITE_WIN32_HAS_ANSI
  36571. else{
  36572. h = osLoadLibraryA((char*)zConverted);
  36573. }
  36574. #endif
  36575. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  36576. sqlite3_free(zConverted);
  36577. return (void*)h;
  36578. }
  36579. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  36580. UNUSED_PARAMETER(pVfs);
  36581. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  36582. }
  36583. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  36584. FARPROC proc;
  36585. UNUSED_PARAMETER(pVfs);
  36586. proc = osGetProcAddressA((HANDLE)pH, zSym);
  36587. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  36588. (void*)pH, zSym, (void*)proc));
  36589. return (void(*)(void))proc;
  36590. }
  36591. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  36592. UNUSED_PARAMETER(pVfs);
  36593. osFreeLibrary((HANDLE)pHandle);
  36594. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  36595. }
  36596. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  36597. #define winDlOpen 0
  36598. #define winDlError 0
  36599. #define winDlSym 0
  36600. #define winDlClose 0
  36601. #endif
  36602. /*
  36603. ** Write up to nBuf bytes of randomness into zBuf.
  36604. */
  36605. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  36606. int n = 0;
  36607. UNUSED_PARAMETER(pVfs);
  36608. #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
  36609. n = nBuf;
  36610. memset(zBuf, 0, nBuf);
  36611. #else
  36612. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  36613. SYSTEMTIME x;
  36614. osGetSystemTime(&x);
  36615. memcpy(&zBuf[n], &x, sizeof(x));
  36616. n += sizeof(x);
  36617. }
  36618. if( sizeof(DWORD)<=nBuf-n ){
  36619. DWORD pid = osGetCurrentProcessId();
  36620. memcpy(&zBuf[n], &pid, sizeof(pid));
  36621. n += sizeof(pid);
  36622. }
  36623. #if SQLITE_OS_WINRT
  36624. if( sizeof(ULONGLONG)<=nBuf-n ){
  36625. ULONGLONG cnt = osGetTickCount64();
  36626. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  36627. n += sizeof(cnt);
  36628. }
  36629. #else
  36630. if( sizeof(DWORD)<=nBuf-n ){
  36631. DWORD cnt = osGetTickCount();
  36632. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  36633. n += sizeof(cnt);
  36634. }
  36635. #endif
  36636. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  36637. LARGE_INTEGER i;
  36638. osQueryPerformanceCounter(&i);
  36639. memcpy(&zBuf[n], &i, sizeof(i));
  36640. n += sizeof(i);
  36641. }
  36642. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
  36643. if( sizeof(UUID)<=nBuf-n ){
  36644. UUID id;
  36645. memset(&id, 0, sizeof(UUID));
  36646. osUuidCreate(&id);
  36647. memcpy(&zBuf[n], &id, sizeof(UUID));
  36648. n += sizeof(UUID);
  36649. }
  36650. if( sizeof(UUID)<=nBuf-n ){
  36651. UUID id;
  36652. memset(&id, 0, sizeof(UUID));
  36653. osUuidCreateSequential(&id);
  36654. memcpy(&zBuf[n], &id, sizeof(UUID));
  36655. n += sizeof(UUID);
  36656. }
  36657. #endif
  36658. #endif /* defined(SQLITE_TEST) || defined(SQLITE_ZERO_PRNG_SEED) */
  36659. return n;
  36660. }
  36661. /*
  36662. ** Sleep for a little while. Return the amount of time slept.
  36663. */
  36664. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  36665. sqlite3_win32_sleep((microsec+999)/1000);
  36666. UNUSED_PARAMETER(pVfs);
  36667. return ((microsec+999)/1000)*1000;
  36668. }
  36669. /*
  36670. ** The following variable, if set to a non-zero value, is interpreted as
  36671. ** the number of seconds since 1970 and is used to set the result of
  36672. ** sqlite3OsCurrentTime() during testing.
  36673. */
  36674. #ifdef SQLITE_TEST
  36675. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  36676. #endif
  36677. /*
  36678. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  36679. ** the current time and date as a Julian Day number times 86_400_000. In
  36680. ** other words, write into *piNow the number of milliseconds since the Julian
  36681. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  36682. ** proleptic Gregorian calendar.
  36683. **
  36684. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  36685. ** cannot be found.
  36686. */
  36687. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  36688. /* FILETIME structure is a 64-bit value representing the number of
  36689. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  36690. */
  36691. FILETIME ft;
  36692. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  36693. #ifdef SQLITE_TEST
  36694. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  36695. #endif
  36696. /* 2^32 - to avoid use of LL and warnings in gcc */
  36697. static const sqlite3_int64 max32BitValue =
  36698. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  36699. (sqlite3_int64)294967296;
  36700. #if SQLITE_OS_WINCE
  36701. SYSTEMTIME time;
  36702. osGetSystemTime(&time);
  36703. /* if SystemTimeToFileTime() fails, it returns zero. */
  36704. if (!osSystemTimeToFileTime(&time,&ft)){
  36705. return SQLITE_ERROR;
  36706. }
  36707. #else
  36708. osGetSystemTimeAsFileTime( &ft );
  36709. #endif
  36710. *piNow = winFiletimeEpoch +
  36711. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  36712. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  36713. #ifdef SQLITE_TEST
  36714. if( sqlite3_current_time ){
  36715. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  36716. }
  36717. #endif
  36718. UNUSED_PARAMETER(pVfs);
  36719. return SQLITE_OK;
  36720. }
  36721. /*
  36722. ** Find the current time (in Universal Coordinated Time). Write the
  36723. ** current time and date as a Julian Day number into *prNow and
  36724. ** return 0. Return 1 if the time and date cannot be found.
  36725. */
  36726. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  36727. int rc;
  36728. sqlite3_int64 i;
  36729. rc = winCurrentTimeInt64(pVfs, &i);
  36730. if( !rc ){
  36731. *prNow = i/86400000.0;
  36732. }
  36733. return rc;
  36734. }
  36735. /*
  36736. ** The idea is that this function works like a combination of
  36737. ** GetLastError() and FormatMessage() on Windows (or errno and
  36738. ** strerror_r() on Unix). After an error is returned by an OS
  36739. ** function, SQLite calls this function with zBuf pointing to
  36740. ** a buffer of nBuf bytes. The OS layer should populate the
  36741. ** buffer with a nul-terminated UTF-8 encoded error message
  36742. ** describing the last IO error to have occurred within the calling
  36743. ** thread.
  36744. **
  36745. ** If the error message is too large for the supplied buffer,
  36746. ** it should be truncated. The return value of xGetLastError
  36747. ** is zero if the error message fits in the buffer, or non-zero
  36748. ** otherwise (if the message was truncated). If non-zero is returned,
  36749. ** then it is not necessary to include the nul-terminator character
  36750. ** in the output buffer.
  36751. **
  36752. ** Not supplying an error message will have no adverse effect
  36753. ** on SQLite. It is fine to have an implementation that never
  36754. ** returns an error message:
  36755. **
  36756. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  36757. ** assert(zBuf[0]=='\0');
  36758. ** return 0;
  36759. ** }
  36760. **
  36761. ** However if an error message is supplied, it will be incorporated
  36762. ** by sqlite into the error message available to the user using
  36763. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  36764. */
  36765. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  36766. UNUSED_PARAMETER(pVfs);
  36767. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  36768. }
  36769. /*
  36770. ** Initialize and deinitialize the operating system interface.
  36771. */
  36772. SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
  36773. static sqlite3_vfs winVfs = {
  36774. 3, /* iVersion */
  36775. sizeof(winFile), /* szOsFile */
  36776. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  36777. 0, /* pNext */
  36778. "win32", /* zName */
  36779. 0, /* pAppData */
  36780. winOpen, /* xOpen */
  36781. winDelete, /* xDelete */
  36782. winAccess, /* xAccess */
  36783. winFullPathname, /* xFullPathname */
  36784. winDlOpen, /* xDlOpen */
  36785. winDlError, /* xDlError */
  36786. winDlSym, /* xDlSym */
  36787. winDlClose, /* xDlClose */
  36788. winRandomness, /* xRandomness */
  36789. winSleep, /* xSleep */
  36790. winCurrentTime, /* xCurrentTime */
  36791. winGetLastError, /* xGetLastError */
  36792. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  36793. winSetSystemCall, /* xSetSystemCall */
  36794. winGetSystemCall, /* xGetSystemCall */
  36795. winNextSystemCall, /* xNextSystemCall */
  36796. };
  36797. #if defined(SQLITE_WIN32_HAS_WIDE)
  36798. static sqlite3_vfs winLongPathVfs = {
  36799. 3, /* iVersion */
  36800. sizeof(winFile), /* szOsFile */
  36801. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  36802. 0, /* pNext */
  36803. "win32-longpath", /* zName */
  36804. 0, /* pAppData */
  36805. winOpen, /* xOpen */
  36806. winDelete, /* xDelete */
  36807. winAccess, /* xAccess */
  36808. winFullPathname, /* xFullPathname */
  36809. winDlOpen, /* xDlOpen */
  36810. winDlError, /* xDlError */
  36811. winDlSym, /* xDlSym */
  36812. winDlClose, /* xDlClose */
  36813. winRandomness, /* xRandomness */
  36814. winSleep, /* xSleep */
  36815. winCurrentTime, /* xCurrentTime */
  36816. winGetLastError, /* xGetLastError */
  36817. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  36818. winSetSystemCall, /* xSetSystemCall */
  36819. winGetSystemCall, /* xGetSystemCall */
  36820. winNextSystemCall, /* xNextSystemCall */
  36821. };
  36822. #endif
  36823. /* Double-check that the aSyscall[] array has been constructed
  36824. ** correctly. See ticket [bb3a86e890c8e96ab] */
  36825. assert( ArraySize(aSyscall)==80 );
  36826. /* get memory map allocation granularity */
  36827. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  36828. #if SQLITE_OS_WINRT
  36829. osGetNativeSystemInfo(&winSysInfo);
  36830. #else
  36831. osGetSystemInfo(&winSysInfo);
  36832. #endif
  36833. assert( winSysInfo.dwAllocationGranularity>0 );
  36834. assert( winSysInfo.dwPageSize>0 );
  36835. sqlite3_vfs_register(&winVfs, 1);
  36836. #if defined(SQLITE_WIN32_HAS_WIDE)
  36837. sqlite3_vfs_register(&winLongPathVfs, 0);
  36838. #endif
  36839. return SQLITE_OK;
  36840. }
  36841. SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
  36842. #if SQLITE_OS_WINRT
  36843. if( sleepObj!=NULL ){
  36844. osCloseHandle(sleepObj);
  36845. sleepObj = NULL;
  36846. }
  36847. #endif
  36848. return SQLITE_OK;
  36849. }
  36850. #endif /* SQLITE_OS_WIN */
  36851. /************** End of os_win.c **********************************************/
  36852. /************** Begin file bitvec.c ******************************************/
  36853. /*
  36854. ** 2008 February 16
  36855. **
  36856. ** The author disclaims copyright to this source code. In place of
  36857. ** a legal notice, here is a blessing:
  36858. **
  36859. ** May you do good and not evil.
  36860. ** May you find forgiveness for yourself and forgive others.
  36861. ** May you share freely, never taking more than you give.
  36862. **
  36863. *************************************************************************
  36864. ** This file implements an object that represents a fixed-length
  36865. ** bitmap. Bits are numbered starting with 1.
  36866. **
  36867. ** A bitmap is used to record which pages of a database file have been
  36868. ** journalled during a transaction, or which pages have the "dont-write"
  36869. ** property. Usually only a few pages are meet either condition.
  36870. ** So the bitmap is usually sparse and has low cardinality.
  36871. ** But sometimes (for example when during a DROP of a large table) most
  36872. ** or all of the pages in a database can get journalled. In those cases,
  36873. ** the bitmap becomes dense with high cardinality. The algorithm needs
  36874. ** to handle both cases well.
  36875. **
  36876. ** The size of the bitmap is fixed when the object is created.
  36877. **
  36878. ** All bits are clear when the bitmap is created. Individual bits
  36879. ** may be set or cleared one at a time.
  36880. **
  36881. ** Test operations are about 100 times more common that set operations.
  36882. ** Clear operations are exceedingly rare. There are usually between
  36883. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  36884. ** sometimes grow into tens of thousands or larger. The size of the
  36885. ** Bitvec object is the number of pages in the database file at the
  36886. ** start of a transaction, and is thus usually less than a few thousand,
  36887. ** but can be as large as 2 billion for a really big database.
  36888. */
  36889. /* #include "sqliteInt.h" */
  36890. /* Size of the Bitvec structure in bytes. */
  36891. #define BITVEC_SZ 512
  36892. /* Round the union size down to the nearest pointer boundary, since that's how
  36893. ** it will be aligned within the Bitvec struct. */
  36894. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  36895. /* Type of the array "element" for the bitmap representation.
  36896. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  36897. ** Setting this to the "natural word" size of your CPU may improve
  36898. ** performance. */
  36899. #define BITVEC_TELEM u8
  36900. /* Size, in bits, of the bitmap element. */
  36901. #define BITVEC_SZELEM 8
  36902. /* Number of elements in a bitmap array. */
  36903. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  36904. /* Number of bits in the bitmap array. */
  36905. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  36906. /* Number of u32 values in hash table. */
  36907. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  36908. /* Maximum number of entries in hash table before
  36909. ** sub-dividing and re-hashing. */
  36910. #define BITVEC_MXHASH (BITVEC_NINT/2)
  36911. /* Hashing function for the aHash representation.
  36912. ** Empirical testing showed that the *37 multiplier
  36913. ** (an arbitrary prime)in the hash function provided
  36914. ** no fewer collisions than the no-op *1. */
  36915. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  36916. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  36917. /*
  36918. ** A bitmap is an instance of the following structure.
  36919. **
  36920. ** This bitmap records the existence of zero or more bits
  36921. ** with values between 1 and iSize, inclusive.
  36922. **
  36923. ** There are three possible representations of the bitmap.
  36924. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  36925. ** bitmap. The least significant bit is bit 1.
  36926. **
  36927. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  36928. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  36929. **
  36930. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  36931. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  36932. ** handles up to iDivisor separate values of i. apSub[0] holds
  36933. ** values between 1 and iDivisor. apSub[1] holds values between
  36934. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  36935. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  36936. ** to hold deal with values between 1 and iDivisor.
  36937. */
  36938. struct Bitvec {
  36939. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  36940. u32 nSet; /* Number of bits that are set - only valid for aHash
  36941. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  36942. ** this would be 125. */
  36943. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  36944. /* Should >=0 for apSub element. */
  36945. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  36946. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  36947. union {
  36948. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  36949. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  36950. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  36951. } u;
  36952. };
  36953. /*
  36954. ** Create a new bitmap object able to handle bits between 0 and iSize,
  36955. ** inclusive. Return a pointer to the new object. Return NULL if
  36956. ** malloc fails.
  36957. */
  36958. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  36959. Bitvec *p;
  36960. assert( sizeof(*p)==BITVEC_SZ );
  36961. p = sqlite3MallocZero( sizeof(*p) );
  36962. if( p ){
  36963. p->iSize = iSize;
  36964. }
  36965. return p;
  36966. }
  36967. /*
  36968. ** Check to see if the i-th bit is set. Return true or false.
  36969. ** If p is NULL (if the bitmap has not been created) or if
  36970. ** i is out of range, then return false.
  36971. */
  36972. SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *p, u32 i){
  36973. assert( p!=0 );
  36974. i--;
  36975. if( i>=p->iSize ) return 0;
  36976. while( p->iDivisor ){
  36977. u32 bin = i/p->iDivisor;
  36978. i = i%p->iDivisor;
  36979. p = p->u.apSub[bin];
  36980. if (!p) {
  36981. return 0;
  36982. }
  36983. }
  36984. if( p->iSize<=BITVEC_NBIT ){
  36985. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  36986. } else{
  36987. u32 h = BITVEC_HASH(i++);
  36988. while( p->u.aHash[h] ){
  36989. if( p->u.aHash[h]==i ) return 1;
  36990. h = (h+1) % BITVEC_NINT;
  36991. }
  36992. return 0;
  36993. }
  36994. }
  36995. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  36996. return p!=0 && sqlite3BitvecTestNotNull(p,i);
  36997. }
  36998. /*
  36999. ** Set the i-th bit. Return 0 on success and an error code if
  37000. ** anything goes wrong.
  37001. **
  37002. ** This routine might cause sub-bitmaps to be allocated. Failing
  37003. ** to get the memory needed to hold the sub-bitmap is the only
  37004. ** that can go wrong with an insert, assuming p and i are valid.
  37005. **
  37006. ** The calling function must ensure that p is a valid Bitvec object
  37007. ** and that the value for "i" is within range of the Bitvec object.
  37008. ** Otherwise the behavior is undefined.
  37009. */
  37010. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  37011. u32 h;
  37012. if( p==0 ) return SQLITE_OK;
  37013. assert( i>0 );
  37014. assert( i<=p->iSize );
  37015. i--;
  37016. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  37017. u32 bin = i/p->iDivisor;
  37018. i = i%p->iDivisor;
  37019. if( p->u.apSub[bin]==0 ){
  37020. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  37021. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  37022. }
  37023. p = p->u.apSub[bin];
  37024. }
  37025. if( p->iSize<=BITVEC_NBIT ){
  37026. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  37027. return SQLITE_OK;
  37028. }
  37029. h = BITVEC_HASH(i++);
  37030. /* if there wasn't a hash collision, and this doesn't */
  37031. /* completely fill the hash, then just add it without */
  37032. /* worring about sub-dividing and re-hashing. */
  37033. if( !p->u.aHash[h] ){
  37034. if (p->nSet<(BITVEC_NINT-1)) {
  37035. goto bitvec_set_end;
  37036. } else {
  37037. goto bitvec_set_rehash;
  37038. }
  37039. }
  37040. /* there was a collision, check to see if it's already */
  37041. /* in hash, if not, try to find a spot for it */
  37042. do {
  37043. if( p->u.aHash[h]==i ) return SQLITE_OK;
  37044. h++;
  37045. if( h>=BITVEC_NINT ) h = 0;
  37046. } while( p->u.aHash[h] );
  37047. /* we didn't find it in the hash. h points to the first */
  37048. /* available free spot. check to see if this is going to */
  37049. /* make our hash too "full". */
  37050. bitvec_set_rehash:
  37051. if( p->nSet>=BITVEC_MXHASH ){
  37052. unsigned int j;
  37053. int rc;
  37054. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  37055. if( aiValues==0 ){
  37056. return SQLITE_NOMEM;
  37057. }else{
  37058. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  37059. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  37060. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  37061. rc = sqlite3BitvecSet(p, i);
  37062. for(j=0; j<BITVEC_NINT; j++){
  37063. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  37064. }
  37065. sqlite3StackFree(0, aiValues);
  37066. return rc;
  37067. }
  37068. }
  37069. bitvec_set_end:
  37070. p->nSet++;
  37071. p->u.aHash[h] = i;
  37072. return SQLITE_OK;
  37073. }
  37074. /*
  37075. ** Clear the i-th bit.
  37076. **
  37077. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  37078. ** that BitvecClear can use to rebuilt its hash table.
  37079. */
  37080. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  37081. if( p==0 ) return;
  37082. assert( i>0 );
  37083. i--;
  37084. while( p->iDivisor ){
  37085. u32 bin = i/p->iDivisor;
  37086. i = i%p->iDivisor;
  37087. p = p->u.apSub[bin];
  37088. if (!p) {
  37089. return;
  37090. }
  37091. }
  37092. if( p->iSize<=BITVEC_NBIT ){
  37093. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  37094. }else{
  37095. unsigned int j;
  37096. u32 *aiValues = pBuf;
  37097. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  37098. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  37099. p->nSet = 0;
  37100. for(j=0; j<BITVEC_NINT; j++){
  37101. if( aiValues[j] && aiValues[j]!=(i+1) ){
  37102. u32 h = BITVEC_HASH(aiValues[j]-1);
  37103. p->nSet++;
  37104. while( p->u.aHash[h] ){
  37105. h++;
  37106. if( h>=BITVEC_NINT ) h = 0;
  37107. }
  37108. p->u.aHash[h] = aiValues[j];
  37109. }
  37110. }
  37111. }
  37112. }
  37113. /*
  37114. ** Destroy a bitmap object. Reclaim all memory used.
  37115. */
  37116. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  37117. if( p==0 ) return;
  37118. if( p->iDivisor ){
  37119. unsigned int i;
  37120. for(i=0; i<BITVEC_NPTR; i++){
  37121. sqlite3BitvecDestroy(p->u.apSub[i]);
  37122. }
  37123. }
  37124. sqlite3_free(p);
  37125. }
  37126. /*
  37127. ** Return the value of the iSize parameter specified when Bitvec *p
  37128. ** was created.
  37129. */
  37130. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  37131. return p->iSize;
  37132. }
  37133. #ifndef SQLITE_OMIT_BUILTIN_TEST
  37134. /*
  37135. ** Let V[] be an array of unsigned characters sufficient to hold
  37136. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  37137. ** Then the following macros can be used to set, clear, or test
  37138. ** individual bits within V.
  37139. */
  37140. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  37141. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  37142. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  37143. /*
  37144. ** This routine runs an extensive test of the Bitvec code.
  37145. **
  37146. ** The input is an array of integers that acts as a program
  37147. ** to test the Bitvec. The integers are opcodes followed
  37148. ** by 0, 1, or 3 operands, depending on the opcode. Another
  37149. ** opcode follows immediately after the last operand.
  37150. **
  37151. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  37152. ** "halt" opcode and causes the test to end.
  37153. **
  37154. ** 0 Halt and return the number of errors
  37155. ** 1 N S X Set N bits beginning with S and incrementing by X
  37156. ** 2 N S X Clear N bits beginning with S and incrementing by X
  37157. ** 3 N Set N randomly chosen bits
  37158. ** 4 N Clear N randomly chosen bits
  37159. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  37160. **
  37161. ** The opcodes 1 through 4 perform set and clear operations are performed
  37162. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  37163. ** Opcode 5 works on the linear array only, not on the Bitvec.
  37164. ** Opcode 5 is used to deliberately induce a fault in order to
  37165. ** confirm that error detection works.
  37166. **
  37167. ** At the conclusion of the test the linear array is compared
  37168. ** against the Bitvec object. If there are any differences,
  37169. ** an error is returned. If they are the same, zero is returned.
  37170. **
  37171. ** If a memory allocation error occurs, return -1.
  37172. */
  37173. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  37174. Bitvec *pBitvec = 0;
  37175. unsigned char *pV = 0;
  37176. int rc = -1;
  37177. int i, nx, pc, op;
  37178. void *pTmpSpace;
  37179. /* Allocate the Bitvec to be tested and a linear array of
  37180. ** bits to act as the reference */
  37181. pBitvec = sqlite3BitvecCreate( sz );
  37182. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  37183. pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
  37184. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  37185. /* NULL pBitvec tests */
  37186. sqlite3BitvecSet(0, 1);
  37187. sqlite3BitvecClear(0, 1, pTmpSpace);
  37188. /* Run the program */
  37189. pc = 0;
  37190. while( (op = aOp[pc])!=0 ){
  37191. switch( op ){
  37192. case 1:
  37193. case 2:
  37194. case 5: {
  37195. nx = 4;
  37196. i = aOp[pc+2] - 1;
  37197. aOp[pc+2] += aOp[pc+3];
  37198. break;
  37199. }
  37200. case 3:
  37201. case 4:
  37202. default: {
  37203. nx = 2;
  37204. sqlite3_randomness(sizeof(i), &i);
  37205. break;
  37206. }
  37207. }
  37208. if( (--aOp[pc+1]) > 0 ) nx = 0;
  37209. pc += nx;
  37210. i = (i & 0x7fffffff)%sz;
  37211. if( (op & 1)!=0 ){
  37212. SETBIT(pV, (i+1));
  37213. if( op!=5 ){
  37214. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  37215. }
  37216. }else{
  37217. CLEARBIT(pV, (i+1));
  37218. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  37219. }
  37220. }
  37221. /* Test to make sure the linear array exactly matches the
  37222. ** Bitvec object. Start with the assumption that they do
  37223. ** match (rc==0). Change rc to non-zero if a discrepancy
  37224. ** is found.
  37225. */
  37226. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  37227. + sqlite3BitvecTest(pBitvec, 0)
  37228. + (sqlite3BitvecSize(pBitvec) - sz);
  37229. for(i=1; i<=sz; i++){
  37230. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  37231. rc = i;
  37232. break;
  37233. }
  37234. }
  37235. /* Free allocated structure */
  37236. bitvec_end:
  37237. sqlite3_free(pTmpSpace);
  37238. sqlite3_free(pV);
  37239. sqlite3BitvecDestroy(pBitvec);
  37240. return rc;
  37241. }
  37242. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  37243. /************** End of bitvec.c **********************************************/
  37244. /************** Begin file pcache.c ******************************************/
  37245. /*
  37246. ** 2008 August 05
  37247. **
  37248. ** The author disclaims copyright to this source code. In place of
  37249. ** a legal notice, here is a blessing:
  37250. **
  37251. ** May you do good and not evil.
  37252. ** May you find forgiveness for yourself and forgive others.
  37253. ** May you share freely, never taking more than you give.
  37254. **
  37255. *************************************************************************
  37256. ** This file implements that page cache.
  37257. */
  37258. /* #include "sqliteInt.h" */
  37259. /*
  37260. ** A complete page cache is an instance of this structure.
  37261. */
  37262. struct PCache {
  37263. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  37264. PgHdr *pSynced; /* Last synced page in dirty page list */
  37265. int nRef; /* Number of referenced pages */
  37266. int szCache; /* Configured cache size */
  37267. int szPage; /* Size of every page in this cache */
  37268. int szExtra; /* Size of extra space for each page */
  37269. u8 bPurgeable; /* True if pages are on backing store */
  37270. u8 eCreate; /* eCreate value for for xFetch() */
  37271. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  37272. void *pStress; /* Argument to xStress */
  37273. sqlite3_pcache *pCache; /* Pluggable cache module */
  37274. };
  37275. /********************************** Linked List Management ********************/
  37276. /* Allowed values for second argument to pcacheManageDirtyList() */
  37277. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  37278. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  37279. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  37280. /*
  37281. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  37282. ** argument determines what operation to do. The 0x01 bit means first
  37283. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  37284. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  37285. */
  37286. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  37287. PCache *p = pPage->pCache;
  37288. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  37289. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  37290. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  37291. /* Update the PCache1.pSynced variable if necessary. */
  37292. if( p->pSynced==pPage ){
  37293. PgHdr *pSynced = pPage->pDirtyPrev;
  37294. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  37295. pSynced = pSynced->pDirtyPrev;
  37296. }
  37297. p->pSynced = pSynced;
  37298. }
  37299. if( pPage->pDirtyNext ){
  37300. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  37301. }else{
  37302. assert( pPage==p->pDirtyTail );
  37303. p->pDirtyTail = pPage->pDirtyPrev;
  37304. }
  37305. if( pPage->pDirtyPrev ){
  37306. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  37307. }else{
  37308. assert( pPage==p->pDirty );
  37309. p->pDirty = pPage->pDirtyNext;
  37310. if( p->pDirty==0 && p->bPurgeable ){
  37311. assert( p->eCreate==1 );
  37312. p->eCreate = 2;
  37313. }
  37314. }
  37315. pPage->pDirtyNext = 0;
  37316. pPage->pDirtyPrev = 0;
  37317. }
  37318. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  37319. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  37320. pPage->pDirtyNext = p->pDirty;
  37321. if( pPage->pDirtyNext ){
  37322. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  37323. pPage->pDirtyNext->pDirtyPrev = pPage;
  37324. }else{
  37325. p->pDirtyTail = pPage;
  37326. if( p->bPurgeable ){
  37327. assert( p->eCreate==2 );
  37328. p->eCreate = 1;
  37329. }
  37330. }
  37331. p->pDirty = pPage;
  37332. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  37333. p->pSynced = pPage;
  37334. }
  37335. }
  37336. }
  37337. /*
  37338. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  37339. ** being used for an in-memory database, this function is a no-op.
  37340. */
  37341. static void pcacheUnpin(PgHdr *p){
  37342. if( p->pCache->bPurgeable ){
  37343. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  37344. }
  37345. }
  37346. /*
  37347. ** Compute the number of pages of cache requested. p->szCache is the
  37348. ** cache size requested by the "PRAGMA cache_size" statement.
  37349. **
  37350. **
  37351. */
  37352. static int numberOfCachePages(PCache *p){
  37353. if( p->szCache>=0 ){
  37354. /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
  37355. ** suggested cache size is set to N. */
  37356. return p->szCache;
  37357. }else{
  37358. /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
  37359. ** the number of cache pages is adjusted to use approximately abs(N*1024)
  37360. ** bytes of memory. */
  37361. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  37362. }
  37363. }
  37364. /*************************************************** General Interfaces ******
  37365. **
  37366. ** Initialize and shutdown the page cache subsystem. Neither of these
  37367. ** functions are threadsafe.
  37368. */
  37369. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  37370. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  37371. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  37372. ** built-in default page cache is used instead of the application defined
  37373. ** page cache. */
  37374. sqlite3PCacheSetDefault();
  37375. }
  37376. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  37377. }
  37378. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  37379. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  37380. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  37381. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  37382. }
  37383. }
  37384. /*
  37385. ** Return the size in bytes of a PCache object.
  37386. */
  37387. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  37388. /*
  37389. ** Create a new PCache object. Storage space to hold the object
  37390. ** has already been allocated and is passed in as the p pointer.
  37391. ** The caller discovers how much space needs to be allocated by
  37392. ** calling sqlite3PcacheSize().
  37393. */
  37394. SQLITE_PRIVATE int sqlite3PcacheOpen(
  37395. int szPage, /* Size of every page */
  37396. int szExtra, /* Extra space associated with each page */
  37397. int bPurgeable, /* True if pages are on backing store */
  37398. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  37399. void *pStress, /* Argument to xStress */
  37400. PCache *p /* Preallocated space for the PCache */
  37401. ){
  37402. memset(p, 0, sizeof(PCache));
  37403. p->szPage = 1;
  37404. p->szExtra = szExtra;
  37405. p->bPurgeable = bPurgeable;
  37406. p->eCreate = 2;
  37407. p->xStress = xStress;
  37408. p->pStress = pStress;
  37409. p->szCache = 100;
  37410. return sqlite3PcacheSetPageSize(p, szPage);
  37411. }
  37412. /*
  37413. ** Change the page size for PCache object. The caller must ensure that there
  37414. ** are no outstanding page references when this function is called.
  37415. */
  37416. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  37417. assert( pCache->nRef==0 && pCache->pDirty==0 );
  37418. if( pCache->szPage ){
  37419. sqlite3_pcache *pNew;
  37420. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  37421. szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
  37422. pCache->bPurgeable
  37423. );
  37424. if( pNew==0 ) return SQLITE_NOMEM;
  37425. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  37426. if( pCache->pCache ){
  37427. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  37428. }
  37429. pCache->pCache = pNew;
  37430. pCache->szPage = szPage;
  37431. }
  37432. return SQLITE_OK;
  37433. }
  37434. /*
  37435. ** Try to obtain a page from the cache.
  37436. **
  37437. ** This routine returns a pointer to an sqlite3_pcache_page object if
  37438. ** such an object is already in cache, or if a new one is created.
  37439. ** This routine returns a NULL pointer if the object was not in cache
  37440. ** and could not be created.
  37441. **
  37442. ** The createFlags should be 0 to check for existing pages and should
  37443. ** be 3 (not 1, but 3) to try to create a new page.
  37444. **
  37445. ** If the createFlag is 0, then NULL is always returned if the page
  37446. ** is not already in the cache. If createFlag is 1, then a new page
  37447. ** is created only if that can be done without spilling dirty pages
  37448. ** and without exceeding the cache size limit.
  37449. **
  37450. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  37451. ** initialize the sqlite3_pcache_page object and convert it into a
  37452. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  37453. ** routines are split this way for performance reasons. When separated
  37454. ** they can both (usually) operate without having to push values to
  37455. ** the stack on entry and pop them back off on exit, which saves a
  37456. ** lot of pushing and popping.
  37457. */
  37458. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  37459. PCache *pCache, /* Obtain the page from this cache */
  37460. Pgno pgno, /* Page number to obtain */
  37461. int createFlag /* If true, create page if it does not exist already */
  37462. ){
  37463. int eCreate;
  37464. assert( pCache!=0 );
  37465. assert( pCache->pCache!=0 );
  37466. assert( createFlag==3 || createFlag==0 );
  37467. assert( pgno>0 );
  37468. /* eCreate defines what to do if the page does not exist.
  37469. ** 0 Do not allocate a new page. (createFlag==0)
  37470. ** 1 Allocate a new page if doing so is inexpensive.
  37471. ** (createFlag==1 AND bPurgeable AND pDirty)
  37472. ** 2 Allocate a new page even it doing so is difficult.
  37473. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  37474. */
  37475. eCreate = createFlag & pCache->eCreate;
  37476. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  37477. assert( createFlag==0 || pCache->eCreate==eCreate );
  37478. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  37479. return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  37480. }
  37481. /*
  37482. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  37483. ** page because new clean pages are available for reuse and the cache
  37484. ** size limit has been reached, then this routine can be invoked to
  37485. ** try harder to allocate a page. This routine might invoke the stress
  37486. ** callback to spill dirty pages to the journal. It will then try to
  37487. ** allocate the new page and will only fail to allocate a new page on
  37488. ** an OOM error.
  37489. **
  37490. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  37491. */
  37492. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  37493. PCache *pCache, /* Obtain the page from this cache */
  37494. Pgno pgno, /* Page number to obtain */
  37495. sqlite3_pcache_page **ppPage /* Write result here */
  37496. ){
  37497. PgHdr *pPg;
  37498. if( pCache->eCreate==2 ) return 0;
  37499. /* Find a dirty page to write-out and recycle. First try to find a
  37500. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  37501. ** cleared), but if that is not possible settle for any other
  37502. ** unreferenced dirty page.
  37503. */
  37504. for(pPg=pCache->pSynced;
  37505. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  37506. pPg=pPg->pDirtyPrev
  37507. );
  37508. pCache->pSynced = pPg;
  37509. if( !pPg ){
  37510. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  37511. }
  37512. if( pPg ){
  37513. int rc;
  37514. #ifdef SQLITE_LOG_CACHE_SPILL
  37515. sqlite3_log(SQLITE_FULL,
  37516. "spill page %d making room for %d - cache used: %d/%d",
  37517. pPg->pgno, pgno,
  37518. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  37519. numberOfCachePages(pCache));
  37520. #endif
  37521. rc = pCache->xStress(pCache->pStress, pPg);
  37522. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  37523. return rc;
  37524. }
  37525. }
  37526. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  37527. return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
  37528. }
  37529. /*
  37530. ** This is a helper routine for sqlite3PcacheFetchFinish()
  37531. **
  37532. ** In the uncommon case where the page being fetched has not been
  37533. ** initialized, this routine is invoked to do the initialization.
  37534. ** This routine is broken out into a separate function since it
  37535. ** requires extra stack manipulation that can be avoided in the common
  37536. ** case.
  37537. */
  37538. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  37539. PCache *pCache, /* Obtain the page from this cache */
  37540. Pgno pgno, /* Page number obtained */
  37541. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  37542. ){
  37543. PgHdr *pPgHdr;
  37544. assert( pPage!=0 );
  37545. pPgHdr = (PgHdr*)pPage->pExtra;
  37546. assert( pPgHdr->pPage==0 );
  37547. memset(pPgHdr, 0, sizeof(PgHdr));
  37548. pPgHdr->pPage = pPage;
  37549. pPgHdr->pData = pPage->pBuf;
  37550. pPgHdr->pExtra = (void *)&pPgHdr[1];
  37551. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  37552. pPgHdr->pCache = pCache;
  37553. pPgHdr->pgno = pgno;
  37554. pPgHdr->flags = PGHDR_CLEAN;
  37555. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  37556. }
  37557. /*
  37558. ** This routine converts the sqlite3_pcache_page object returned by
  37559. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  37560. ** must be called after sqlite3PcacheFetch() in order to get a usable
  37561. ** result.
  37562. */
  37563. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  37564. PCache *pCache, /* Obtain the page from this cache */
  37565. Pgno pgno, /* Page number obtained */
  37566. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  37567. ){
  37568. PgHdr *pPgHdr;
  37569. assert( pPage!=0 );
  37570. pPgHdr = (PgHdr *)pPage->pExtra;
  37571. if( !pPgHdr->pPage ){
  37572. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  37573. }
  37574. if( 0==pPgHdr->nRef ){
  37575. pCache->nRef++;
  37576. }
  37577. pPgHdr->nRef++;
  37578. return pPgHdr;
  37579. }
  37580. /*
  37581. ** Decrement the reference count on a page. If the page is clean and the
  37582. ** reference count drops to 0, then it is made eligible for recycling.
  37583. */
  37584. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  37585. assert( p->nRef>0 );
  37586. p->nRef--;
  37587. if( p->nRef==0 ){
  37588. p->pCache->nRef--;
  37589. if( p->flags&PGHDR_CLEAN ){
  37590. pcacheUnpin(p);
  37591. }else if( p->pDirtyPrev!=0 ){
  37592. /* Move the page to the head of the dirty list. */
  37593. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  37594. }
  37595. }
  37596. }
  37597. /*
  37598. ** Increase the reference count of a supplied page by 1.
  37599. */
  37600. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  37601. assert(p->nRef>0);
  37602. p->nRef++;
  37603. }
  37604. /*
  37605. ** Drop a page from the cache. There must be exactly one reference to the
  37606. ** page. This function deletes that reference, so after it returns the
  37607. ** page pointed to by p is invalid.
  37608. */
  37609. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  37610. assert( p->nRef==1 );
  37611. if( p->flags&PGHDR_DIRTY ){
  37612. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  37613. }
  37614. p->pCache->nRef--;
  37615. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  37616. }
  37617. /*
  37618. ** Make sure the page is marked as dirty. If it isn't dirty already,
  37619. ** make it so.
  37620. */
  37621. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  37622. assert( p->nRef>0 );
  37623. if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){
  37624. p->flags &= ~PGHDR_DONT_WRITE;
  37625. if( p->flags & PGHDR_CLEAN ){
  37626. p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
  37627. assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
  37628. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  37629. }
  37630. }
  37631. }
  37632. /*
  37633. ** Make sure the page is marked as clean. If it isn't clean already,
  37634. ** make it so.
  37635. */
  37636. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  37637. if( (p->flags & PGHDR_DIRTY) ){
  37638. assert( (p->flags & PGHDR_CLEAN)==0 );
  37639. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  37640. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
  37641. p->flags |= PGHDR_CLEAN;
  37642. if( p->nRef==0 ){
  37643. pcacheUnpin(p);
  37644. }
  37645. }
  37646. }
  37647. /*
  37648. ** Make every page in the cache clean.
  37649. */
  37650. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  37651. PgHdr *p;
  37652. while( (p = pCache->pDirty)!=0 ){
  37653. sqlite3PcacheMakeClean(p);
  37654. }
  37655. }
  37656. /*
  37657. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  37658. */
  37659. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  37660. PgHdr *p;
  37661. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37662. p->flags &= ~PGHDR_NEED_SYNC;
  37663. }
  37664. pCache->pSynced = pCache->pDirtyTail;
  37665. }
  37666. /*
  37667. ** Change the page number of page p to newPgno.
  37668. */
  37669. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  37670. PCache *pCache = p->pCache;
  37671. assert( p->nRef>0 );
  37672. assert( newPgno>0 );
  37673. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  37674. p->pgno = newPgno;
  37675. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  37676. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  37677. }
  37678. }
  37679. /*
  37680. ** Drop every cache entry whose page number is greater than "pgno". The
  37681. ** caller must ensure that there are no outstanding references to any pages
  37682. ** other than page 1 with a page number greater than pgno.
  37683. **
  37684. ** If there is a reference to page 1 and the pgno parameter passed to this
  37685. ** function is 0, then the data area associated with page 1 is zeroed, but
  37686. ** the page object is not dropped.
  37687. */
  37688. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  37689. if( pCache->pCache ){
  37690. PgHdr *p;
  37691. PgHdr *pNext;
  37692. for(p=pCache->pDirty; p; p=pNext){
  37693. pNext = p->pDirtyNext;
  37694. /* This routine never gets call with a positive pgno except right
  37695. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  37696. ** it must be that pgno==0.
  37697. */
  37698. assert( p->pgno>0 );
  37699. if( ALWAYS(p->pgno>pgno) ){
  37700. assert( p->flags&PGHDR_DIRTY );
  37701. sqlite3PcacheMakeClean(p);
  37702. }
  37703. }
  37704. if( pgno==0 && pCache->nRef ){
  37705. sqlite3_pcache_page *pPage1;
  37706. pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
  37707. if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
  37708. ** pCache->nRef>0 */
  37709. memset(pPage1->pBuf, 0, pCache->szPage);
  37710. pgno = 1;
  37711. }
  37712. }
  37713. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  37714. }
  37715. }
  37716. /*
  37717. ** Close a cache.
  37718. */
  37719. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  37720. assert( pCache->pCache!=0 );
  37721. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  37722. }
  37723. /*
  37724. ** Discard the contents of the cache.
  37725. */
  37726. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  37727. sqlite3PcacheTruncate(pCache, 0);
  37728. }
  37729. /*
  37730. ** Merge two lists of pages connected by pDirty and in pgno order.
  37731. ** Do not both fixing the pDirtyPrev pointers.
  37732. */
  37733. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  37734. PgHdr result, *pTail;
  37735. pTail = &result;
  37736. while( pA && pB ){
  37737. if( pA->pgno<pB->pgno ){
  37738. pTail->pDirty = pA;
  37739. pTail = pA;
  37740. pA = pA->pDirty;
  37741. }else{
  37742. pTail->pDirty = pB;
  37743. pTail = pB;
  37744. pB = pB->pDirty;
  37745. }
  37746. }
  37747. if( pA ){
  37748. pTail->pDirty = pA;
  37749. }else if( pB ){
  37750. pTail->pDirty = pB;
  37751. }else{
  37752. pTail->pDirty = 0;
  37753. }
  37754. return result.pDirty;
  37755. }
  37756. /*
  37757. ** Sort the list of pages in accending order by pgno. Pages are
  37758. ** connected by pDirty pointers. The pDirtyPrev pointers are
  37759. ** corrupted by this sort.
  37760. **
  37761. ** Since there cannot be more than 2^31 distinct pages in a database,
  37762. ** there cannot be more than 31 buckets required by the merge sorter.
  37763. ** One extra bucket is added to catch overflow in case something
  37764. ** ever changes to make the previous sentence incorrect.
  37765. */
  37766. #define N_SORT_BUCKET 32
  37767. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  37768. PgHdr *a[N_SORT_BUCKET], *p;
  37769. int i;
  37770. memset(a, 0, sizeof(a));
  37771. while( pIn ){
  37772. p = pIn;
  37773. pIn = p->pDirty;
  37774. p->pDirty = 0;
  37775. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  37776. if( a[i]==0 ){
  37777. a[i] = p;
  37778. break;
  37779. }else{
  37780. p = pcacheMergeDirtyList(a[i], p);
  37781. a[i] = 0;
  37782. }
  37783. }
  37784. if( NEVER(i==N_SORT_BUCKET-1) ){
  37785. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  37786. ** the input list. But that is impossible.
  37787. */
  37788. a[i] = pcacheMergeDirtyList(a[i], p);
  37789. }
  37790. }
  37791. p = a[0];
  37792. for(i=1; i<N_SORT_BUCKET; i++){
  37793. p = pcacheMergeDirtyList(p, a[i]);
  37794. }
  37795. return p;
  37796. }
  37797. /*
  37798. ** Return a list of all dirty pages in the cache, sorted by page number.
  37799. */
  37800. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  37801. PgHdr *p;
  37802. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37803. p->pDirty = p->pDirtyNext;
  37804. }
  37805. return pcacheSortDirtyList(pCache->pDirty);
  37806. }
  37807. /*
  37808. ** Return the total number of referenced pages held by the cache.
  37809. */
  37810. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  37811. return pCache->nRef;
  37812. }
  37813. /*
  37814. ** Return the number of references to the page supplied as an argument.
  37815. */
  37816. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  37817. return p->nRef;
  37818. }
  37819. /*
  37820. ** Return the total number of pages in the cache.
  37821. */
  37822. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  37823. assert( pCache->pCache!=0 );
  37824. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  37825. }
  37826. #ifdef SQLITE_TEST
  37827. /*
  37828. ** Get the suggested cache-size value.
  37829. */
  37830. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  37831. return numberOfCachePages(pCache);
  37832. }
  37833. #endif
  37834. /*
  37835. ** Set the suggested cache-size value.
  37836. */
  37837. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  37838. assert( pCache->pCache!=0 );
  37839. pCache->szCache = mxPage;
  37840. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  37841. numberOfCachePages(pCache));
  37842. }
  37843. /*
  37844. ** Free up as much memory as possible from the page cache.
  37845. */
  37846. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  37847. assert( pCache->pCache!=0 );
  37848. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  37849. }
  37850. /*
  37851. ** Return the size of the header added by this middleware layer
  37852. ** in the page-cache hierarchy.
  37853. */
  37854. SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
  37855. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  37856. /*
  37857. ** For all dirty pages currently in the cache, invoke the specified
  37858. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  37859. ** defined.
  37860. */
  37861. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  37862. PgHdr *pDirty;
  37863. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  37864. xIter(pDirty);
  37865. }
  37866. }
  37867. #endif
  37868. /************** End of pcache.c **********************************************/
  37869. /************** Begin file pcache1.c *****************************************/
  37870. /*
  37871. ** 2008 November 05
  37872. **
  37873. ** The author disclaims copyright to this source code. In place of
  37874. ** a legal notice, here is a blessing:
  37875. **
  37876. ** May you do good and not evil.
  37877. ** May you find forgiveness for yourself and forgive others.
  37878. ** May you share freely, never taking more than you give.
  37879. **
  37880. *************************************************************************
  37881. **
  37882. ** This file implements the default page cache implementation (the
  37883. ** sqlite3_pcache interface). It also contains part of the implementation
  37884. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  37885. ** If the default page cache implementation is overridden, then neither of
  37886. ** these two features are available.
  37887. **
  37888. ** A Page cache line looks like this:
  37889. **
  37890. ** -------------------------------------------------------------
  37891. ** | database page content | PgHdr1 | MemPage | PgHdr |
  37892. ** -------------------------------------------------------------
  37893. **
  37894. ** The database page content is up front (so that buffer overreads tend to
  37895. ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
  37896. ** is the extension added by the btree.c module containing information such
  37897. ** as the database page number and how that database page is used. PgHdr
  37898. ** is added by the pcache.c layer and contains information used to keep track
  37899. ** of which pages are "dirty". PgHdr1 is an extension added by this
  37900. ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
  37901. ** PgHdr1 contains information needed to look up a page by its page number.
  37902. ** The superclass sqlite3_pcache_page.pBuf points to the start of the
  37903. ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
  37904. **
  37905. ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
  37906. ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
  37907. ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
  37908. ** size can vary according to architecture, compile-time options, and
  37909. ** SQLite library version number.
  37910. **
  37911. ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
  37912. ** using a separate memory allocation from the database page content. This
  37913. ** seeks to overcome the "clownshoe" problem (also called "internal
  37914. ** fragmentation" in academic literature) of allocating a few bytes more
  37915. ** than a power of two with the memory allocator rounding up to the next
  37916. ** power of two, and leaving the rounded-up space unused.
  37917. **
  37918. ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
  37919. ** with this module. Information is passed back and forth as PgHdr1 pointers.
  37920. **
  37921. ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
  37922. ** The btree.c module deals with pointers to MemPage objects.
  37923. **
  37924. ** SOURCE OF PAGE CACHE MEMORY:
  37925. **
  37926. ** Memory for a page might come from any of three sources:
  37927. **
  37928. ** (1) The general-purpose memory allocator - sqlite3Malloc()
  37929. ** (2) Global page-cache memory provided using sqlite3_config() with
  37930. ** SQLITE_CONFIG_PAGECACHE.
  37931. ** (3) PCache-local bulk allocation.
  37932. **
  37933. ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
  37934. ** that is allocated when the page cache is created. The size of the local
  37935. ** bulk allocation can be adjusted using
  37936. **
  37937. ** sqlite3_config(SQLITE_CONFIG_PCACHE, 0, 0, N).
  37938. **
  37939. ** If N is positive, then N pages worth of memory are allocated using a single
  37940. ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
  37941. ** Or if N is negative, then -1024*N bytes of memory are allocated and used
  37942. ** for as many pages as can be accomodated.
  37943. **
  37944. ** Only one of (2) or (3) can be used. Once the memory available to (2) or
  37945. ** (3) is exhausted, subsequent allocations fail over to the general-purpose
  37946. ** memory allocator (1).
  37947. **
  37948. ** Earlier versions of SQLite used only methods (1) and (2). But experiments
  37949. ** show that method (3) with N==100 provides about a 5% performance boost for
  37950. ** common workloads.
  37951. */
  37952. /* #include "sqliteInt.h" */
  37953. typedef struct PCache1 PCache1;
  37954. typedef struct PgHdr1 PgHdr1;
  37955. typedef struct PgFreeslot PgFreeslot;
  37956. typedef struct PGroup PGroup;
  37957. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  37958. ** of one or more PCaches that are able to recycle each other's unpinned
  37959. ** pages when they are under memory pressure. A PGroup is an instance of
  37960. ** the following object.
  37961. **
  37962. ** This page cache implementation works in one of two modes:
  37963. **
  37964. ** (1) Every PCache is the sole member of its own PGroup. There is
  37965. ** one PGroup per PCache.
  37966. **
  37967. ** (2) There is a single global PGroup that all PCaches are a member
  37968. ** of.
  37969. **
  37970. ** Mode 1 uses more memory (since PCache instances are not able to rob
  37971. ** unused pages from other PCaches) but it also operates without a mutex,
  37972. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  37973. ** threadsafe, but recycles pages more efficiently.
  37974. **
  37975. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  37976. ** PGroup which is the pcache1.grp global variable and its mutex is
  37977. ** SQLITE_MUTEX_STATIC_LRU.
  37978. */
  37979. struct PGroup {
  37980. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  37981. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  37982. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  37983. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  37984. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  37985. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  37986. };
  37987. /* Each page cache is an instance of the following object. Every
  37988. ** open database file (including each in-memory database and each
  37989. ** temporary or transient database) has a single page cache which
  37990. ** is an instance of this object.
  37991. **
  37992. ** Pointers to structures of this type are cast and returned as
  37993. ** opaque sqlite3_pcache* handles.
  37994. */
  37995. struct PCache1 {
  37996. /* Cache configuration parameters. Page size (szPage) and the purgeable
  37997. ** flag (bPurgeable) are set when the cache is created. nMax may be
  37998. ** modified at any time by a call to the pcache1Cachesize() method.
  37999. ** The PGroup mutex must be held when accessing nMax.
  38000. */
  38001. PGroup *pGroup; /* PGroup this cache belongs to */
  38002. int szPage; /* Size of database content section */
  38003. int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
  38004. int szAlloc; /* Total size of one pcache line */
  38005. int bPurgeable; /* True if cache is purgeable */
  38006. unsigned int nMin; /* Minimum number of pages reserved */
  38007. unsigned int nMax; /* Configured "cache_size" value */
  38008. unsigned int n90pct; /* nMax*9/10 */
  38009. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  38010. /* Hash table of all pages. The following variables may only be accessed
  38011. ** when the accessor is holding the PGroup mutex.
  38012. */
  38013. unsigned int nRecyclable; /* Number of pages in the LRU list */
  38014. unsigned int nPage; /* Total number of pages in apHash */
  38015. unsigned int nHash; /* Number of slots in apHash[] */
  38016. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  38017. PgHdr1 *pFree; /* List of unused pcache-local pages */
  38018. void *pBulk; /* Bulk memory used by pcache-local */
  38019. };
  38020. /*
  38021. ** Each cache entry is represented by an instance of the following
  38022. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  38023. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  38024. ** in memory.
  38025. */
  38026. struct PgHdr1 {
  38027. sqlite3_pcache_page page;
  38028. unsigned int iKey; /* Key value (page number) */
  38029. u8 isPinned; /* Page in use, not on the LRU list */
  38030. u8 isBulkLocal; /* This page from bulk local storage */
  38031. PgHdr1 *pNext; /* Next in hash table chain */
  38032. PCache1 *pCache; /* Cache that currently owns this page */
  38033. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  38034. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  38035. };
  38036. /*
  38037. ** Free slots in the allocator used to divide up the global page cache
  38038. ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
  38039. */
  38040. struct PgFreeslot {
  38041. PgFreeslot *pNext; /* Next free slot */
  38042. };
  38043. /*
  38044. ** Global data used by this cache.
  38045. */
  38046. static SQLITE_WSD struct PCacheGlobal {
  38047. PGroup grp; /* The global PGroup for mode (2) */
  38048. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  38049. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  38050. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  38051. ** The nFreeSlot and pFree values do require mutex protection.
  38052. */
  38053. int isInit; /* True if initialized */
  38054. int separateCache; /* Use a new PGroup for each PCache */
  38055. int nInitPage; /* Initial bulk allocation size */
  38056. int szSlot; /* Size of each free slot */
  38057. int nSlot; /* The number of pcache slots */
  38058. int nReserve; /* Try to keep nFreeSlot above this */
  38059. void *pStart, *pEnd; /* Bounds of global page cache memory */
  38060. /* Above requires no mutex. Use mutex below for variable that follow. */
  38061. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  38062. PgFreeslot *pFree; /* Free page blocks */
  38063. int nFreeSlot; /* Number of unused pcache slots */
  38064. /* The following value requires a mutex to change. We skip the mutex on
  38065. ** reading because (1) most platforms read a 32-bit integer atomically and
  38066. ** (2) even if an incorrect value is read, no great harm is done since this
  38067. ** is really just an optimization. */
  38068. int bUnderPressure; /* True if low on PAGECACHE memory */
  38069. } pcache1_g;
  38070. /*
  38071. ** All code in this file should access the global structure above via the
  38072. ** alias "pcache1". This ensures that the WSD emulation is used when
  38073. ** compiling for systems that do not support real WSD.
  38074. */
  38075. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  38076. /*
  38077. ** Macros to enter and leave the PCache LRU mutex.
  38078. */
  38079. #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  38080. # define pcache1EnterMutex(X) assert((X)->mutex==0)
  38081. # define pcache1LeaveMutex(X) assert((X)->mutex==0)
  38082. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
  38083. #else
  38084. # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  38085. # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  38086. # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
  38087. #endif
  38088. /******************************************************************************/
  38089. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  38090. /*
  38091. ** This function is called during initialization if a static buffer is
  38092. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  38093. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  38094. ** enough to contain 'n' buffers of 'sz' bytes each.
  38095. **
  38096. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  38097. ** to be serialized already. There is no need for further mutexing.
  38098. */
  38099. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  38100. if( pcache1.isInit ){
  38101. PgFreeslot *p;
  38102. if( pBuf==0 ) sz = n = 0;
  38103. sz = ROUNDDOWN8(sz);
  38104. pcache1.szSlot = sz;
  38105. pcache1.nSlot = pcache1.nFreeSlot = n;
  38106. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  38107. pcache1.pStart = pBuf;
  38108. pcache1.pFree = 0;
  38109. pcache1.bUnderPressure = 0;
  38110. while( n-- ){
  38111. p = (PgFreeslot*)pBuf;
  38112. p->pNext = pcache1.pFree;
  38113. pcache1.pFree = p;
  38114. pBuf = (void*)&((char*)pBuf)[sz];
  38115. }
  38116. pcache1.pEnd = pBuf;
  38117. }
  38118. }
  38119. /*
  38120. ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
  38121. ** true if pCache->pFree ends up containing one or more free pages.
  38122. */
  38123. static int pcache1InitBulk(PCache1 *pCache){
  38124. i64 szBulk;
  38125. char *zBulk;
  38126. if( pcache1.nInitPage==0 ) return 0;
  38127. /* Do not bother with a bulk allocation if the cache size very small */
  38128. if( pCache->nMax<3 ) return 0;
  38129. sqlite3BeginBenignMalloc();
  38130. if( pcache1.nInitPage>0 ){
  38131. szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
  38132. }else{
  38133. szBulk = -1024 * (i64)pcache1.nInitPage;
  38134. }
  38135. if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
  38136. szBulk = pCache->szAlloc*pCache->nMax;
  38137. }
  38138. zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
  38139. sqlite3EndBenignMalloc();
  38140. if( zBulk ){
  38141. int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
  38142. int i;
  38143. for(i=0; i<nBulk; i++){
  38144. PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
  38145. pX->page.pBuf = zBulk;
  38146. pX->page.pExtra = &pX[1];
  38147. pX->isBulkLocal = 1;
  38148. pX->pNext = pCache->pFree;
  38149. pCache->pFree = pX;
  38150. zBulk += pCache->szAlloc;
  38151. }
  38152. }
  38153. return pCache->pFree!=0;
  38154. }
  38155. /*
  38156. ** Malloc function used within this file to allocate space from the buffer
  38157. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  38158. ** such buffer exists or there is no space left in it, this function falls
  38159. ** back to sqlite3Malloc().
  38160. **
  38161. ** Multiple threads can run this routine at the same time. Global variables
  38162. ** in pcache1 need to be protected via mutex.
  38163. */
  38164. static void *pcache1Alloc(int nByte){
  38165. void *p = 0;
  38166. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  38167. if( nByte<=pcache1.szSlot ){
  38168. sqlite3_mutex_enter(pcache1.mutex);
  38169. p = (PgHdr1 *)pcache1.pFree;
  38170. if( p ){
  38171. pcache1.pFree = pcache1.pFree->pNext;
  38172. pcache1.nFreeSlot--;
  38173. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  38174. assert( pcache1.nFreeSlot>=0 );
  38175. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  38176. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
  38177. }
  38178. sqlite3_mutex_leave(pcache1.mutex);
  38179. }
  38180. if( p==0 ){
  38181. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  38182. ** it from sqlite3Malloc instead.
  38183. */
  38184. p = sqlite3Malloc(nByte);
  38185. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  38186. if( p ){
  38187. int sz = sqlite3MallocSize(p);
  38188. sqlite3_mutex_enter(pcache1.mutex);
  38189. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  38190. sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  38191. sqlite3_mutex_leave(pcache1.mutex);
  38192. }
  38193. #endif
  38194. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  38195. }
  38196. return p;
  38197. }
  38198. /*
  38199. ** Free an allocated buffer obtained from pcache1Alloc().
  38200. */
  38201. static void pcache1Free(void *p){
  38202. int nFreed = 0;
  38203. if( p==0 ) return;
  38204. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  38205. PgFreeslot *pSlot;
  38206. sqlite3_mutex_enter(pcache1.mutex);
  38207. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
  38208. pSlot = (PgFreeslot*)p;
  38209. pSlot->pNext = pcache1.pFree;
  38210. pcache1.pFree = pSlot;
  38211. pcache1.nFreeSlot++;
  38212. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  38213. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  38214. sqlite3_mutex_leave(pcache1.mutex);
  38215. }else{
  38216. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  38217. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  38218. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  38219. nFreed = sqlite3MallocSize(p);
  38220. sqlite3_mutex_enter(pcache1.mutex);
  38221. sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
  38222. sqlite3_mutex_leave(pcache1.mutex);
  38223. #endif
  38224. sqlite3_free(p);
  38225. }
  38226. }
  38227. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38228. /*
  38229. ** Return the size of a pcache allocation
  38230. */
  38231. static int pcache1MemSize(void *p){
  38232. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  38233. return pcache1.szSlot;
  38234. }else{
  38235. int iSize;
  38236. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  38237. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  38238. iSize = sqlite3MallocSize(p);
  38239. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  38240. return iSize;
  38241. }
  38242. }
  38243. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  38244. /*
  38245. ** Allocate a new page object initially associated with cache pCache.
  38246. */
  38247. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  38248. PgHdr1 *p = 0;
  38249. void *pPg;
  38250. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38251. if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
  38252. p = pCache->pFree;
  38253. pCache->pFree = p->pNext;
  38254. p->pNext = 0;
  38255. }else{
  38256. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38257. /* The group mutex must be released before pcache1Alloc() is called. This
  38258. ** is because it might call sqlite3_release_memory(), which assumes that
  38259. ** this mutex is not held. */
  38260. assert( pcache1.separateCache==0 );
  38261. assert( pCache->pGroup==&pcache1.grp );
  38262. pcache1LeaveMutex(pCache->pGroup);
  38263. #endif
  38264. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38265. pPg = pcache1Alloc(pCache->szPage);
  38266. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  38267. if( !pPg || !p ){
  38268. pcache1Free(pPg);
  38269. sqlite3_free(p);
  38270. pPg = 0;
  38271. }
  38272. #else
  38273. pPg = pcache1Alloc(pCache->szAlloc);
  38274. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  38275. #endif
  38276. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38277. pcache1EnterMutex(pCache->pGroup);
  38278. #endif
  38279. if( pPg==0 ) return 0;
  38280. p->page.pBuf = pPg;
  38281. p->page.pExtra = &p[1];
  38282. p->isBulkLocal = 0;
  38283. }
  38284. if( pCache->bPurgeable ){
  38285. pCache->pGroup->nCurrentPage++;
  38286. }
  38287. return p;
  38288. }
  38289. /*
  38290. ** Free a page object allocated by pcache1AllocPage().
  38291. */
  38292. static void pcache1FreePage(PgHdr1 *p){
  38293. PCache1 *pCache;
  38294. assert( p!=0 );
  38295. pCache = p->pCache;
  38296. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  38297. if( p->isBulkLocal ){
  38298. p->pNext = pCache->pFree;
  38299. pCache->pFree = p;
  38300. }else{
  38301. pcache1Free(p->page.pBuf);
  38302. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38303. sqlite3_free(p);
  38304. #endif
  38305. }
  38306. if( pCache->bPurgeable ){
  38307. pCache->pGroup->nCurrentPage--;
  38308. }
  38309. }
  38310. /*
  38311. ** Malloc function used by SQLite to obtain space from the buffer configured
  38312. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  38313. ** exists, this function falls back to sqlite3Malloc().
  38314. */
  38315. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  38316. return pcache1Alloc(sz);
  38317. }
  38318. /*
  38319. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  38320. */
  38321. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  38322. pcache1Free(p);
  38323. }
  38324. /*
  38325. ** Return true if it desirable to avoid allocating a new page cache
  38326. ** entry.
  38327. **
  38328. ** If memory was allocated specifically to the page cache using
  38329. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  38330. ** it is desirable to avoid allocating a new page cache entry because
  38331. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  38332. ** for all page cache needs and we should not need to spill the
  38333. ** allocation onto the heap.
  38334. **
  38335. ** Or, the heap is used for all page cache memory but the heap is
  38336. ** under memory pressure, then again it is desirable to avoid
  38337. ** allocating a new page cache entry in order to avoid stressing
  38338. ** the heap even further.
  38339. */
  38340. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  38341. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  38342. return pcache1.bUnderPressure;
  38343. }else{
  38344. return sqlite3HeapNearlyFull();
  38345. }
  38346. }
  38347. /******************************************************************************/
  38348. /******** General Implementation Functions ************************************/
  38349. /*
  38350. ** This function is used to resize the hash table used by the cache passed
  38351. ** as the first argument.
  38352. **
  38353. ** The PCache mutex must be held when this function is called.
  38354. */
  38355. static void pcache1ResizeHash(PCache1 *p){
  38356. PgHdr1 **apNew;
  38357. unsigned int nNew;
  38358. unsigned int i;
  38359. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  38360. nNew = p->nHash*2;
  38361. if( nNew<256 ){
  38362. nNew = 256;
  38363. }
  38364. pcache1LeaveMutex(p->pGroup);
  38365. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  38366. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  38367. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  38368. pcache1EnterMutex(p->pGroup);
  38369. if( apNew ){
  38370. for(i=0; i<p->nHash; i++){
  38371. PgHdr1 *pPage;
  38372. PgHdr1 *pNext = p->apHash[i];
  38373. while( (pPage = pNext)!=0 ){
  38374. unsigned int h = pPage->iKey % nNew;
  38375. pNext = pPage->pNext;
  38376. pPage->pNext = apNew[h];
  38377. apNew[h] = pPage;
  38378. }
  38379. }
  38380. sqlite3_free(p->apHash);
  38381. p->apHash = apNew;
  38382. p->nHash = nNew;
  38383. }
  38384. }
  38385. /*
  38386. ** This function is used internally to remove the page pPage from the
  38387. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  38388. ** LRU list, then this function is a no-op.
  38389. **
  38390. ** The PGroup mutex must be held when this function is called.
  38391. */
  38392. static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
  38393. PCache1 *pCache;
  38394. assert( pPage!=0 );
  38395. assert( pPage->isPinned==0 );
  38396. pCache = pPage->pCache;
  38397. assert( pPage->pLruNext || pPage==pCache->pGroup->pLruTail );
  38398. assert( pPage->pLruPrev || pPage==pCache->pGroup->pLruHead );
  38399. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38400. if( pPage->pLruPrev ){
  38401. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  38402. }else{
  38403. pCache->pGroup->pLruHead = pPage->pLruNext;
  38404. }
  38405. if( pPage->pLruNext ){
  38406. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  38407. }else{
  38408. pCache->pGroup->pLruTail = pPage->pLruPrev;
  38409. }
  38410. pPage->pLruNext = 0;
  38411. pPage->pLruPrev = 0;
  38412. pPage->isPinned = 1;
  38413. pCache->nRecyclable--;
  38414. return pPage;
  38415. }
  38416. /*
  38417. ** Remove the page supplied as an argument from the hash table
  38418. ** (PCache1.apHash structure) that it is currently stored in.
  38419. ** Also free the page if freePage is true.
  38420. **
  38421. ** The PGroup mutex must be held when this function is called.
  38422. */
  38423. static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
  38424. unsigned int h;
  38425. PCache1 *pCache = pPage->pCache;
  38426. PgHdr1 **pp;
  38427. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38428. h = pPage->iKey % pCache->nHash;
  38429. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  38430. *pp = (*pp)->pNext;
  38431. pCache->nPage--;
  38432. if( freeFlag ) pcache1FreePage(pPage);
  38433. }
  38434. /*
  38435. ** If there are currently more than nMaxPage pages allocated, try
  38436. ** to recycle pages to reduce the number allocated to nMaxPage.
  38437. */
  38438. static void pcache1EnforceMaxPage(PCache1 *pCache){
  38439. PGroup *pGroup = pCache->pGroup;
  38440. assert( sqlite3_mutex_held(pGroup->mutex) );
  38441. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  38442. PgHdr1 *p = pGroup->pLruTail;
  38443. assert( p->pCache->pGroup==pGroup );
  38444. assert( p->isPinned==0 );
  38445. pcache1PinPage(p);
  38446. pcache1RemoveFromHash(p, 1);
  38447. }
  38448. if( pCache->nPage==0 && pCache->pBulk ){
  38449. sqlite3_free(pCache->pBulk);
  38450. pCache->pBulk = pCache->pFree = 0;
  38451. }
  38452. }
  38453. /*
  38454. ** Discard all pages from cache pCache with a page number (key value)
  38455. ** greater than or equal to iLimit. Any pinned pages that meet this
  38456. ** criteria are unpinned before they are discarded.
  38457. **
  38458. ** The PCache mutex must be held when this function is called.
  38459. */
  38460. static void pcache1TruncateUnsafe(
  38461. PCache1 *pCache, /* The cache to truncate */
  38462. unsigned int iLimit /* Drop pages with this pgno or larger */
  38463. ){
  38464. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  38465. unsigned int h;
  38466. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38467. for(h=0; h<pCache->nHash; h++){
  38468. PgHdr1 **pp = &pCache->apHash[h];
  38469. PgHdr1 *pPage;
  38470. while( (pPage = *pp)!=0 ){
  38471. if( pPage->iKey>=iLimit ){
  38472. pCache->nPage--;
  38473. *pp = pPage->pNext;
  38474. if( !pPage->isPinned ) pcache1PinPage(pPage);
  38475. pcache1FreePage(pPage);
  38476. }else{
  38477. pp = &pPage->pNext;
  38478. TESTONLY( nPage++; )
  38479. }
  38480. }
  38481. }
  38482. assert( pCache->nPage==nPage );
  38483. }
  38484. /******************************************************************************/
  38485. /******** sqlite3_pcache Methods **********************************************/
  38486. /*
  38487. ** Implementation of the sqlite3_pcache.xInit method.
  38488. */
  38489. static int pcache1Init(void *NotUsed){
  38490. UNUSED_PARAMETER(NotUsed);
  38491. assert( pcache1.isInit==0 );
  38492. memset(&pcache1, 0, sizeof(pcache1));
  38493. /*
  38494. ** The pcache1.separateCache variable is true if each PCache has its own
  38495. ** private PGroup (mode-1). pcache1.separateCache is false if the single
  38496. ** PGroup in pcache1.grp is used for all page caches (mode-2).
  38497. **
  38498. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  38499. **
  38500. ** * Use a unified cache in single-threaded applications that have
  38501. ** configured a start-time buffer for use as page-cache memory using
  38502. ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
  38503. ** pBuf argument.
  38504. **
  38505. ** * Otherwise use separate caches (mode-1)
  38506. */
  38507. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
  38508. pcache1.separateCache = 0;
  38509. #elif SQLITE_THREADSAFE
  38510. pcache1.separateCache = sqlite3GlobalConfig.pPage==0
  38511. || sqlite3GlobalConfig.bCoreMutex>0;
  38512. #else
  38513. pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
  38514. #endif
  38515. #if SQLITE_THREADSAFE
  38516. if( sqlite3GlobalConfig.bCoreMutex ){
  38517. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  38518. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  38519. }
  38520. #endif
  38521. if( pcache1.separateCache
  38522. && sqlite3GlobalConfig.nPage!=0
  38523. && sqlite3GlobalConfig.pPage==0
  38524. ){
  38525. pcache1.nInitPage = sqlite3GlobalConfig.nPage;
  38526. }else{
  38527. pcache1.nInitPage = 0;
  38528. }
  38529. pcache1.grp.mxPinned = 10;
  38530. pcache1.isInit = 1;
  38531. return SQLITE_OK;
  38532. }
  38533. /*
  38534. ** Implementation of the sqlite3_pcache.xShutdown method.
  38535. ** Note that the static mutex allocated in xInit does
  38536. ** not need to be freed.
  38537. */
  38538. static void pcache1Shutdown(void *NotUsed){
  38539. UNUSED_PARAMETER(NotUsed);
  38540. assert( pcache1.isInit!=0 );
  38541. memset(&pcache1, 0, sizeof(pcache1));
  38542. }
  38543. /* forward declaration */
  38544. static void pcache1Destroy(sqlite3_pcache *p);
  38545. /*
  38546. ** Implementation of the sqlite3_pcache.xCreate method.
  38547. **
  38548. ** Allocate a new cache.
  38549. */
  38550. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  38551. PCache1 *pCache; /* The newly created page cache */
  38552. PGroup *pGroup; /* The group the new page cache will belong to */
  38553. int sz; /* Bytes of memory required to allocate the new cache */
  38554. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  38555. assert( szExtra < 300 );
  38556. sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
  38557. pCache = (PCache1 *)sqlite3MallocZero(sz);
  38558. if( pCache ){
  38559. if( pcache1.separateCache ){
  38560. pGroup = (PGroup*)&pCache[1];
  38561. pGroup->mxPinned = 10;
  38562. }else{
  38563. pGroup = &pcache1.grp;
  38564. }
  38565. pCache->pGroup = pGroup;
  38566. pCache->szPage = szPage;
  38567. pCache->szExtra = szExtra;
  38568. pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
  38569. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  38570. pcache1EnterMutex(pGroup);
  38571. pcache1ResizeHash(pCache);
  38572. if( bPurgeable ){
  38573. pCache->nMin = 10;
  38574. pGroup->nMinPage += pCache->nMin;
  38575. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38576. }
  38577. pcache1LeaveMutex(pGroup);
  38578. if( pCache->nHash==0 ){
  38579. pcache1Destroy((sqlite3_pcache*)pCache);
  38580. pCache = 0;
  38581. }
  38582. }
  38583. return (sqlite3_pcache *)pCache;
  38584. }
  38585. /*
  38586. ** Implementation of the sqlite3_pcache.xCachesize method.
  38587. **
  38588. ** Configure the cache_size limit for a cache.
  38589. */
  38590. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  38591. PCache1 *pCache = (PCache1 *)p;
  38592. if( pCache->bPurgeable ){
  38593. PGroup *pGroup = pCache->pGroup;
  38594. pcache1EnterMutex(pGroup);
  38595. pGroup->nMaxPage += (nMax - pCache->nMax);
  38596. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38597. pCache->nMax = nMax;
  38598. pCache->n90pct = pCache->nMax*9/10;
  38599. pcache1EnforceMaxPage(pCache);
  38600. pcache1LeaveMutex(pGroup);
  38601. }
  38602. }
  38603. /*
  38604. ** Implementation of the sqlite3_pcache.xShrink method.
  38605. **
  38606. ** Free up as much memory as possible.
  38607. */
  38608. static void pcache1Shrink(sqlite3_pcache *p){
  38609. PCache1 *pCache = (PCache1*)p;
  38610. if( pCache->bPurgeable ){
  38611. PGroup *pGroup = pCache->pGroup;
  38612. int savedMaxPage;
  38613. pcache1EnterMutex(pGroup);
  38614. savedMaxPage = pGroup->nMaxPage;
  38615. pGroup->nMaxPage = 0;
  38616. pcache1EnforceMaxPage(pCache);
  38617. pGroup->nMaxPage = savedMaxPage;
  38618. pcache1LeaveMutex(pGroup);
  38619. }
  38620. }
  38621. /*
  38622. ** Implementation of the sqlite3_pcache.xPagecount method.
  38623. */
  38624. static int pcache1Pagecount(sqlite3_pcache *p){
  38625. int n;
  38626. PCache1 *pCache = (PCache1*)p;
  38627. pcache1EnterMutex(pCache->pGroup);
  38628. n = pCache->nPage;
  38629. pcache1LeaveMutex(pCache->pGroup);
  38630. return n;
  38631. }
  38632. /*
  38633. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  38634. ** in the header of the pcache1Fetch() procedure.
  38635. **
  38636. ** This steps are broken out into a separate procedure because they are
  38637. ** usually not needed, and by avoiding the stack initialization required
  38638. ** for these steps, the main pcache1Fetch() procedure can run faster.
  38639. */
  38640. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  38641. PCache1 *pCache,
  38642. unsigned int iKey,
  38643. int createFlag
  38644. ){
  38645. unsigned int nPinned;
  38646. PGroup *pGroup = pCache->pGroup;
  38647. PgHdr1 *pPage = 0;
  38648. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  38649. assert( pCache->nPage >= pCache->nRecyclable );
  38650. nPinned = pCache->nPage - pCache->nRecyclable;
  38651. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  38652. assert( pCache->n90pct == pCache->nMax*9/10 );
  38653. if( createFlag==1 && (
  38654. nPinned>=pGroup->mxPinned
  38655. || nPinned>=pCache->n90pct
  38656. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  38657. )){
  38658. return 0;
  38659. }
  38660. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  38661. assert( pCache->nHash>0 && pCache->apHash );
  38662. /* Step 4. Try to recycle a page. */
  38663. if( pCache->bPurgeable
  38664. && pGroup->pLruTail
  38665. && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
  38666. ){
  38667. PCache1 *pOther;
  38668. pPage = pGroup->pLruTail;
  38669. assert( pPage->isPinned==0 );
  38670. pcache1RemoveFromHash(pPage, 0);
  38671. pcache1PinPage(pPage);
  38672. pOther = pPage->pCache;
  38673. if( pOther->szAlloc != pCache->szAlloc ){
  38674. pcache1FreePage(pPage);
  38675. pPage = 0;
  38676. }else{
  38677. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  38678. }
  38679. }
  38680. /* Step 5. If a usable page buffer has still not been found,
  38681. ** attempt to allocate a new one.
  38682. */
  38683. if( !pPage ){
  38684. if( createFlag==1 ){ sqlite3BeginBenignMalloc(); }
  38685. pPage = pcache1AllocPage(pCache);
  38686. if( createFlag==1 ){ sqlite3EndBenignMalloc(); }
  38687. }
  38688. if( pPage ){
  38689. unsigned int h = iKey % pCache->nHash;
  38690. pCache->nPage++;
  38691. pPage->iKey = iKey;
  38692. pPage->pNext = pCache->apHash[h];
  38693. pPage->pCache = pCache;
  38694. pPage->pLruPrev = 0;
  38695. pPage->pLruNext = 0;
  38696. pPage->isPinned = 1;
  38697. *(void **)pPage->page.pExtra = 0;
  38698. pCache->apHash[h] = pPage;
  38699. if( iKey>pCache->iMaxKey ){
  38700. pCache->iMaxKey = iKey;
  38701. }
  38702. }
  38703. return pPage;
  38704. }
  38705. /*
  38706. ** Implementation of the sqlite3_pcache.xFetch method.
  38707. **
  38708. ** Fetch a page by key value.
  38709. **
  38710. ** Whether or not a new page may be allocated by this function depends on
  38711. ** the value of the createFlag argument. 0 means do not allocate a new
  38712. ** page. 1 means allocate a new page if space is easily available. 2
  38713. ** means to try really hard to allocate a new page.
  38714. **
  38715. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  38716. ** database) there is really no difference between createFlag 1 and 2. So
  38717. ** the calling function (pcache.c) will never have a createFlag of 1 on
  38718. ** a non-purgeable cache.
  38719. **
  38720. ** There are three different approaches to obtaining space for a page,
  38721. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  38722. **
  38723. ** 1. Regardless of the value of createFlag, the cache is searched for a
  38724. ** copy of the requested page. If one is found, it is returned.
  38725. **
  38726. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  38727. ** returned.
  38728. **
  38729. ** 3. If createFlag is 1, and the page is not already in the cache, then
  38730. ** return NULL (do not allocate a new page) if any of the following
  38731. ** conditions are true:
  38732. **
  38733. ** (a) the number of pages pinned by the cache is greater than
  38734. ** PCache1.nMax, or
  38735. **
  38736. ** (b) the number of pages pinned by the cache is greater than
  38737. ** the sum of nMax for all purgeable caches, less the sum of
  38738. ** nMin for all other purgeable caches, or
  38739. **
  38740. ** 4. If none of the first three conditions apply and the cache is marked
  38741. ** as purgeable, and if one of the following is true:
  38742. **
  38743. ** (a) The number of pages allocated for the cache is already
  38744. ** PCache1.nMax, or
  38745. **
  38746. ** (b) The number of pages allocated for all purgeable caches is
  38747. ** already equal to or greater than the sum of nMax for all
  38748. ** purgeable caches,
  38749. **
  38750. ** (c) The system is under memory pressure and wants to avoid
  38751. ** unnecessary pages cache entry allocations
  38752. **
  38753. ** then attempt to recycle a page from the LRU list. If it is the right
  38754. ** size, return the recycled buffer. Otherwise, free the buffer and
  38755. ** proceed to step 5.
  38756. **
  38757. ** 5. Otherwise, allocate and return a new page buffer.
  38758. **
  38759. ** There are two versions of this routine. pcache1FetchWithMutex() is
  38760. ** the general case. pcache1FetchNoMutex() is a faster implementation for
  38761. ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
  38762. ** invokes the appropriate routine.
  38763. */
  38764. static PgHdr1 *pcache1FetchNoMutex(
  38765. sqlite3_pcache *p,
  38766. unsigned int iKey,
  38767. int createFlag
  38768. ){
  38769. PCache1 *pCache = (PCache1 *)p;
  38770. PgHdr1 *pPage = 0;
  38771. /* Step 1: Search the hash table for an existing entry. */
  38772. pPage = pCache->apHash[iKey % pCache->nHash];
  38773. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  38774. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  38775. if( pPage ){
  38776. if( !pPage->isPinned ){
  38777. return pcache1PinPage(pPage);
  38778. }else{
  38779. return pPage;
  38780. }
  38781. }else if( createFlag ){
  38782. /* Steps 3, 4, and 5 implemented by this subroutine */
  38783. return pcache1FetchStage2(pCache, iKey, createFlag);
  38784. }else{
  38785. return 0;
  38786. }
  38787. }
  38788. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  38789. static PgHdr1 *pcache1FetchWithMutex(
  38790. sqlite3_pcache *p,
  38791. unsigned int iKey,
  38792. int createFlag
  38793. ){
  38794. PCache1 *pCache = (PCache1 *)p;
  38795. PgHdr1 *pPage;
  38796. pcache1EnterMutex(pCache->pGroup);
  38797. pPage = pcache1FetchNoMutex(p, iKey, createFlag);
  38798. assert( pPage==0 || pCache->iMaxKey>=iKey );
  38799. pcache1LeaveMutex(pCache->pGroup);
  38800. return pPage;
  38801. }
  38802. #endif
  38803. static sqlite3_pcache_page *pcache1Fetch(
  38804. sqlite3_pcache *p,
  38805. unsigned int iKey,
  38806. int createFlag
  38807. ){
  38808. #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
  38809. PCache1 *pCache = (PCache1 *)p;
  38810. #endif
  38811. assert( offsetof(PgHdr1,page)==0 );
  38812. assert( pCache->bPurgeable || createFlag!=1 );
  38813. assert( pCache->bPurgeable || pCache->nMin==0 );
  38814. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  38815. assert( pCache->nMin==0 || pCache->bPurgeable );
  38816. assert( pCache->nHash>0 );
  38817. #if PCACHE1_MIGHT_USE_GROUP_MUTEX
  38818. if( pCache->pGroup->mutex ){
  38819. return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
  38820. }else
  38821. #endif
  38822. {
  38823. return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
  38824. }
  38825. }
  38826. /*
  38827. ** Implementation of the sqlite3_pcache.xUnpin method.
  38828. **
  38829. ** Mark a page as unpinned (eligible for asynchronous recycling).
  38830. */
  38831. static void pcache1Unpin(
  38832. sqlite3_pcache *p,
  38833. sqlite3_pcache_page *pPg,
  38834. int reuseUnlikely
  38835. ){
  38836. PCache1 *pCache = (PCache1 *)p;
  38837. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38838. PGroup *pGroup = pCache->pGroup;
  38839. assert( pPage->pCache==pCache );
  38840. pcache1EnterMutex(pGroup);
  38841. /* It is an error to call this function if the page is already
  38842. ** part of the PGroup LRU list.
  38843. */
  38844. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  38845. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  38846. assert( pPage->isPinned==1 );
  38847. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  38848. pcache1RemoveFromHash(pPage, 1);
  38849. }else{
  38850. /* Add the page to the PGroup LRU list. */
  38851. if( pGroup->pLruHead ){
  38852. pGroup->pLruHead->pLruPrev = pPage;
  38853. pPage->pLruNext = pGroup->pLruHead;
  38854. pGroup->pLruHead = pPage;
  38855. }else{
  38856. pGroup->pLruTail = pPage;
  38857. pGroup->pLruHead = pPage;
  38858. }
  38859. pCache->nRecyclable++;
  38860. pPage->isPinned = 0;
  38861. }
  38862. pcache1LeaveMutex(pCache->pGroup);
  38863. }
  38864. /*
  38865. ** Implementation of the sqlite3_pcache.xRekey method.
  38866. */
  38867. static void pcache1Rekey(
  38868. sqlite3_pcache *p,
  38869. sqlite3_pcache_page *pPg,
  38870. unsigned int iOld,
  38871. unsigned int iNew
  38872. ){
  38873. PCache1 *pCache = (PCache1 *)p;
  38874. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38875. PgHdr1 **pp;
  38876. unsigned int h;
  38877. assert( pPage->iKey==iOld );
  38878. assert( pPage->pCache==pCache );
  38879. pcache1EnterMutex(pCache->pGroup);
  38880. h = iOld%pCache->nHash;
  38881. pp = &pCache->apHash[h];
  38882. while( (*pp)!=pPage ){
  38883. pp = &(*pp)->pNext;
  38884. }
  38885. *pp = pPage->pNext;
  38886. h = iNew%pCache->nHash;
  38887. pPage->iKey = iNew;
  38888. pPage->pNext = pCache->apHash[h];
  38889. pCache->apHash[h] = pPage;
  38890. if( iNew>pCache->iMaxKey ){
  38891. pCache->iMaxKey = iNew;
  38892. }
  38893. pcache1LeaveMutex(pCache->pGroup);
  38894. }
  38895. /*
  38896. ** Implementation of the sqlite3_pcache.xTruncate method.
  38897. **
  38898. ** Discard all unpinned pages in the cache with a page number equal to
  38899. ** or greater than parameter iLimit. Any pinned pages with a page number
  38900. ** equal to or greater than iLimit are implicitly unpinned.
  38901. */
  38902. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  38903. PCache1 *pCache = (PCache1 *)p;
  38904. pcache1EnterMutex(pCache->pGroup);
  38905. if( iLimit<=pCache->iMaxKey ){
  38906. pcache1TruncateUnsafe(pCache, iLimit);
  38907. pCache->iMaxKey = iLimit-1;
  38908. }
  38909. pcache1LeaveMutex(pCache->pGroup);
  38910. }
  38911. /*
  38912. ** Implementation of the sqlite3_pcache.xDestroy method.
  38913. **
  38914. ** Destroy a cache allocated using pcache1Create().
  38915. */
  38916. static void pcache1Destroy(sqlite3_pcache *p){
  38917. PCache1 *pCache = (PCache1 *)p;
  38918. PGroup *pGroup = pCache->pGroup;
  38919. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  38920. pcache1EnterMutex(pGroup);
  38921. pcache1TruncateUnsafe(pCache, 0);
  38922. assert( pGroup->nMaxPage >= pCache->nMax );
  38923. pGroup->nMaxPage -= pCache->nMax;
  38924. assert( pGroup->nMinPage >= pCache->nMin );
  38925. pGroup->nMinPage -= pCache->nMin;
  38926. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38927. pcache1EnforceMaxPage(pCache);
  38928. pcache1LeaveMutex(pGroup);
  38929. sqlite3_free(pCache->pBulk);
  38930. sqlite3_free(pCache->apHash);
  38931. sqlite3_free(pCache);
  38932. }
  38933. /*
  38934. ** This function is called during initialization (sqlite3_initialize()) to
  38935. ** install the default pluggable cache module, assuming the user has not
  38936. ** already provided an alternative.
  38937. */
  38938. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  38939. static const sqlite3_pcache_methods2 defaultMethods = {
  38940. 1, /* iVersion */
  38941. 0, /* pArg */
  38942. pcache1Init, /* xInit */
  38943. pcache1Shutdown, /* xShutdown */
  38944. pcache1Create, /* xCreate */
  38945. pcache1Cachesize, /* xCachesize */
  38946. pcache1Pagecount, /* xPagecount */
  38947. pcache1Fetch, /* xFetch */
  38948. pcache1Unpin, /* xUnpin */
  38949. pcache1Rekey, /* xRekey */
  38950. pcache1Truncate, /* xTruncate */
  38951. pcache1Destroy, /* xDestroy */
  38952. pcache1Shrink /* xShrink */
  38953. };
  38954. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  38955. }
  38956. /*
  38957. ** Return the size of the header on each page of this PCACHE implementation.
  38958. */
  38959. SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
  38960. /*
  38961. ** Return the global mutex used by this PCACHE implementation. The
  38962. ** sqlite3_status() routine needs access to this mutex.
  38963. */
  38964. SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
  38965. return pcache1.mutex;
  38966. }
  38967. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38968. /*
  38969. ** This function is called to free superfluous dynamically allocated memory
  38970. ** held by the pager system. Memory in use by any SQLite pager allocated
  38971. ** by the current thread may be sqlite3_free()ed.
  38972. **
  38973. ** nReq is the number of bytes of memory required. Once this much has
  38974. ** been released, the function returns. The return value is the total number
  38975. ** of bytes of memory released.
  38976. */
  38977. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  38978. int nFree = 0;
  38979. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  38980. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  38981. if( sqlite3GlobalConfig.nPage==0 ){
  38982. PgHdr1 *p;
  38983. pcache1EnterMutex(&pcache1.grp);
  38984. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  38985. nFree += pcache1MemSize(p->page.pBuf);
  38986. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38987. nFree += sqlite3MemSize(p);
  38988. #endif
  38989. assert( p->isPinned==0 );
  38990. pcache1PinPage(p);
  38991. pcache1RemoveFromHash(p, 1);
  38992. }
  38993. pcache1LeaveMutex(&pcache1.grp);
  38994. }
  38995. return nFree;
  38996. }
  38997. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  38998. #ifdef SQLITE_TEST
  38999. /*
  39000. ** This function is used by test procedures to inspect the internal state
  39001. ** of the global cache.
  39002. */
  39003. SQLITE_PRIVATE void sqlite3PcacheStats(
  39004. int *pnCurrent, /* OUT: Total number of pages cached */
  39005. int *pnMax, /* OUT: Global maximum cache size */
  39006. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  39007. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  39008. ){
  39009. PgHdr1 *p;
  39010. int nRecyclable = 0;
  39011. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  39012. assert( p->isPinned==0 );
  39013. nRecyclable++;
  39014. }
  39015. *pnCurrent = pcache1.grp.nCurrentPage;
  39016. *pnMax = (int)pcache1.grp.nMaxPage;
  39017. *pnMin = (int)pcache1.grp.nMinPage;
  39018. *pnRecyclable = nRecyclable;
  39019. }
  39020. #endif
  39021. /************** End of pcache1.c *********************************************/
  39022. /************** Begin file rowset.c ******************************************/
  39023. /*
  39024. ** 2008 December 3
  39025. **
  39026. ** The author disclaims copyright to this source code. In place of
  39027. ** a legal notice, here is a blessing:
  39028. **
  39029. ** May you do good and not evil.
  39030. ** May you find forgiveness for yourself and forgive others.
  39031. ** May you share freely, never taking more than you give.
  39032. **
  39033. *************************************************************************
  39034. **
  39035. ** This module implements an object we call a "RowSet".
  39036. **
  39037. ** The RowSet object is a collection of rowids. Rowids
  39038. ** are inserted into the RowSet in an arbitrary order. Inserts
  39039. ** can be intermixed with tests to see if a given rowid has been
  39040. ** previously inserted into the RowSet.
  39041. **
  39042. ** After all inserts are finished, it is possible to extract the
  39043. ** elements of the RowSet in sorted order. Once this extraction
  39044. ** process has started, no new elements may be inserted.
  39045. **
  39046. ** Hence, the primitive operations for a RowSet are:
  39047. **
  39048. ** CREATE
  39049. ** INSERT
  39050. ** TEST
  39051. ** SMALLEST
  39052. ** DESTROY
  39053. **
  39054. ** The CREATE and DESTROY primitives are the constructor and destructor,
  39055. ** obviously. The INSERT primitive adds a new element to the RowSet.
  39056. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  39057. ** extracts the least value from the RowSet.
  39058. **
  39059. ** The INSERT primitive might allocate additional memory. Memory is
  39060. ** allocated in chunks so most INSERTs do no allocation. There is an
  39061. ** upper bound on the size of allocated memory. No memory is freed
  39062. ** until DESTROY.
  39063. **
  39064. ** The TEST primitive includes a "batch" number. The TEST primitive
  39065. ** will only see elements that were inserted before the last change
  39066. ** in the batch number. In other words, if an INSERT occurs between
  39067. ** two TESTs where the TESTs have the same batch nubmer, then the
  39068. ** value added by the INSERT will not be visible to the second TEST.
  39069. ** The initial batch number is zero, so if the very first TEST contains
  39070. ** a non-zero batch number, it will see all prior INSERTs.
  39071. **
  39072. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  39073. ** that is attempted.
  39074. **
  39075. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  39076. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  39077. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  39078. ** The cost of a TEST using the same batch number is O(logN). The cost
  39079. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  39080. ** primitives are constant time. The cost of DESTROY is O(N).
  39081. **
  39082. ** There is an added cost of O(N) when switching between TEST and
  39083. ** SMALLEST primitives.
  39084. */
  39085. /* #include "sqliteInt.h" */
  39086. /*
  39087. ** Target size for allocation chunks.
  39088. */
  39089. #define ROWSET_ALLOCATION_SIZE 1024
  39090. /*
  39091. ** The number of rowset entries per allocation chunk.
  39092. */
  39093. #define ROWSET_ENTRY_PER_CHUNK \
  39094. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  39095. /*
  39096. ** Each entry in a RowSet is an instance of the following object.
  39097. **
  39098. ** This same object is reused to store a linked list of trees of RowSetEntry
  39099. ** objects. In that alternative use, pRight points to the next entry
  39100. ** in the list, pLeft points to the tree, and v is unused. The
  39101. ** RowSet.pForest value points to the head of this forest list.
  39102. */
  39103. struct RowSetEntry {
  39104. i64 v; /* ROWID value for this entry */
  39105. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  39106. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  39107. };
  39108. /*
  39109. ** RowSetEntry objects are allocated in large chunks (instances of the
  39110. ** following structure) to reduce memory allocation overhead. The
  39111. ** chunks are kept on a linked list so that they can be deallocated
  39112. ** when the RowSet is destroyed.
  39113. */
  39114. struct RowSetChunk {
  39115. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  39116. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  39117. };
  39118. /*
  39119. ** A RowSet in an instance of the following structure.
  39120. **
  39121. ** A typedef of this structure if found in sqliteInt.h.
  39122. */
  39123. struct RowSet {
  39124. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  39125. sqlite3 *db; /* The database connection */
  39126. struct RowSetEntry *pEntry; /* List of entries using pRight */
  39127. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  39128. struct RowSetEntry *pFresh; /* Source of new entry objects */
  39129. struct RowSetEntry *pForest; /* List of binary trees of entries */
  39130. u16 nFresh; /* Number of objects on pFresh */
  39131. u16 rsFlags; /* Various flags */
  39132. int iBatch; /* Current insert batch */
  39133. };
  39134. /*
  39135. ** Allowed values for RowSet.rsFlags
  39136. */
  39137. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  39138. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  39139. /*
  39140. ** Turn bulk memory into a RowSet object. N bytes of memory
  39141. ** are available at pSpace. The db pointer is used as a memory context
  39142. ** for any subsequent allocations that need to occur.
  39143. ** Return a pointer to the new RowSet object.
  39144. **
  39145. ** It must be the case that N is sufficient to make a Rowset. If not
  39146. ** an assertion fault occurs.
  39147. **
  39148. ** If N is larger than the minimum, use the surplus as an initial
  39149. ** allocation of entries available to be filled.
  39150. */
  39151. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  39152. RowSet *p;
  39153. assert( N >= ROUND8(sizeof(*p)) );
  39154. p = pSpace;
  39155. p->pChunk = 0;
  39156. p->db = db;
  39157. p->pEntry = 0;
  39158. p->pLast = 0;
  39159. p->pForest = 0;
  39160. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  39161. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  39162. p->rsFlags = ROWSET_SORTED;
  39163. p->iBatch = 0;
  39164. return p;
  39165. }
  39166. /*
  39167. ** Deallocate all chunks from a RowSet. This frees all memory that
  39168. ** the RowSet has allocated over its lifetime. This routine is
  39169. ** the destructor for the RowSet.
  39170. */
  39171. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  39172. struct RowSetChunk *pChunk, *pNextChunk;
  39173. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  39174. pNextChunk = pChunk->pNextChunk;
  39175. sqlite3DbFree(p->db, pChunk);
  39176. }
  39177. p->pChunk = 0;
  39178. p->nFresh = 0;
  39179. p->pEntry = 0;
  39180. p->pLast = 0;
  39181. p->pForest = 0;
  39182. p->rsFlags = ROWSET_SORTED;
  39183. }
  39184. /*
  39185. ** Allocate a new RowSetEntry object that is associated with the
  39186. ** given RowSet. Return a pointer to the new and completely uninitialized
  39187. ** objected.
  39188. **
  39189. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  39190. ** routine returns NULL.
  39191. */
  39192. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  39193. assert( p!=0 );
  39194. if( p->nFresh==0 ){
  39195. struct RowSetChunk *pNew;
  39196. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  39197. if( pNew==0 ){
  39198. return 0;
  39199. }
  39200. pNew->pNextChunk = p->pChunk;
  39201. p->pChunk = pNew;
  39202. p->pFresh = pNew->aEntry;
  39203. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  39204. }
  39205. p->nFresh--;
  39206. return p->pFresh++;
  39207. }
  39208. /*
  39209. ** Insert a new value into a RowSet.
  39210. **
  39211. ** The mallocFailed flag of the database connection is set if a
  39212. ** memory allocation fails.
  39213. */
  39214. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  39215. struct RowSetEntry *pEntry; /* The new entry */
  39216. struct RowSetEntry *pLast; /* The last prior entry */
  39217. /* This routine is never called after sqlite3RowSetNext() */
  39218. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  39219. pEntry = rowSetEntryAlloc(p);
  39220. if( pEntry==0 ) return;
  39221. pEntry->v = rowid;
  39222. pEntry->pRight = 0;
  39223. pLast = p->pLast;
  39224. if( pLast ){
  39225. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  39226. p->rsFlags &= ~ROWSET_SORTED;
  39227. }
  39228. pLast->pRight = pEntry;
  39229. }else{
  39230. p->pEntry = pEntry;
  39231. }
  39232. p->pLast = pEntry;
  39233. }
  39234. /*
  39235. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  39236. **
  39237. ** The input lists are connected via pRight pointers and are
  39238. ** assumed to each already be in sorted order.
  39239. */
  39240. static struct RowSetEntry *rowSetEntryMerge(
  39241. struct RowSetEntry *pA, /* First sorted list to be merged */
  39242. struct RowSetEntry *pB /* Second sorted list to be merged */
  39243. ){
  39244. struct RowSetEntry head;
  39245. struct RowSetEntry *pTail;
  39246. pTail = &head;
  39247. while( pA && pB ){
  39248. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  39249. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  39250. if( pA->v<pB->v ){
  39251. pTail->pRight = pA;
  39252. pA = pA->pRight;
  39253. pTail = pTail->pRight;
  39254. }else if( pB->v<pA->v ){
  39255. pTail->pRight = pB;
  39256. pB = pB->pRight;
  39257. pTail = pTail->pRight;
  39258. }else{
  39259. pA = pA->pRight;
  39260. }
  39261. }
  39262. if( pA ){
  39263. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  39264. pTail->pRight = pA;
  39265. }else{
  39266. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  39267. pTail->pRight = pB;
  39268. }
  39269. return head.pRight;
  39270. }
  39271. /*
  39272. ** Sort all elements on the list of RowSetEntry objects into order of
  39273. ** increasing v.
  39274. */
  39275. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  39276. unsigned int i;
  39277. struct RowSetEntry *pNext, *aBucket[40];
  39278. memset(aBucket, 0, sizeof(aBucket));
  39279. while( pIn ){
  39280. pNext = pIn->pRight;
  39281. pIn->pRight = 0;
  39282. for(i=0; aBucket[i]; i++){
  39283. pIn = rowSetEntryMerge(aBucket[i], pIn);
  39284. aBucket[i] = 0;
  39285. }
  39286. aBucket[i] = pIn;
  39287. pIn = pNext;
  39288. }
  39289. pIn = 0;
  39290. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  39291. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  39292. }
  39293. return pIn;
  39294. }
  39295. /*
  39296. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  39297. ** Convert this tree into a linked list connected by the pRight pointers
  39298. ** and return pointers to the first and last elements of the new list.
  39299. */
  39300. static void rowSetTreeToList(
  39301. struct RowSetEntry *pIn, /* Root of the input tree */
  39302. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  39303. struct RowSetEntry **ppLast /* Write tail of the output list here */
  39304. ){
  39305. assert( pIn!=0 );
  39306. if( pIn->pLeft ){
  39307. struct RowSetEntry *p;
  39308. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  39309. p->pRight = pIn;
  39310. }else{
  39311. *ppFirst = pIn;
  39312. }
  39313. if( pIn->pRight ){
  39314. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  39315. }else{
  39316. *ppLast = pIn;
  39317. }
  39318. assert( (*ppLast)->pRight==0 );
  39319. }
  39320. /*
  39321. ** Convert a sorted list of elements (connected by pRight) into a binary
  39322. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  39323. ** node taken from the head of *ppList. A depth of 2 means a tree with
  39324. ** three nodes. And so forth.
  39325. **
  39326. ** Use as many entries from the input list as required and update the
  39327. ** *ppList to point to the unused elements of the list. If the input
  39328. ** list contains too few elements, then construct an incomplete tree
  39329. ** and leave *ppList set to NULL.
  39330. **
  39331. ** Return a pointer to the root of the constructed binary tree.
  39332. */
  39333. static struct RowSetEntry *rowSetNDeepTree(
  39334. struct RowSetEntry **ppList,
  39335. int iDepth
  39336. ){
  39337. struct RowSetEntry *p; /* Root of the new tree */
  39338. struct RowSetEntry *pLeft; /* Left subtree */
  39339. if( *ppList==0 ){
  39340. return 0;
  39341. }
  39342. if( iDepth==1 ){
  39343. p = *ppList;
  39344. *ppList = p->pRight;
  39345. p->pLeft = p->pRight = 0;
  39346. return p;
  39347. }
  39348. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  39349. p = *ppList;
  39350. if( p==0 ){
  39351. return pLeft;
  39352. }
  39353. p->pLeft = pLeft;
  39354. *ppList = p->pRight;
  39355. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  39356. return p;
  39357. }
  39358. /*
  39359. ** Convert a sorted list of elements into a binary tree. Make the tree
  39360. ** as deep as it needs to be in order to contain the entire list.
  39361. */
  39362. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  39363. int iDepth; /* Depth of the tree so far */
  39364. struct RowSetEntry *p; /* Current tree root */
  39365. struct RowSetEntry *pLeft; /* Left subtree */
  39366. assert( pList!=0 );
  39367. p = pList;
  39368. pList = p->pRight;
  39369. p->pLeft = p->pRight = 0;
  39370. for(iDepth=1; pList; iDepth++){
  39371. pLeft = p;
  39372. p = pList;
  39373. pList = p->pRight;
  39374. p->pLeft = pLeft;
  39375. p->pRight = rowSetNDeepTree(&pList, iDepth);
  39376. }
  39377. return p;
  39378. }
  39379. /*
  39380. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  39381. ** sort them all together into one big ordered list on p->pEntry.
  39382. **
  39383. ** This routine should only be called once in the life of a RowSet.
  39384. */
  39385. static void rowSetToList(RowSet *p){
  39386. /* This routine is called only once */
  39387. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  39388. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  39389. p->pEntry = rowSetEntrySort(p->pEntry);
  39390. }
  39391. /* While this module could theoretically support it, sqlite3RowSetNext()
  39392. ** is never called after sqlite3RowSetText() for the same RowSet. So
  39393. ** there is never a forest to deal with. Should this change, simply
  39394. ** remove the assert() and the #if 0. */
  39395. assert( p->pForest==0 );
  39396. #if 0
  39397. while( p->pForest ){
  39398. struct RowSetEntry *pTree = p->pForest->pLeft;
  39399. if( pTree ){
  39400. struct RowSetEntry *pHead, *pTail;
  39401. rowSetTreeToList(pTree, &pHead, &pTail);
  39402. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  39403. }
  39404. p->pForest = p->pForest->pRight;
  39405. }
  39406. #endif
  39407. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  39408. }
  39409. /*
  39410. ** Extract the smallest element from the RowSet.
  39411. ** Write the element into *pRowid. Return 1 on success. Return
  39412. ** 0 if the RowSet is already empty.
  39413. **
  39414. ** After this routine has been called, the sqlite3RowSetInsert()
  39415. ** routine may not be called again.
  39416. */
  39417. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  39418. assert( p!=0 );
  39419. /* Merge the forest into a single sorted list on first call */
  39420. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  39421. /* Return the next entry on the list */
  39422. if( p->pEntry ){
  39423. *pRowid = p->pEntry->v;
  39424. p->pEntry = p->pEntry->pRight;
  39425. if( p->pEntry==0 ){
  39426. sqlite3RowSetClear(p);
  39427. }
  39428. return 1;
  39429. }else{
  39430. return 0;
  39431. }
  39432. }
  39433. /*
  39434. ** Check to see if element iRowid was inserted into the rowset as
  39435. ** part of any insert batch prior to iBatch. Return 1 or 0.
  39436. **
  39437. ** If this is the first test of a new batch and if there exist entries
  39438. ** on pRowSet->pEntry, then sort those entries into the forest at
  39439. ** pRowSet->pForest so that they can be tested.
  39440. */
  39441. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  39442. struct RowSetEntry *p, *pTree;
  39443. /* This routine is never called after sqlite3RowSetNext() */
  39444. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  39445. /* Sort entries into the forest on the first test of a new batch
  39446. */
  39447. if( iBatch!=pRowSet->iBatch ){
  39448. p = pRowSet->pEntry;
  39449. if( p ){
  39450. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  39451. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  39452. p = rowSetEntrySort(p);
  39453. }
  39454. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  39455. ppPrevTree = &pTree->pRight;
  39456. if( pTree->pLeft==0 ){
  39457. pTree->pLeft = rowSetListToTree(p);
  39458. break;
  39459. }else{
  39460. struct RowSetEntry *pAux, *pTail;
  39461. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  39462. pTree->pLeft = 0;
  39463. p = rowSetEntryMerge(pAux, p);
  39464. }
  39465. }
  39466. if( pTree==0 ){
  39467. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  39468. if( pTree ){
  39469. pTree->v = 0;
  39470. pTree->pRight = 0;
  39471. pTree->pLeft = rowSetListToTree(p);
  39472. }
  39473. }
  39474. pRowSet->pEntry = 0;
  39475. pRowSet->pLast = 0;
  39476. pRowSet->rsFlags |= ROWSET_SORTED;
  39477. }
  39478. pRowSet->iBatch = iBatch;
  39479. }
  39480. /* Test to see if the iRowid value appears anywhere in the forest.
  39481. ** Return 1 if it does and 0 if not.
  39482. */
  39483. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  39484. p = pTree->pLeft;
  39485. while( p ){
  39486. if( p->v<iRowid ){
  39487. p = p->pRight;
  39488. }else if( p->v>iRowid ){
  39489. p = p->pLeft;
  39490. }else{
  39491. return 1;
  39492. }
  39493. }
  39494. }
  39495. return 0;
  39496. }
  39497. /************** End of rowset.c **********************************************/
  39498. /************** Begin file pager.c *******************************************/
  39499. /*
  39500. ** 2001 September 15
  39501. **
  39502. ** The author disclaims copyright to this source code. In place of
  39503. ** a legal notice, here is a blessing:
  39504. **
  39505. ** May you do good and not evil.
  39506. ** May you find forgiveness for yourself and forgive others.
  39507. ** May you share freely, never taking more than you give.
  39508. **
  39509. *************************************************************************
  39510. ** This is the implementation of the page cache subsystem or "pager".
  39511. **
  39512. ** The pager is used to access a database disk file. It implements
  39513. ** atomic commit and rollback through the use of a journal file that
  39514. ** is separate from the database file. The pager also implements file
  39515. ** locking to prevent two processes from writing the same database
  39516. ** file simultaneously, or one process from reading the database while
  39517. ** another is writing.
  39518. */
  39519. #ifndef SQLITE_OMIT_DISKIO
  39520. /* #include "sqliteInt.h" */
  39521. /************** Include wal.h in the middle of pager.c ***********************/
  39522. /************** Begin file wal.h *********************************************/
  39523. /*
  39524. ** 2010 February 1
  39525. **
  39526. ** The author disclaims copyright to this source code. In place of
  39527. ** a legal notice, here is a blessing:
  39528. **
  39529. ** May you do good and not evil.
  39530. ** May you find forgiveness for yourself and forgive others.
  39531. ** May you share freely, never taking more than you give.
  39532. **
  39533. *************************************************************************
  39534. ** This header file defines the interface to the write-ahead logging
  39535. ** system. Refer to the comments below and the header comment attached to
  39536. ** the implementation of each function in log.c for further details.
  39537. */
  39538. #ifndef _WAL_H_
  39539. #define _WAL_H_
  39540. /* #include "sqliteInt.h" */
  39541. /* Additional values that can be added to the sync_flags argument of
  39542. ** sqlite3WalFrames():
  39543. */
  39544. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  39545. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  39546. #ifdef SQLITE_OMIT_WAL
  39547. # define sqlite3WalOpen(x,y,z) 0
  39548. # define sqlite3WalLimit(x,y)
  39549. # define sqlite3WalClose(w,x,y,z) 0
  39550. # define sqlite3WalBeginReadTransaction(y,z) 0
  39551. # define sqlite3WalEndReadTransaction(z)
  39552. # define sqlite3WalDbsize(y) 0
  39553. # define sqlite3WalBeginWriteTransaction(y) 0
  39554. # define sqlite3WalEndWriteTransaction(x) 0
  39555. # define sqlite3WalUndo(x,y,z) 0
  39556. # define sqlite3WalSavepoint(y,z)
  39557. # define sqlite3WalSavepointUndo(y,z) 0
  39558. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  39559. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  39560. # define sqlite3WalCallback(z) 0
  39561. # define sqlite3WalExclusiveMode(y,z) 0
  39562. # define sqlite3WalHeapMemory(z) 0
  39563. # define sqlite3WalFramesize(z) 0
  39564. # define sqlite3WalFindFrame(x,y,z) 0
  39565. #else
  39566. #define WAL_SAVEPOINT_NDATA 4
  39567. /* Connection to a write-ahead log (WAL) file.
  39568. ** There is one object of this type for each pager.
  39569. */
  39570. typedef struct Wal Wal;
  39571. /* Open and close a connection to a write-ahead log. */
  39572. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  39573. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  39574. /* Set the limiting size of a WAL file. */
  39575. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  39576. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  39577. ** snapshot is like a read-transaction. It is the state of the database
  39578. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  39579. ** preserves the current state even if the other threads or processes
  39580. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  39581. ** transaction and releases the lock.
  39582. */
  39583. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  39584. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  39585. /* Read a page from the write-ahead log, if it is present. */
  39586. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  39587. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  39588. /* If the WAL is not empty, return the size of the database. */
  39589. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  39590. /* Obtain or release the WRITER lock. */
  39591. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  39592. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  39593. /* Undo any frames written (but not committed) to the log */
  39594. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  39595. /* Return an integer that records the current (uncommitted) write
  39596. ** position in the WAL */
  39597. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  39598. /* Move the write position of the WAL back to iFrame. Called in
  39599. ** response to a ROLLBACK TO command. */
  39600. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  39601. /* Write a frame or frames to the log. */
  39602. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  39603. /* Copy pages from the log to the database file */
  39604. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  39605. Wal *pWal, /* Write-ahead log connection */
  39606. int eMode, /* One of PASSIVE, FULL and RESTART */
  39607. int (*xBusy)(void*), /* Function to call when busy */
  39608. void *pBusyArg, /* Context argument for xBusyHandler */
  39609. int sync_flags, /* Flags to sync db file with (or 0) */
  39610. int nBuf, /* Size of buffer nBuf */
  39611. u8 *zBuf, /* Temporary buffer to use */
  39612. int *pnLog, /* OUT: Number of frames in WAL */
  39613. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  39614. );
  39615. /* Return the value to pass to a sqlite3_wal_hook callback, the
  39616. ** number of frames in the WAL at the point of the last commit since
  39617. ** sqlite3WalCallback() was called. If no commits have occurred since
  39618. ** the last call, then return 0.
  39619. */
  39620. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  39621. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  39622. ** by the pager layer on the database file.
  39623. */
  39624. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  39625. /* Return true if the argument is non-NULL and the WAL module is using
  39626. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  39627. ** WAL module is using shared-memory, return false.
  39628. */
  39629. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  39630. #ifdef SQLITE_ENABLE_ZIPVFS
  39631. /* If the WAL file is not empty, return the number of bytes of content
  39632. ** stored in each frame (i.e. the db page-size when the WAL was created).
  39633. */
  39634. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  39635. #endif
  39636. #endif /* ifndef SQLITE_OMIT_WAL */
  39637. #endif /* _WAL_H_ */
  39638. /************** End of wal.h *************************************************/
  39639. /************** Continuing where we left off in pager.c **********************/
  39640. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  39641. **
  39642. ** This comment block describes invariants that hold when using a rollback
  39643. ** journal. These invariants do not apply for journal_mode=WAL,
  39644. ** journal_mode=MEMORY, or journal_mode=OFF.
  39645. **
  39646. ** Within this comment block, a page is deemed to have been synced
  39647. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  39648. ** Otherwise, the page is not synced until the xSync method of the VFS
  39649. ** is called successfully on the file containing the page.
  39650. **
  39651. ** Definition: A page of the database file is said to be "overwriteable" if
  39652. ** one or more of the following are true about the page:
  39653. **
  39654. ** (a) The original content of the page as it was at the beginning of
  39655. ** the transaction has been written into the rollback journal and
  39656. ** synced.
  39657. **
  39658. ** (b) The page was a freelist leaf page at the start of the transaction.
  39659. **
  39660. ** (c) The page number is greater than the largest page that existed in
  39661. ** the database file at the start of the transaction.
  39662. **
  39663. ** (1) A page of the database file is never overwritten unless one of the
  39664. ** following are true:
  39665. **
  39666. ** (a) The page and all other pages on the same sector are overwriteable.
  39667. **
  39668. ** (b) The atomic page write optimization is enabled, and the entire
  39669. ** transaction other than the update of the transaction sequence
  39670. ** number consists of a single page change.
  39671. **
  39672. ** (2) The content of a page written into the rollback journal exactly matches
  39673. ** both the content in the database when the rollback journal was written
  39674. ** and the content in the database at the beginning of the current
  39675. ** transaction.
  39676. **
  39677. ** (3) Writes to the database file are an integer multiple of the page size
  39678. ** in length and are aligned on a page boundary.
  39679. **
  39680. ** (4) Reads from the database file are either aligned on a page boundary and
  39681. ** an integer multiple of the page size in length or are taken from the
  39682. ** first 100 bytes of the database file.
  39683. **
  39684. ** (5) All writes to the database file are synced prior to the rollback journal
  39685. ** being deleted, truncated, or zeroed.
  39686. **
  39687. ** (6) If a master journal file is used, then all writes to the database file
  39688. ** are synced prior to the master journal being deleted.
  39689. **
  39690. ** Definition: Two databases (or the same database at two points it time)
  39691. ** are said to be "logically equivalent" if they give the same answer to
  39692. ** all queries. Note in particular the content of freelist leaf
  39693. ** pages can be changed arbitrarily without affecting the logical equivalence
  39694. ** of the database.
  39695. **
  39696. ** (7) At any time, if any subset, including the empty set and the total set,
  39697. ** of the unsynced changes to a rollback journal are removed and the
  39698. ** journal is rolled back, the resulting database file will be logically
  39699. ** equivalent to the database file at the beginning of the transaction.
  39700. **
  39701. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  39702. ** is called to restore the database file to the same size it was at
  39703. ** the beginning of the transaction. (In some VFSes, the xTruncate
  39704. ** method is a no-op, but that does not change the fact the SQLite will
  39705. ** invoke it.)
  39706. **
  39707. ** (9) Whenever the database file is modified, at least one bit in the range
  39708. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  39709. ** the EXCLUSIVE lock, thus signaling other connections on the same
  39710. ** database to flush their caches.
  39711. **
  39712. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  39713. ** than one billion transactions.
  39714. **
  39715. ** (11) A database file is well-formed at the beginning and at the conclusion
  39716. ** of every transaction.
  39717. **
  39718. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  39719. ** the database file.
  39720. **
  39721. ** (13) A SHARED lock is held on the database file while reading any
  39722. ** content out of the database file.
  39723. **
  39724. ******************************************************************************/
  39725. /*
  39726. ** Macros for troubleshooting. Normally turned off
  39727. */
  39728. #if 0
  39729. int sqlite3PagerTrace=1; /* True to enable tracing */
  39730. #define sqlite3DebugPrintf printf
  39731. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  39732. #else
  39733. #define PAGERTRACE(X)
  39734. #endif
  39735. /*
  39736. ** The following two macros are used within the PAGERTRACE() macros above
  39737. ** to print out file-descriptors.
  39738. **
  39739. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  39740. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  39741. ** struct as its argument.
  39742. */
  39743. #define PAGERID(p) ((int)(p->fd))
  39744. #define FILEHANDLEID(fd) ((int)fd)
  39745. /*
  39746. ** The Pager.eState variable stores the current 'state' of a pager. A
  39747. ** pager may be in any one of the seven states shown in the following
  39748. ** state diagram.
  39749. **
  39750. ** OPEN <------+------+
  39751. ** | | |
  39752. ** V | |
  39753. ** +---------> READER-------+ |
  39754. ** | | |
  39755. ** | V |
  39756. ** |<-------WRITER_LOCKED------> ERROR
  39757. ** | | ^
  39758. ** | V |
  39759. ** |<------WRITER_CACHEMOD-------->|
  39760. ** | | |
  39761. ** | V |
  39762. ** |<-------WRITER_DBMOD---------->|
  39763. ** | | |
  39764. ** | V |
  39765. ** +<------WRITER_FINISHED-------->+
  39766. **
  39767. **
  39768. ** List of state transitions and the C [function] that performs each:
  39769. **
  39770. ** OPEN -> READER [sqlite3PagerSharedLock]
  39771. ** READER -> OPEN [pager_unlock]
  39772. **
  39773. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  39774. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  39775. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  39776. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  39777. ** WRITER_*** -> READER [pager_end_transaction]
  39778. **
  39779. ** WRITER_*** -> ERROR [pager_error]
  39780. ** ERROR -> OPEN [pager_unlock]
  39781. **
  39782. **
  39783. ** OPEN:
  39784. **
  39785. ** The pager starts up in this state. Nothing is guaranteed in this
  39786. ** state - the file may or may not be locked and the database size is
  39787. ** unknown. The database may not be read or written.
  39788. **
  39789. ** * No read or write transaction is active.
  39790. ** * Any lock, or no lock at all, may be held on the database file.
  39791. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  39792. **
  39793. ** READER:
  39794. **
  39795. ** In this state all the requirements for reading the database in
  39796. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  39797. ** was) in exclusive-locking mode, a user-level read transaction is
  39798. ** open. The database size is known in this state.
  39799. **
  39800. ** A connection running with locking_mode=normal enters this state when
  39801. ** it opens a read-transaction on the database and returns to state
  39802. ** OPEN after the read-transaction is completed. However a connection
  39803. ** running in locking_mode=exclusive (including temp databases) remains in
  39804. ** this state even after the read-transaction is closed. The only way
  39805. ** a locking_mode=exclusive connection can transition from READER to OPEN
  39806. ** is via the ERROR state (see below).
  39807. **
  39808. ** * A read transaction may be active (but a write-transaction cannot).
  39809. ** * A SHARED or greater lock is held on the database file.
  39810. ** * The dbSize variable may be trusted (even if a user-level read
  39811. ** transaction is not active). The dbOrigSize and dbFileSize variables
  39812. ** may not be trusted at this point.
  39813. ** * If the database is a WAL database, then the WAL connection is open.
  39814. ** * Even if a read-transaction is not open, it is guaranteed that
  39815. ** there is no hot-journal in the file-system.
  39816. **
  39817. ** WRITER_LOCKED:
  39818. **
  39819. ** The pager moves to this state from READER when a write-transaction
  39820. ** is first opened on the database. In WRITER_LOCKED state, all locks
  39821. ** required to start a write-transaction are held, but no actual
  39822. ** modifications to the cache or database have taken place.
  39823. **
  39824. ** In rollback mode, a RESERVED or (if the transaction was opened with
  39825. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  39826. ** moving to this state, but the journal file is not written to or opened
  39827. ** to in this state. If the transaction is committed or rolled back while
  39828. ** in WRITER_LOCKED state, all that is required is to unlock the database
  39829. ** file.
  39830. **
  39831. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  39832. ** If the connection is running with locking_mode=exclusive, an attempt
  39833. ** is made to obtain an EXCLUSIVE lock on the database file.
  39834. **
  39835. ** * A write transaction is active.
  39836. ** * If the connection is open in rollback-mode, a RESERVED or greater
  39837. ** lock is held on the database file.
  39838. ** * If the connection is open in WAL-mode, a WAL write transaction
  39839. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  39840. ** called).
  39841. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  39842. ** * The contents of the pager cache have not been modified.
  39843. ** * The journal file may or may not be open.
  39844. ** * Nothing (not even the first header) has been written to the journal.
  39845. **
  39846. ** WRITER_CACHEMOD:
  39847. **
  39848. ** A pager moves from WRITER_LOCKED state to this state when a page is
  39849. ** first modified by the upper layer. In rollback mode the journal file
  39850. ** is opened (if it is not already open) and a header written to the
  39851. ** start of it. The database file on disk has not been modified.
  39852. **
  39853. ** * A write transaction is active.
  39854. ** * A RESERVED or greater lock is held on the database file.
  39855. ** * The journal file is open and the first header has been written
  39856. ** to it, but the header has not been synced to disk.
  39857. ** * The contents of the page cache have been modified.
  39858. **
  39859. ** WRITER_DBMOD:
  39860. **
  39861. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  39862. ** when it modifies the contents of the database file. WAL connections
  39863. ** never enter this state (since they do not modify the database file,
  39864. ** just the log file).
  39865. **
  39866. ** * A write transaction is active.
  39867. ** * An EXCLUSIVE or greater lock is held on the database file.
  39868. ** * The journal file is open and the first header has been written
  39869. ** and synced to disk.
  39870. ** * The contents of the page cache have been modified (and possibly
  39871. ** written to disk).
  39872. **
  39873. ** WRITER_FINISHED:
  39874. **
  39875. ** It is not possible for a WAL connection to enter this state.
  39876. **
  39877. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  39878. ** state after the entire transaction has been successfully written into the
  39879. ** database file. In this state the transaction may be committed simply
  39880. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  39881. ** not possible to modify the database further. At this point, the upper
  39882. ** layer must either commit or rollback the transaction.
  39883. **
  39884. ** * A write transaction is active.
  39885. ** * An EXCLUSIVE or greater lock is held on the database file.
  39886. ** * All writing and syncing of journal and database data has finished.
  39887. ** If no error occurred, all that remains is to finalize the journal to
  39888. ** commit the transaction. If an error did occur, the caller will need
  39889. ** to rollback the transaction.
  39890. **
  39891. ** ERROR:
  39892. **
  39893. ** The ERROR state is entered when an IO or disk-full error (including
  39894. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  39895. ** difficult to be sure that the in-memory pager state (cache contents,
  39896. ** db size etc.) are consistent with the contents of the file-system.
  39897. **
  39898. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  39899. ** cannot.
  39900. **
  39901. ** For example, if an IO error occurs while performing a rollback,
  39902. ** the contents of the page-cache may be left in an inconsistent state.
  39903. ** At this point it would be dangerous to change back to READER state
  39904. ** (as usually happens after a rollback). Any subsequent readers might
  39905. ** report database corruption (due to the inconsistent cache), and if
  39906. ** they upgrade to writers, they may inadvertently corrupt the database
  39907. ** file. To avoid this hazard, the pager switches into the ERROR state
  39908. ** instead of READER following such an error.
  39909. **
  39910. ** Once it has entered the ERROR state, any attempt to use the pager
  39911. ** to read or write data returns an error. Eventually, once all
  39912. ** outstanding transactions have been abandoned, the pager is able to
  39913. ** transition back to OPEN state, discarding the contents of the
  39914. ** page-cache and any other in-memory state at the same time. Everything
  39915. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  39916. ** when a read-transaction is next opened on the pager (transitioning
  39917. ** the pager into READER state). At that point the system has recovered
  39918. ** from the error.
  39919. **
  39920. ** Specifically, the pager jumps into the ERROR state if:
  39921. **
  39922. ** 1. An error occurs while attempting a rollback. This happens in
  39923. ** function sqlite3PagerRollback().
  39924. **
  39925. ** 2. An error occurs while attempting to finalize a journal file
  39926. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  39927. **
  39928. ** 3. An error occurs while attempting to write to the journal or
  39929. ** database file in function pagerStress() in order to free up
  39930. ** memory.
  39931. **
  39932. ** In other cases, the error is returned to the b-tree layer. The b-tree
  39933. ** layer then attempts a rollback operation. If the error condition
  39934. ** persists, the pager enters the ERROR state via condition (1) above.
  39935. **
  39936. ** Condition (3) is necessary because it can be triggered by a read-only
  39937. ** statement executed within a transaction. In this case, if the error
  39938. ** code were simply returned to the user, the b-tree layer would not
  39939. ** automatically attempt a rollback, as it assumes that an error in a
  39940. ** read-only statement cannot leave the pager in an internally inconsistent
  39941. ** state.
  39942. **
  39943. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  39944. ** * There are one or more outstanding references to pages (after the
  39945. ** last reference is dropped the pager should move back to OPEN state).
  39946. ** * The pager is not an in-memory pager.
  39947. **
  39948. **
  39949. ** Notes:
  39950. **
  39951. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  39952. ** connection is open in WAL mode. A WAL connection is always in one
  39953. ** of the first four states.
  39954. **
  39955. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  39956. ** state. There are two exceptions: immediately after exclusive-mode has
  39957. ** been turned on (and before any read or write transactions are
  39958. ** executed), and when the pager is leaving the "error state".
  39959. **
  39960. ** * See also: assert_pager_state().
  39961. */
  39962. #define PAGER_OPEN 0
  39963. #define PAGER_READER 1
  39964. #define PAGER_WRITER_LOCKED 2
  39965. #define PAGER_WRITER_CACHEMOD 3
  39966. #define PAGER_WRITER_DBMOD 4
  39967. #define PAGER_WRITER_FINISHED 5
  39968. #define PAGER_ERROR 6
  39969. /*
  39970. ** The Pager.eLock variable is almost always set to one of the
  39971. ** following locking-states, according to the lock currently held on
  39972. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  39973. ** This variable is kept up to date as locks are taken and released by
  39974. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  39975. **
  39976. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  39977. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  39978. ** the operation was successful. In these circumstances pagerLockDb() and
  39979. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  39980. ** when unlocking the file, and only updated when locking the file if the
  39981. ** VFS call is successful. This way, the Pager.eLock variable may be set
  39982. ** to a less exclusive (lower) value than the lock that is actually held
  39983. ** at the system level, but it is never set to a more exclusive value.
  39984. **
  39985. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  39986. ** be a few redundant xLock() calls or a lock may be held for longer than
  39987. ** required, but nothing really goes wrong.
  39988. **
  39989. ** The exception is when the database file is unlocked as the pager moves
  39990. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  39991. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  39992. ** transition, by the same pager or any other). If the call to xUnlock()
  39993. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  39994. ** can confuse the call to xCheckReservedLock() call made later as part
  39995. ** of hot-journal detection.
  39996. **
  39997. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  39998. ** lock held by this process or any others". So xCheckReservedLock may
  39999. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  40000. ** doesn't know it because of a previous error in xUnlock). If this happens
  40001. ** a hot-journal may be mistaken for a journal being created by an active
  40002. ** transaction in another process, causing SQLite to read from the database
  40003. ** without rolling it back.
  40004. **
  40005. ** To work around this, if a call to xUnlock() fails when unlocking the
  40006. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  40007. ** is only changed back to a real locking state after a successful call
  40008. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  40009. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  40010. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  40011. ** lock on the database file before attempting to roll it back. See function
  40012. ** PagerSharedLock() for more detail.
  40013. **
  40014. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  40015. ** PAGER_OPEN state.
  40016. */
  40017. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  40018. /*
  40019. ** A macro used for invoking the codec if there is one
  40020. */
  40021. #ifdef SQLITE_HAS_CODEC
  40022. # define CODEC1(P,D,N,X,E) \
  40023. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  40024. # define CODEC2(P,D,N,X,E,O) \
  40025. if( P->xCodec==0 ){ O=(char*)D; }else \
  40026. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  40027. #else
  40028. # define CODEC1(P,D,N,X,E) /* NO-OP */
  40029. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  40030. #endif
  40031. /*
  40032. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  40033. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  40034. ** This could conceivably cause corruption following a power failure on
  40035. ** such a system. This is currently an undocumented limit.
  40036. */
  40037. #define MAX_SECTOR_SIZE 0x10000
  40038. /*
  40039. ** An instance of the following structure is allocated for each active
  40040. ** savepoint and statement transaction in the system. All such structures
  40041. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  40042. ** resized using sqlite3Realloc().
  40043. **
  40044. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  40045. ** set to 0. If a journal-header is written into the main journal while
  40046. ** the savepoint is active, then iHdrOffset is set to the byte offset
  40047. ** immediately following the last journal record written into the main
  40048. ** journal before the journal-header. This is required during savepoint
  40049. ** rollback (see pagerPlaybackSavepoint()).
  40050. */
  40051. typedef struct PagerSavepoint PagerSavepoint;
  40052. struct PagerSavepoint {
  40053. i64 iOffset; /* Starting offset in main journal */
  40054. i64 iHdrOffset; /* See above */
  40055. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  40056. Pgno nOrig; /* Original number of pages in file */
  40057. Pgno iSubRec; /* Index of first record in sub-journal */
  40058. #ifndef SQLITE_OMIT_WAL
  40059. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  40060. #endif
  40061. };
  40062. /*
  40063. ** Bits of the Pager.doNotSpill flag. See further description below.
  40064. */
  40065. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  40066. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  40067. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  40068. /*
  40069. ** An open page cache is an instance of struct Pager. A description of
  40070. ** some of the more important member variables follows:
  40071. **
  40072. ** eState
  40073. **
  40074. ** The current 'state' of the pager object. See the comment and state
  40075. ** diagram above for a description of the pager state.
  40076. **
  40077. ** eLock
  40078. **
  40079. ** For a real on-disk database, the current lock held on the database file -
  40080. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  40081. **
  40082. ** For a temporary or in-memory database (neither of which require any
  40083. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  40084. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  40085. ** logic into thinking that it already has all the locks it will ever
  40086. ** need (and no reason to release them).
  40087. **
  40088. ** In some (obscure) circumstances, this variable may also be set to
  40089. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  40090. ** details.
  40091. **
  40092. ** changeCountDone
  40093. **
  40094. ** This boolean variable is used to make sure that the change-counter
  40095. ** (the 4-byte header field at byte offset 24 of the database file) is
  40096. ** not updated more often than necessary.
  40097. **
  40098. ** It is set to true when the change-counter field is updated, which
  40099. ** can only happen if an exclusive lock is held on the database file.
  40100. ** It is cleared (set to false) whenever an exclusive lock is
  40101. ** relinquished on the database file. Each time a transaction is committed,
  40102. ** The changeCountDone flag is inspected. If it is true, the work of
  40103. ** updating the change-counter is omitted for the current transaction.
  40104. **
  40105. ** This mechanism means that when running in exclusive mode, a connection
  40106. ** need only update the change-counter once, for the first transaction
  40107. ** committed.
  40108. **
  40109. ** setMaster
  40110. **
  40111. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  40112. ** (or may not) specify a master-journal name to be written into the
  40113. ** journal file before it is synced to disk.
  40114. **
  40115. ** Whether or not a journal file contains a master-journal pointer affects
  40116. ** the way in which the journal file is finalized after the transaction is
  40117. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  40118. ** If a journal file does not contain a master-journal pointer, it is
  40119. ** finalized by overwriting the first journal header with zeroes. If
  40120. ** it does contain a master-journal pointer the journal file is finalized
  40121. ** by truncating it to zero bytes, just as if the connection were
  40122. ** running in "journal_mode=truncate" mode.
  40123. **
  40124. ** Journal files that contain master journal pointers cannot be finalized
  40125. ** simply by overwriting the first journal-header with zeroes, as the
  40126. ** master journal pointer could interfere with hot-journal rollback of any
  40127. ** subsequently interrupted transaction that reuses the journal file.
  40128. **
  40129. ** The flag is cleared as soon as the journal file is finalized (either
  40130. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  40131. ** journal file from being successfully finalized, the setMaster flag
  40132. ** is cleared anyway (and the pager will move to ERROR state).
  40133. **
  40134. ** doNotSpill
  40135. **
  40136. ** This variables control the behavior of cache-spills (calls made by
  40137. ** the pcache module to the pagerStress() routine to write cached data
  40138. ** to the file-system in order to free up memory).
  40139. **
  40140. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  40141. ** writing to the database from pagerStress() is disabled altogether.
  40142. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  40143. ** comes up during savepoint rollback that requires the pcache module
  40144. ** to allocate a new page to prevent the journal file from being written
  40145. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  40146. ** case is a user preference.
  40147. **
  40148. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
  40149. ** pagerStress() is permitted, but syncing the journal file is not.
  40150. ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
  40151. ** is larger than the database page-size in order to prevent a journal sync
  40152. ** from happening in between the journalling of two pages on the same sector.
  40153. **
  40154. ** subjInMemory
  40155. **
  40156. ** This is a boolean variable. If true, then any required sub-journal
  40157. ** is opened as an in-memory journal file. If false, then in-memory
  40158. ** sub-journals are only used for in-memory pager files.
  40159. **
  40160. ** This variable is updated by the upper layer each time a new
  40161. ** write-transaction is opened.
  40162. **
  40163. ** dbSize, dbOrigSize, dbFileSize
  40164. **
  40165. ** Variable dbSize is set to the number of pages in the database file.
  40166. ** It is valid in PAGER_READER and higher states (all states except for
  40167. ** OPEN and ERROR).
  40168. **
  40169. ** dbSize is set based on the size of the database file, which may be
  40170. ** larger than the size of the database (the value stored at offset
  40171. ** 28 of the database header by the btree). If the size of the file
  40172. ** is not an integer multiple of the page-size, the value stored in
  40173. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  40174. ** Except, any file that is greater than 0 bytes in size is considered
  40175. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  40176. ** to dbSize==1).
  40177. **
  40178. ** During a write-transaction, if pages with page-numbers greater than
  40179. ** dbSize are modified in the cache, dbSize is updated accordingly.
  40180. ** Similarly, if the database is truncated using PagerTruncateImage(),
  40181. ** dbSize is updated.
  40182. **
  40183. ** Variables dbOrigSize and dbFileSize are valid in states
  40184. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  40185. ** variable at the start of the transaction. It is used during rollback,
  40186. ** and to determine whether or not pages need to be journalled before
  40187. ** being modified.
  40188. **
  40189. ** Throughout a write-transaction, dbFileSize contains the size of
  40190. ** the file on disk in pages. It is set to a copy of dbSize when the
  40191. ** write-transaction is first opened, and updated when VFS calls are made
  40192. ** to write or truncate the database file on disk.
  40193. **
  40194. ** The only reason the dbFileSize variable is required is to suppress
  40195. ** unnecessary calls to xTruncate() after committing a transaction. If,
  40196. ** when a transaction is committed, the dbFileSize variable indicates
  40197. ** that the database file is larger than the database image (Pager.dbSize),
  40198. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  40199. ** to measure the database file on disk, and then truncates it if required.
  40200. ** dbFileSize is not used when rolling back a transaction. In this case
  40201. ** pager_truncate() is called unconditionally (which means there may be
  40202. ** a call to xFilesize() that is not strictly required). In either case,
  40203. ** pager_truncate() may cause the file to become smaller or larger.
  40204. **
  40205. ** dbHintSize
  40206. **
  40207. ** The dbHintSize variable is used to limit the number of calls made to
  40208. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  40209. **
  40210. ** dbHintSize is set to a copy of the dbSize variable when a
  40211. ** write-transaction is opened (at the same time as dbFileSize and
  40212. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  40213. ** dbHintSize is increased to the number of pages that correspond to the
  40214. ** size-hint passed to the method call. See pager_write_pagelist() for
  40215. ** details.
  40216. **
  40217. ** errCode
  40218. **
  40219. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  40220. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  40221. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  40222. ** sub-codes.
  40223. */
  40224. struct Pager {
  40225. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  40226. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  40227. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  40228. u8 useJournal; /* Use a rollback journal on this file */
  40229. u8 noSync; /* Do not sync the journal if true */
  40230. u8 fullSync; /* Do extra syncs of the journal for robustness */
  40231. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  40232. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  40233. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  40234. u8 tempFile; /* zFilename is a temporary or immutable file */
  40235. u8 noLock; /* Do not lock (except in WAL mode) */
  40236. u8 readOnly; /* True for a read-only database */
  40237. u8 memDb; /* True to inhibit all file I/O */
  40238. /**************************************************************************
  40239. ** The following block contains those class members that change during
  40240. ** routine operation. Class members not in this block are either fixed
  40241. ** when the pager is first created or else only change when there is a
  40242. ** significant mode change (such as changing the page_size, locking_mode,
  40243. ** or the journal_mode). From another view, these class members describe
  40244. ** the "state" of the pager, while other class members describe the
  40245. ** "configuration" of the pager.
  40246. */
  40247. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  40248. u8 eLock; /* Current lock held on database file */
  40249. u8 changeCountDone; /* Set after incrementing the change-counter */
  40250. u8 setMaster; /* True if a m-j name has been written to jrnl */
  40251. u8 doNotSpill; /* Do not spill the cache when non-zero */
  40252. u8 subjInMemory; /* True to use in-memory sub-journals */
  40253. u8 bUseFetch; /* True to use xFetch() */
  40254. u8 hasBeenUsed; /* True if any content previously read */
  40255. Pgno dbSize; /* Number of pages in the database */
  40256. Pgno dbOrigSize; /* dbSize before the current transaction */
  40257. Pgno dbFileSize; /* Number of pages in the database file */
  40258. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  40259. int errCode; /* One of several kinds of errors */
  40260. int nRec; /* Pages journalled since last j-header written */
  40261. u32 cksumInit; /* Quasi-random value added to every checksum */
  40262. u32 nSubRec; /* Number of records written to sub-journal */
  40263. Bitvec *pInJournal; /* One bit for each page in the database file */
  40264. sqlite3_file *fd; /* File descriptor for database */
  40265. sqlite3_file *jfd; /* File descriptor for main journal */
  40266. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  40267. i64 journalOff; /* Current write offset in the journal file */
  40268. i64 journalHdr; /* Byte offset to previous journal header */
  40269. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  40270. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  40271. int nSavepoint; /* Number of elements in aSavepoint[] */
  40272. u32 iDataVersion; /* Changes whenever database content changes */
  40273. char dbFileVers[16]; /* Changes whenever database file changes */
  40274. int nMmapOut; /* Number of mmap pages currently outstanding */
  40275. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  40276. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  40277. /*
  40278. ** End of the routinely-changing class members
  40279. ***************************************************************************/
  40280. u16 nExtra; /* Add this many bytes to each in-memory page */
  40281. i16 nReserve; /* Number of unused bytes at end of each page */
  40282. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  40283. u32 sectorSize; /* Assumed sector size during rollback */
  40284. int pageSize; /* Number of bytes in a page */
  40285. Pgno mxPgno; /* Maximum allowed size of the database */
  40286. i64 journalSizeLimit; /* Size limit for persistent journal files */
  40287. char *zFilename; /* Name of the database file */
  40288. char *zJournal; /* Name of the journal file */
  40289. int (*xBusyHandler)(void*); /* Function to call when busy */
  40290. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  40291. int aStat[3]; /* Total cache hits, misses and writes */
  40292. #ifdef SQLITE_TEST
  40293. int nRead; /* Database pages read */
  40294. #endif
  40295. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  40296. #ifdef SQLITE_HAS_CODEC
  40297. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  40298. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  40299. void (*xCodecFree)(void*); /* Destructor for the codec */
  40300. void *pCodec; /* First argument to xCodec... methods */
  40301. #endif
  40302. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  40303. PCache *pPCache; /* Pointer to page cache object */
  40304. #ifndef SQLITE_OMIT_WAL
  40305. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  40306. char *zWal; /* File name for write-ahead log */
  40307. #endif
  40308. };
  40309. /*
  40310. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  40311. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  40312. ** or CACHE_WRITE to sqlite3_db_status().
  40313. */
  40314. #define PAGER_STAT_HIT 0
  40315. #define PAGER_STAT_MISS 1
  40316. #define PAGER_STAT_WRITE 2
  40317. /*
  40318. ** The following global variables hold counters used for
  40319. ** testing purposes only. These variables do not exist in
  40320. ** a non-testing build. These variables are not thread-safe.
  40321. */
  40322. #ifdef SQLITE_TEST
  40323. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  40324. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  40325. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  40326. # define PAGER_INCR(v) v++
  40327. #else
  40328. # define PAGER_INCR(v)
  40329. #endif
  40330. /*
  40331. ** Journal files begin with the following magic string. The data
  40332. ** was obtained from /dev/random. It is used only as a sanity check.
  40333. **
  40334. ** Since version 2.8.0, the journal format contains additional sanity
  40335. ** checking information. If the power fails while the journal is being
  40336. ** written, semi-random garbage data might appear in the journal
  40337. ** file after power is restored. If an attempt is then made
  40338. ** to roll the journal back, the database could be corrupted. The additional
  40339. ** sanity checking data is an attempt to discover the garbage in the
  40340. ** journal and ignore it.
  40341. **
  40342. ** The sanity checking information for the new journal format consists
  40343. ** of a 32-bit checksum on each page of data. The checksum covers both
  40344. ** the page number and the pPager->pageSize bytes of data for the page.
  40345. ** This cksum is initialized to a 32-bit random value that appears in the
  40346. ** journal file right after the header. The random initializer is important,
  40347. ** because garbage data that appears at the end of a journal is likely
  40348. ** data that was once in other files that have now been deleted. If the
  40349. ** garbage data came from an obsolete journal file, the checksums might
  40350. ** be correct. But by initializing the checksum to random value which
  40351. ** is different for every journal, we minimize that risk.
  40352. */
  40353. static const unsigned char aJournalMagic[] = {
  40354. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  40355. };
  40356. /*
  40357. ** The size of the of each page record in the journal is given by
  40358. ** the following macro.
  40359. */
  40360. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  40361. /*
  40362. ** The journal header size for this pager. This is usually the same
  40363. ** size as a single disk sector. See also setSectorSize().
  40364. */
  40365. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  40366. /*
  40367. ** The macro MEMDB is true if we are dealing with an in-memory database.
  40368. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  40369. ** the value of MEMDB will be a constant and the compiler will optimize
  40370. ** out code that would never execute.
  40371. */
  40372. #ifdef SQLITE_OMIT_MEMORYDB
  40373. # define MEMDB 0
  40374. #else
  40375. # define MEMDB pPager->memDb
  40376. #endif
  40377. /*
  40378. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  40379. ** interfaces to access the database using memory-mapped I/O.
  40380. */
  40381. #if SQLITE_MAX_MMAP_SIZE>0
  40382. # define USEFETCH(x) ((x)->bUseFetch)
  40383. #else
  40384. # define USEFETCH(x) 0
  40385. #endif
  40386. /*
  40387. ** The maximum legal page number is (2^31 - 1).
  40388. */
  40389. #define PAGER_MAX_PGNO 2147483647
  40390. /*
  40391. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  40392. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  40393. **
  40394. ** This is so that expressions can be written as:
  40395. **
  40396. ** if( isOpen(pPager->jfd) ){ ...
  40397. **
  40398. ** instead of
  40399. **
  40400. ** if( pPager->jfd->pMethods ){ ...
  40401. */
  40402. #define isOpen(pFd) ((pFd)->pMethods!=0)
  40403. /*
  40404. ** Return true if this pager uses a write-ahead log instead of the usual
  40405. ** rollback journal. Otherwise false.
  40406. */
  40407. #ifndef SQLITE_OMIT_WAL
  40408. static int pagerUseWal(Pager *pPager){
  40409. return (pPager->pWal!=0);
  40410. }
  40411. #else
  40412. # define pagerUseWal(x) 0
  40413. # define pagerRollbackWal(x) 0
  40414. # define pagerWalFrames(v,w,x,y) 0
  40415. # define pagerOpenWalIfPresent(z) SQLITE_OK
  40416. # define pagerBeginReadTransaction(z) SQLITE_OK
  40417. #endif
  40418. #ifndef NDEBUG
  40419. /*
  40420. ** Usage:
  40421. **
  40422. ** assert( assert_pager_state(pPager) );
  40423. **
  40424. ** This function runs many asserts to try to find inconsistencies in
  40425. ** the internal state of the Pager object.
  40426. */
  40427. static int assert_pager_state(Pager *p){
  40428. Pager *pPager = p;
  40429. /* State must be valid. */
  40430. assert( p->eState==PAGER_OPEN
  40431. || p->eState==PAGER_READER
  40432. || p->eState==PAGER_WRITER_LOCKED
  40433. || p->eState==PAGER_WRITER_CACHEMOD
  40434. || p->eState==PAGER_WRITER_DBMOD
  40435. || p->eState==PAGER_WRITER_FINISHED
  40436. || p->eState==PAGER_ERROR
  40437. );
  40438. /* Regardless of the current state, a temp-file connection always behaves
  40439. ** as if it has an exclusive lock on the database file. It never updates
  40440. ** the change-counter field, so the changeCountDone flag is always set.
  40441. */
  40442. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  40443. assert( p->tempFile==0 || pPager->changeCountDone );
  40444. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  40445. ** And if the journal-mode is "OFF", the journal file must not be open.
  40446. */
  40447. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  40448. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  40449. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  40450. ** this means an in-memory pager performs no IO at all, it cannot encounter
  40451. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  40452. ** a journal file. (although the in-memory journal implementation may
  40453. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  40454. ** is therefore not possible for an in-memory pager to enter the ERROR
  40455. ** state.
  40456. */
  40457. if( MEMDB ){
  40458. assert( p->noSync );
  40459. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  40460. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  40461. );
  40462. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  40463. assert( pagerUseWal(p)==0 );
  40464. }
  40465. /* If changeCountDone is set, a RESERVED lock or greater must be held
  40466. ** on the file.
  40467. */
  40468. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  40469. assert( p->eLock!=PENDING_LOCK );
  40470. switch( p->eState ){
  40471. case PAGER_OPEN:
  40472. assert( !MEMDB );
  40473. assert( pPager->errCode==SQLITE_OK );
  40474. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  40475. break;
  40476. case PAGER_READER:
  40477. assert( pPager->errCode==SQLITE_OK );
  40478. assert( p->eLock!=UNKNOWN_LOCK );
  40479. assert( p->eLock>=SHARED_LOCK );
  40480. break;
  40481. case PAGER_WRITER_LOCKED:
  40482. assert( p->eLock!=UNKNOWN_LOCK );
  40483. assert( pPager->errCode==SQLITE_OK );
  40484. if( !pagerUseWal(pPager) ){
  40485. assert( p->eLock>=RESERVED_LOCK );
  40486. }
  40487. assert( pPager->dbSize==pPager->dbOrigSize );
  40488. assert( pPager->dbOrigSize==pPager->dbFileSize );
  40489. assert( pPager->dbOrigSize==pPager->dbHintSize );
  40490. assert( pPager->setMaster==0 );
  40491. break;
  40492. case PAGER_WRITER_CACHEMOD:
  40493. assert( p->eLock!=UNKNOWN_LOCK );
  40494. assert( pPager->errCode==SQLITE_OK );
  40495. if( !pagerUseWal(pPager) ){
  40496. /* It is possible that if journal_mode=wal here that neither the
  40497. ** journal file nor the WAL file are open. This happens during
  40498. ** a rollback transaction that switches from journal_mode=off
  40499. ** to journal_mode=wal.
  40500. */
  40501. assert( p->eLock>=RESERVED_LOCK );
  40502. assert( isOpen(p->jfd)
  40503. || p->journalMode==PAGER_JOURNALMODE_OFF
  40504. || p->journalMode==PAGER_JOURNALMODE_WAL
  40505. );
  40506. }
  40507. assert( pPager->dbOrigSize==pPager->dbFileSize );
  40508. assert( pPager->dbOrigSize==pPager->dbHintSize );
  40509. break;
  40510. case PAGER_WRITER_DBMOD:
  40511. assert( p->eLock==EXCLUSIVE_LOCK );
  40512. assert( pPager->errCode==SQLITE_OK );
  40513. assert( !pagerUseWal(pPager) );
  40514. assert( p->eLock>=EXCLUSIVE_LOCK );
  40515. assert( isOpen(p->jfd)
  40516. || p->journalMode==PAGER_JOURNALMODE_OFF
  40517. || p->journalMode==PAGER_JOURNALMODE_WAL
  40518. );
  40519. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  40520. break;
  40521. case PAGER_WRITER_FINISHED:
  40522. assert( p->eLock==EXCLUSIVE_LOCK );
  40523. assert( pPager->errCode==SQLITE_OK );
  40524. assert( !pagerUseWal(pPager) );
  40525. assert( isOpen(p->jfd)
  40526. || p->journalMode==PAGER_JOURNALMODE_OFF
  40527. || p->journalMode==PAGER_JOURNALMODE_WAL
  40528. );
  40529. break;
  40530. case PAGER_ERROR:
  40531. /* There must be at least one outstanding reference to the pager if
  40532. ** in ERROR state. Otherwise the pager should have already dropped
  40533. ** back to OPEN state.
  40534. */
  40535. assert( pPager->errCode!=SQLITE_OK );
  40536. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  40537. break;
  40538. }
  40539. return 1;
  40540. }
  40541. #endif /* ifndef NDEBUG */
  40542. #ifdef SQLITE_DEBUG
  40543. /*
  40544. ** Return a pointer to a human readable string in a static buffer
  40545. ** containing the state of the Pager object passed as an argument. This
  40546. ** is intended to be used within debuggers. For example, as an alternative
  40547. ** to "print *pPager" in gdb:
  40548. **
  40549. ** (gdb) printf "%s", print_pager_state(pPager)
  40550. */
  40551. static char *print_pager_state(Pager *p){
  40552. static char zRet[1024];
  40553. sqlite3_snprintf(1024, zRet,
  40554. "Filename: %s\n"
  40555. "State: %s errCode=%d\n"
  40556. "Lock: %s\n"
  40557. "Locking mode: locking_mode=%s\n"
  40558. "Journal mode: journal_mode=%s\n"
  40559. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  40560. "Journal: journalOff=%lld journalHdr=%lld\n"
  40561. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  40562. , p->zFilename
  40563. , p->eState==PAGER_OPEN ? "OPEN" :
  40564. p->eState==PAGER_READER ? "READER" :
  40565. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  40566. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  40567. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  40568. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  40569. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  40570. , (int)p->errCode
  40571. , p->eLock==NO_LOCK ? "NO_LOCK" :
  40572. p->eLock==RESERVED_LOCK ? "RESERVED" :
  40573. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  40574. p->eLock==SHARED_LOCK ? "SHARED" :
  40575. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  40576. , p->exclusiveMode ? "exclusive" : "normal"
  40577. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  40578. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  40579. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  40580. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  40581. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  40582. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  40583. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  40584. , p->journalOff, p->journalHdr
  40585. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  40586. );
  40587. return zRet;
  40588. }
  40589. #endif
  40590. /*
  40591. ** Return true if it is necessary to write page *pPg into the sub-journal.
  40592. ** A page needs to be written into the sub-journal if there exists one
  40593. ** or more open savepoints for which:
  40594. **
  40595. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  40596. ** * The bit corresponding to the page-number is not set in
  40597. ** PagerSavepoint.pInSavepoint.
  40598. */
  40599. static int subjRequiresPage(PgHdr *pPg){
  40600. Pager *pPager = pPg->pPager;
  40601. PagerSavepoint *p;
  40602. Pgno pgno = pPg->pgno;
  40603. int i;
  40604. for(i=0; i<pPager->nSavepoint; i++){
  40605. p = &pPager->aSavepoint[i];
  40606. if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
  40607. return 1;
  40608. }
  40609. }
  40610. return 0;
  40611. }
  40612. #ifdef SQLITE_DEBUG
  40613. /*
  40614. ** Return true if the page is already in the journal file.
  40615. */
  40616. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  40617. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  40618. }
  40619. #endif
  40620. /*
  40621. ** Read a 32-bit integer from the given file descriptor. Store the integer
  40622. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  40623. ** error code is something goes wrong.
  40624. **
  40625. ** All values are stored on disk as big-endian.
  40626. */
  40627. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  40628. unsigned char ac[4];
  40629. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  40630. if( rc==SQLITE_OK ){
  40631. *pRes = sqlite3Get4byte(ac);
  40632. }
  40633. return rc;
  40634. }
  40635. /*
  40636. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  40637. */
  40638. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  40639. /*
  40640. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  40641. ** on success or an error code is something goes wrong.
  40642. */
  40643. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  40644. char ac[4];
  40645. put32bits(ac, val);
  40646. return sqlite3OsWrite(fd, ac, 4, offset);
  40647. }
  40648. /*
  40649. ** Unlock the database file to level eLock, which must be either NO_LOCK
  40650. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  40651. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  40652. **
  40653. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  40654. ** called, do not modify it. See the comment above the #define of
  40655. ** UNKNOWN_LOCK for an explanation of this.
  40656. */
  40657. static int pagerUnlockDb(Pager *pPager, int eLock){
  40658. int rc = SQLITE_OK;
  40659. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  40660. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  40661. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  40662. if( isOpen(pPager->fd) ){
  40663. assert( pPager->eLock>=eLock );
  40664. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  40665. if( pPager->eLock!=UNKNOWN_LOCK ){
  40666. pPager->eLock = (u8)eLock;
  40667. }
  40668. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  40669. }
  40670. return rc;
  40671. }
  40672. /*
  40673. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  40674. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  40675. ** Pager.eLock variable to the new locking state.
  40676. **
  40677. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  40678. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  40679. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  40680. ** of this.
  40681. */
  40682. static int pagerLockDb(Pager *pPager, int eLock){
  40683. int rc = SQLITE_OK;
  40684. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  40685. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  40686. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  40687. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  40688. pPager->eLock = (u8)eLock;
  40689. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  40690. }
  40691. }
  40692. return rc;
  40693. }
  40694. /*
  40695. ** This function determines whether or not the atomic-write optimization
  40696. ** can be used with this pager. The optimization can be used if:
  40697. **
  40698. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  40699. ** a database page may be written atomically, and
  40700. ** (b) the value returned by OsSectorSize() is less than or equal
  40701. ** to the page size.
  40702. **
  40703. ** The optimization is also always enabled for temporary files. It is
  40704. ** an error to call this function if pPager is opened on an in-memory
  40705. ** database.
  40706. **
  40707. ** If the optimization cannot be used, 0 is returned. If it can be used,
  40708. ** then the value returned is the size of the journal file when it
  40709. ** contains rollback data for exactly one page.
  40710. */
  40711. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40712. static int jrnlBufferSize(Pager *pPager){
  40713. assert( !MEMDB );
  40714. if( !pPager->tempFile ){
  40715. int dc; /* Device characteristics */
  40716. int nSector; /* Sector size */
  40717. int szPage; /* Page size */
  40718. assert( isOpen(pPager->fd) );
  40719. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  40720. nSector = pPager->sectorSize;
  40721. szPage = pPager->pageSize;
  40722. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  40723. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  40724. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  40725. return 0;
  40726. }
  40727. }
  40728. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  40729. }
  40730. #endif
  40731. /*
  40732. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  40733. ** on the cache using a hash function. This is used for testing
  40734. ** and debugging only.
  40735. */
  40736. #ifdef SQLITE_CHECK_PAGES
  40737. /*
  40738. ** Return a 32-bit hash of the page data for pPage.
  40739. */
  40740. static u32 pager_datahash(int nByte, unsigned char *pData){
  40741. u32 hash = 0;
  40742. int i;
  40743. for(i=0; i<nByte; i++){
  40744. hash = (hash*1039) + pData[i];
  40745. }
  40746. return hash;
  40747. }
  40748. static u32 pager_pagehash(PgHdr *pPage){
  40749. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  40750. }
  40751. static void pager_set_pagehash(PgHdr *pPage){
  40752. pPage->pageHash = pager_pagehash(pPage);
  40753. }
  40754. /*
  40755. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  40756. ** is defined, and NDEBUG is not defined, an assert() statement checks
  40757. ** that the page is either dirty or still matches the calculated page-hash.
  40758. */
  40759. #define CHECK_PAGE(x) checkPage(x)
  40760. static void checkPage(PgHdr *pPg){
  40761. Pager *pPager = pPg->pPager;
  40762. assert( pPager->eState!=PAGER_ERROR );
  40763. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  40764. }
  40765. #else
  40766. #define pager_datahash(X,Y) 0
  40767. #define pager_pagehash(X) 0
  40768. #define pager_set_pagehash(X)
  40769. #define CHECK_PAGE(x)
  40770. #endif /* SQLITE_CHECK_PAGES */
  40771. /*
  40772. ** When this is called the journal file for pager pPager must be open.
  40773. ** This function attempts to read a master journal file name from the
  40774. ** end of the file and, if successful, copies it into memory supplied
  40775. ** by the caller. See comments above writeMasterJournal() for the format
  40776. ** used to store a master journal file name at the end of a journal file.
  40777. **
  40778. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  40779. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  40780. ** enough space to write the master journal name). If the master journal
  40781. ** name in the journal is longer than nMaster bytes (including a
  40782. ** nul-terminator), then this is handled as if no master journal name
  40783. ** were present in the journal.
  40784. **
  40785. ** If a master journal file name is present at the end of the journal
  40786. ** file, then it is copied into the buffer pointed to by zMaster. A
  40787. ** nul-terminator byte is appended to the buffer following the master
  40788. ** journal file name.
  40789. **
  40790. ** If it is determined that no master journal file name is present
  40791. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  40792. **
  40793. ** If an error occurs while reading from the journal file, an SQLite
  40794. ** error code is returned.
  40795. */
  40796. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  40797. int rc; /* Return code */
  40798. u32 len; /* Length in bytes of master journal name */
  40799. i64 szJ; /* Total size in bytes of journal file pJrnl */
  40800. u32 cksum; /* MJ checksum value read from journal */
  40801. u32 u; /* Unsigned loop counter */
  40802. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  40803. zMaster[0] = '\0';
  40804. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  40805. || szJ<16
  40806. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  40807. || len>=nMaster
  40808. || len==0
  40809. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  40810. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  40811. || memcmp(aMagic, aJournalMagic, 8)
  40812. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  40813. ){
  40814. return rc;
  40815. }
  40816. /* See if the checksum matches the master journal name */
  40817. for(u=0; u<len; u++){
  40818. cksum -= zMaster[u];
  40819. }
  40820. if( cksum ){
  40821. /* If the checksum doesn't add up, then one or more of the disk sectors
  40822. ** containing the master journal filename is corrupted. This means
  40823. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  40824. ** master-journal filename.
  40825. */
  40826. len = 0;
  40827. }
  40828. zMaster[len] = '\0';
  40829. return SQLITE_OK;
  40830. }
  40831. /*
  40832. ** Return the offset of the sector boundary at or immediately
  40833. ** following the value in pPager->journalOff, assuming a sector
  40834. ** size of pPager->sectorSize bytes.
  40835. **
  40836. ** i.e for a sector size of 512:
  40837. **
  40838. ** Pager.journalOff Return value
  40839. ** ---------------------------------------
  40840. ** 0 0
  40841. ** 512 512
  40842. ** 100 512
  40843. ** 2000 2048
  40844. **
  40845. */
  40846. static i64 journalHdrOffset(Pager *pPager){
  40847. i64 offset = 0;
  40848. i64 c = pPager->journalOff;
  40849. if( c ){
  40850. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  40851. }
  40852. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  40853. assert( offset>=c );
  40854. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  40855. return offset;
  40856. }
  40857. /*
  40858. ** The journal file must be open when this function is called.
  40859. **
  40860. ** This function is a no-op if the journal file has not been written to
  40861. ** within the current transaction (i.e. if Pager.journalOff==0).
  40862. **
  40863. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  40864. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  40865. ** zero the 28-byte header at the start of the journal file. In either case,
  40866. ** if the pager is not in no-sync mode, sync the journal file immediately
  40867. ** after writing or truncating it.
  40868. **
  40869. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  40870. ** following the truncation or zeroing described above the size of the
  40871. ** journal file in bytes is larger than this value, then truncate the
  40872. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  40873. ** not need to be synced following this operation.
  40874. **
  40875. ** If an IO error occurs, abandon processing and return the IO error code.
  40876. ** Otherwise, return SQLITE_OK.
  40877. */
  40878. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  40879. int rc = SQLITE_OK; /* Return code */
  40880. assert( isOpen(pPager->jfd) );
  40881. if( pPager->journalOff ){
  40882. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  40883. IOTRACE(("JZEROHDR %p\n", pPager))
  40884. if( doTruncate || iLimit==0 ){
  40885. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40886. }else{
  40887. static const char zeroHdr[28] = {0};
  40888. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  40889. }
  40890. if( rc==SQLITE_OK && !pPager->noSync ){
  40891. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  40892. }
  40893. /* At this point the transaction is committed but the write lock
  40894. ** is still held on the file. If there is a size limit configured for
  40895. ** the persistent journal and the journal file currently consumes more
  40896. ** space than that limit allows for, truncate it now. There is no need
  40897. ** to sync the file following this operation.
  40898. */
  40899. if( rc==SQLITE_OK && iLimit>0 ){
  40900. i64 sz;
  40901. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  40902. if( rc==SQLITE_OK && sz>iLimit ){
  40903. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  40904. }
  40905. }
  40906. }
  40907. return rc;
  40908. }
  40909. /*
  40910. ** The journal file must be open when this routine is called. A journal
  40911. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  40912. ** current location.
  40913. **
  40914. ** The format for the journal header is as follows:
  40915. ** - 8 bytes: Magic identifying journal format.
  40916. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  40917. ** - 4 bytes: Random number used for page hash.
  40918. ** - 4 bytes: Initial database page count.
  40919. ** - 4 bytes: Sector size used by the process that wrote this journal.
  40920. ** - 4 bytes: Database page size.
  40921. **
  40922. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  40923. */
  40924. static int writeJournalHdr(Pager *pPager){
  40925. int rc = SQLITE_OK; /* Return code */
  40926. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  40927. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  40928. u32 nWrite; /* Bytes of header sector written */
  40929. int ii; /* Loop counter */
  40930. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  40931. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  40932. nHeader = JOURNAL_HDR_SZ(pPager);
  40933. }
  40934. /* If there are active savepoints and any of them were created
  40935. ** since the most recent journal header was written, update the
  40936. ** PagerSavepoint.iHdrOffset fields now.
  40937. */
  40938. for(ii=0; ii<pPager->nSavepoint; ii++){
  40939. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  40940. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  40941. }
  40942. }
  40943. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  40944. /*
  40945. ** Write the nRec Field - the number of page records that follow this
  40946. ** journal header. Normally, zero is written to this value at this time.
  40947. ** After the records are added to the journal (and the journal synced,
  40948. ** if in full-sync mode), the zero is overwritten with the true number
  40949. ** of records (see syncJournal()).
  40950. **
  40951. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  40952. ** reading the journal this value tells SQLite to assume that the
  40953. ** rest of the journal file contains valid page records. This assumption
  40954. ** is dangerous, as if a failure occurred whilst writing to the journal
  40955. ** file it may contain some garbage data. There are two scenarios
  40956. ** where this risk can be ignored:
  40957. **
  40958. ** * When the pager is in no-sync mode. Corruption can follow a
  40959. ** power failure in this case anyway.
  40960. **
  40961. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  40962. ** that garbage data is never appended to the journal file.
  40963. */
  40964. assert( isOpen(pPager->fd) || pPager->noSync );
  40965. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  40966. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  40967. ){
  40968. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  40969. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  40970. }else{
  40971. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  40972. }
  40973. /* The random check-hash initializer */
  40974. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  40975. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  40976. /* The initial database size */
  40977. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  40978. /* The assumed sector size for this process */
  40979. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  40980. /* The page size */
  40981. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  40982. /* Initializing the tail of the buffer is not necessary. Everything
  40983. ** works find if the following memset() is omitted. But initializing
  40984. ** the memory prevents valgrind from complaining, so we are willing to
  40985. ** take the performance hit.
  40986. */
  40987. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  40988. nHeader-(sizeof(aJournalMagic)+20));
  40989. /* In theory, it is only necessary to write the 28 bytes that the
  40990. ** journal header consumes to the journal file here. Then increment the
  40991. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  40992. ** record is written to the following sector (leaving a gap in the file
  40993. ** that will be implicitly filled in by the OS).
  40994. **
  40995. ** However it has been discovered that on some systems this pattern can
  40996. ** be significantly slower than contiguously writing data to the file,
  40997. ** even if that means explicitly writing data to the block of
  40998. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  40999. ** is done.
  41000. **
  41001. ** The loop is required here in case the sector-size is larger than the
  41002. ** database page size. Since the zHeader buffer is only Pager.pageSize
  41003. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  41004. ** to populate the entire journal header sector.
  41005. */
  41006. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  41007. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  41008. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  41009. assert( pPager->journalHdr <= pPager->journalOff );
  41010. pPager->journalOff += nHeader;
  41011. }
  41012. return rc;
  41013. }
  41014. /*
  41015. ** The journal file must be open when this is called. A journal header file
  41016. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  41017. ** file. The current location in the journal file is given by
  41018. ** pPager->journalOff. See comments above function writeJournalHdr() for
  41019. ** a description of the journal header format.
  41020. **
  41021. ** If the header is read successfully, *pNRec is set to the number of
  41022. ** page records following this header and *pDbSize is set to the size of the
  41023. ** database before the transaction began, in pages. Also, pPager->cksumInit
  41024. ** is set to the value read from the journal header. SQLITE_OK is returned
  41025. ** in this case.
  41026. **
  41027. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  41028. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  41029. ** cannot be read from the journal file an error code is returned.
  41030. */
  41031. static int readJournalHdr(
  41032. Pager *pPager, /* Pager object */
  41033. int isHot,
  41034. i64 journalSize, /* Size of the open journal file in bytes */
  41035. u32 *pNRec, /* OUT: Value read from the nRec field */
  41036. u32 *pDbSize /* OUT: Value of original database size field */
  41037. ){
  41038. int rc; /* Return code */
  41039. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  41040. i64 iHdrOff; /* Offset of journal header being read */
  41041. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  41042. /* Advance Pager.journalOff to the start of the next sector. If the
  41043. ** journal file is too small for there to be a header stored at this
  41044. ** point, return SQLITE_DONE.
  41045. */
  41046. pPager->journalOff = journalHdrOffset(pPager);
  41047. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  41048. return SQLITE_DONE;
  41049. }
  41050. iHdrOff = pPager->journalOff;
  41051. /* Read in the first 8 bytes of the journal header. If they do not match
  41052. ** the magic string found at the start of each journal header, return
  41053. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  41054. ** proceed.
  41055. */
  41056. if( isHot || iHdrOff!=pPager->journalHdr ){
  41057. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  41058. if( rc ){
  41059. return rc;
  41060. }
  41061. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  41062. return SQLITE_DONE;
  41063. }
  41064. }
  41065. /* Read the first three 32-bit fields of the journal header: The nRec
  41066. ** field, the checksum-initializer and the database size at the start
  41067. ** of the transaction. Return an error code if anything goes wrong.
  41068. */
  41069. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  41070. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  41071. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  41072. ){
  41073. return rc;
  41074. }
  41075. if( pPager->journalOff==0 ){
  41076. u32 iPageSize; /* Page-size field of journal header */
  41077. u32 iSectorSize; /* Sector-size field of journal header */
  41078. /* Read the page-size and sector-size journal header fields. */
  41079. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  41080. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  41081. ){
  41082. return rc;
  41083. }
  41084. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  41085. ** journal header to zero. In this case, assume that the Pager.pageSize
  41086. ** variable is already set to the correct page size.
  41087. */
  41088. if( iPageSize==0 ){
  41089. iPageSize = pPager->pageSize;
  41090. }
  41091. /* Check that the values read from the page-size and sector-size fields
  41092. ** are within range. To be 'in range', both values need to be a power
  41093. ** of two greater than or equal to 512 or 32, and not greater than their
  41094. ** respective compile time maximum limits.
  41095. */
  41096. if( iPageSize<512 || iSectorSize<32
  41097. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  41098. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  41099. ){
  41100. /* If the either the page-size or sector-size in the journal-header is
  41101. ** invalid, then the process that wrote the journal-header must have
  41102. ** crashed before the header was synced. In this case stop reading
  41103. ** the journal file here.
  41104. */
  41105. return SQLITE_DONE;
  41106. }
  41107. /* Update the page-size to match the value read from the journal.
  41108. ** Use a testcase() macro to make sure that malloc failure within
  41109. ** PagerSetPagesize() is tested.
  41110. */
  41111. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  41112. testcase( rc!=SQLITE_OK );
  41113. /* Update the assumed sector-size to match the value used by
  41114. ** the process that created this journal. If this journal was
  41115. ** created by a process other than this one, then this routine
  41116. ** is being called from within pager_playback(). The local value
  41117. ** of Pager.sectorSize is restored at the end of that routine.
  41118. */
  41119. pPager->sectorSize = iSectorSize;
  41120. }
  41121. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  41122. return rc;
  41123. }
  41124. /*
  41125. ** Write the supplied master journal name into the journal file for pager
  41126. ** pPager at the current location. The master journal name must be the last
  41127. ** thing written to a journal file. If the pager is in full-sync mode, the
  41128. ** journal file descriptor is advanced to the next sector boundary before
  41129. ** anything is written. The format is:
  41130. **
  41131. ** + 4 bytes: PAGER_MJ_PGNO.
  41132. ** + N bytes: Master journal filename in utf-8.
  41133. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  41134. ** + 4 bytes: Master journal name checksum.
  41135. ** + 8 bytes: aJournalMagic[].
  41136. **
  41137. ** The master journal page checksum is the sum of the bytes in the master
  41138. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  41139. **
  41140. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  41141. ** this call is a no-op.
  41142. */
  41143. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  41144. int rc; /* Return code */
  41145. int nMaster; /* Length of string zMaster */
  41146. i64 iHdrOff; /* Offset of header in journal file */
  41147. i64 jrnlSize; /* Size of journal file on disk */
  41148. u32 cksum = 0; /* Checksum of string zMaster */
  41149. assert( pPager->setMaster==0 );
  41150. assert( !pagerUseWal(pPager) );
  41151. if( !zMaster
  41152. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  41153. || !isOpen(pPager->jfd)
  41154. ){
  41155. return SQLITE_OK;
  41156. }
  41157. pPager->setMaster = 1;
  41158. assert( pPager->journalHdr <= pPager->journalOff );
  41159. /* Calculate the length in bytes and the checksum of zMaster */
  41160. for(nMaster=0; zMaster[nMaster]; nMaster++){
  41161. cksum += zMaster[nMaster];
  41162. }
  41163. /* If in full-sync mode, advance to the next disk sector before writing
  41164. ** the master journal name. This is in case the previous page written to
  41165. ** the journal has already been synced.
  41166. */
  41167. if( pPager->fullSync ){
  41168. pPager->journalOff = journalHdrOffset(pPager);
  41169. }
  41170. iHdrOff = pPager->journalOff;
  41171. /* Write the master journal data to the end of the journal file. If
  41172. ** an error occurs, return the error code to the caller.
  41173. */
  41174. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  41175. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  41176. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  41177. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  41178. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
  41179. iHdrOff+4+nMaster+8)))
  41180. ){
  41181. return rc;
  41182. }
  41183. pPager->journalOff += (nMaster+20);
  41184. /* If the pager is in peristent-journal mode, then the physical
  41185. ** journal-file may extend past the end of the master-journal name
  41186. ** and 8 bytes of magic data just written to the file. This is
  41187. ** dangerous because the code to rollback a hot-journal file
  41188. ** will not be able to find the master-journal name to determine
  41189. ** whether or not the journal is hot.
  41190. **
  41191. ** Easiest thing to do in this scenario is to truncate the journal
  41192. ** file to the required size.
  41193. */
  41194. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  41195. && jrnlSize>pPager->journalOff
  41196. ){
  41197. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  41198. }
  41199. return rc;
  41200. }
  41201. /*
  41202. ** Discard the entire contents of the in-memory page-cache.
  41203. */
  41204. static void pager_reset(Pager *pPager){
  41205. pPager->iDataVersion++;
  41206. sqlite3BackupRestart(pPager->pBackup);
  41207. sqlite3PcacheClear(pPager->pPCache);
  41208. }
  41209. /*
  41210. ** Return the pPager->iDataVersion value
  41211. */
  41212. SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
  41213. assert( pPager->eState>PAGER_OPEN );
  41214. return pPager->iDataVersion;
  41215. }
  41216. /*
  41217. ** Free all structures in the Pager.aSavepoint[] array and set both
  41218. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  41219. ** if it is open and the pager is not in exclusive mode.
  41220. */
  41221. static void releaseAllSavepoints(Pager *pPager){
  41222. int ii; /* Iterator for looping through Pager.aSavepoint */
  41223. for(ii=0; ii<pPager->nSavepoint; ii++){
  41224. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  41225. }
  41226. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  41227. sqlite3OsClose(pPager->sjfd);
  41228. }
  41229. sqlite3_free(pPager->aSavepoint);
  41230. pPager->aSavepoint = 0;
  41231. pPager->nSavepoint = 0;
  41232. pPager->nSubRec = 0;
  41233. }
  41234. /*
  41235. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  41236. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  41237. ** or SQLITE_NOMEM if a malloc failure occurs.
  41238. */
  41239. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  41240. int ii; /* Loop counter */
  41241. int rc = SQLITE_OK; /* Result code */
  41242. for(ii=0; ii<pPager->nSavepoint; ii++){
  41243. PagerSavepoint *p = &pPager->aSavepoint[ii];
  41244. if( pgno<=p->nOrig ){
  41245. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  41246. testcase( rc==SQLITE_NOMEM );
  41247. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  41248. }
  41249. }
  41250. return rc;
  41251. }
  41252. /*
  41253. ** This function is a no-op if the pager is in exclusive mode and not
  41254. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  41255. ** state.
  41256. **
  41257. ** If the pager is not in exclusive-access mode, the database file is
  41258. ** completely unlocked. If the file is unlocked and the file-system does
  41259. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  41260. ** closed (if it is open).
  41261. **
  41262. ** If the pager is in ERROR state when this function is called, the
  41263. ** contents of the pager cache are discarded before switching back to
  41264. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  41265. ** or not, any journal file left in the file-system will be treated
  41266. ** as a hot-journal and rolled back the next time a read-transaction
  41267. ** is opened (by this or by any other connection).
  41268. */
  41269. static void pager_unlock(Pager *pPager){
  41270. assert( pPager->eState==PAGER_READER
  41271. || pPager->eState==PAGER_OPEN
  41272. || pPager->eState==PAGER_ERROR
  41273. );
  41274. sqlite3BitvecDestroy(pPager->pInJournal);
  41275. pPager->pInJournal = 0;
  41276. releaseAllSavepoints(pPager);
  41277. if( pagerUseWal(pPager) ){
  41278. assert( !isOpen(pPager->jfd) );
  41279. sqlite3WalEndReadTransaction(pPager->pWal);
  41280. pPager->eState = PAGER_OPEN;
  41281. }else if( !pPager->exclusiveMode ){
  41282. int rc; /* Error code returned by pagerUnlockDb() */
  41283. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  41284. /* If the operating system support deletion of open files, then
  41285. ** close the journal file when dropping the database lock. Otherwise
  41286. ** another connection with journal_mode=delete might delete the file
  41287. ** out from under us.
  41288. */
  41289. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  41290. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  41291. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  41292. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  41293. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  41294. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  41295. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  41296. || 1!=(pPager->journalMode & 5)
  41297. ){
  41298. sqlite3OsClose(pPager->jfd);
  41299. }
  41300. /* If the pager is in the ERROR state and the call to unlock the database
  41301. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  41302. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  41303. ** is necessary.
  41304. */
  41305. rc = pagerUnlockDb(pPager, NO_LOCK);
  41306. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  41307. pPager->eLock = UNKNOWN_LOCK;
  41308. }
  41309. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  41310. ** without clearing the error code. This is intentional - the error
  41311. ** code is cleared and the cache reset in the block below.
  41312. */
  41313. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  41314. pPager->changeCountDone = 0;
  41315. pPager->eState = PAGER_OPEN;
  41316. }
  41317. /* If Pager.errCode is set, the contents of the pager cache cannot be
  41318. ** trusted. Now that there are no outstanding references to the pager,
  41319. ** it can safely move back to PAGER_OPEN state. This happens in both
  41320. ** normal and exclusive-locking mode.
  41321. */
  41322. if( pPager->errCode ){
  41323. assert( !MEMDB );
  41324. pager_reset(pPager);
  41325. pPager->changeCountDone = pPager->tempFile;
  41326. pPager->eState = PAGER_OPEN;
  41327. pPager->errCode = SQLITE_OK;
  41328. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  41329. }
  41330. pPager->journalOff = 0;
  41331. pPager->journalHdr = 0;
  41332. pPager->setMaster = 0;
  41333. }
  41334. /*
  41335. ** This function is called whenever an IOERR or FULL error that requires
  41336. ** the pager to transition into the ERROR state may ahve occurred.
  41337. ** The first argument is a pointer to the pager structure, the second
  41338. ** the error-code about to be returned by a pager API function. The
  41339. ** value returned is a copy of the second argument to this function.
  41340. **
  41341. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  41342. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  41343. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  41344. ** all major API calls on the Pager will immediately return Pager.errCode.
  41345. **
  41346. ** The ERROR state indicates that the contents of the pager-cache
  41347. ** cannot be trusted. This state can be cleared by completely discarding
  41348. ** the contents of the pager-cache. If a transaction was active when
  41349. ** the persistent error occurred, then the rollback journal may need
  41350. ** to be replayed to restore the contents of the database file (as if
  41351. ** it were a hot-journal).
  41352. */
  41353. static int pager_error(Pager *pPager, int rc){
  41354. int rc2 = rc & 0xff;
  41355. assert( rc==SQLITE_OK || !MEMDB );
  41356. assert(
  41357. pPager->errCode==SQLITE_FULL ||
  41358. pPager->errCode==SQLITE_OK ||
  41359. (pPager->errCode & 0xff)==SQLITE_IOERR
  41360. );
  41361. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  41362. pPager->errCode = rc;
  41363. pPager->eState = PAGER_ERROR;
  41364. }
  41365. return rc;
  41366. }
  41367. static int pager_truncate(Pager *pPager, Pgno nPage);
  41368. /*
  41369. ** This routine ends a transaction. A transaction is usually ended by
  41370. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  41371. ** after rollback of a hot-journal, or if an error occurs while opening
  41372. ** the journal file or writing the very first journal-header of a
  41373. ** database transaction.
  41374. **
  41375. ** This routine is never called in PAGER_ERROR state. If it is called
  41376. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  41377. ** exclusive than a RESERVED lock, it is a no-op.
  41378. **
  41379. ** Otherwise, any active savepoints are released.
  41380. **
  41381. ** If the journal file is open, then it is "finalized". Once a journal
  41382. ** file has been finalized it is not possible to use it to roll back a
  41383. ** transaction. Nor will it be considered to be a hot-journal by this
  41384. ** or any other database connection. Exactly how a journal is finalized
  41385. ** depends on whether or not the pager is running in exclusive mode and
  41386. ** the current journal-mode (Pager.journalMode value), as follows:
  41387. **
  41388. ** journalMode==MEMORY
  41389. ** Journal file descriptor is simply closed. This destroys an
  41390. ** in-memory journal.
  41391. **
  41392. ** journalMode==TRUNCATE
  41393. ** Journal file is truncated to zero bytes in size.
  41394. **
  41395. ** journalMode==PERSIST
  41396. ** The first 28 bytes of the journal file are zeroed. This invalidates
  41397. ** the first journal header in the file, and hence the entire journal
  41398. ** file. An invalid journal file cannot be rolled back.
  41399. **
  41400. ** journalMode==DELETE
  41401. ** The journal file is closed and deleted using sqlite3OsDelete().
  41402. **
  41403. ** If the pager is running in exclusive mode, this method of finalizing
  41404. ** the journal file is never used. Instead, if the journalMode is
  41405. ** DELETE and the pager is in exclusive mode, the method described under
  41406. ** journalMode==PERSIST is used instead.
  41407. **
  41408. ** After the journal is finalized, the pager moves to PAGER_READER state.
  41409. ** If running in non-exclusive rollback mode, the lock on the file is
  41410. ** downgraded to a SHARED_LOCK.
  41411. **
  41412. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  41413. ** any of the IO operations to finalize the journal file or unlock the
  41414. ** database then the IO error code is returned to the user. If the
  41415. ** operation to finalize the journal file fails, then the code still
  41416. ** tries to unlock the database file if not in exclusive mode. If the
  41417. ** unlock operation fails as well, then the first error code related
  41418. ** to the first error encountered (the journal finalization one) is
  41419. ** returned.
  41420. */
  41421. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  41422. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  41423. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  41424. /* Do nothing if the pager does not have an open write transaction
  41425. ** or at least a RESERVED lock. This function may be called when there
  41426. ** is no write-transaction active but a RESERVED or greater lock is
  41427. ** held under two circumstances:
  41428. **
  41429. ** 1. After a successful hot-journal rollback, it is called with
  41430. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  41431. **
  41432. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  41433. ** lock switches back to locking_mode=normal and then executes a
  41434. ** read-transaction, this function is called with eState==PAGER_READER
  41435. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  41436. */
  41437. assert( assert_pager_state(pPager) );
  41438. assert( pPager->eState!=PAGER_ERROR );
  41439. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  41440. return SQLITE_OK;
  41441. }
  41442. releaseAllSavepoints(pPager);
  41443. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  41444. if( isOpen(pPager->jfd) ){
  41445. assert( !pagerUseWal(pPager) );
  41446. /* Finalize the journal file. */
  41447. if( sqlite3IsMemJournal(pPager->jfd) ){
  41448. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  41449. sqlite3OsClose(pPager->jfd);
  41450. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  41451. if( pPager->journalOff==0 ){
  41452. rc = SQLITE_OK;
  41453. }else{
  41454. rc = sqlite3OsTruncate(pPager->jfd, 0);
  41455. if( rc==SQLITE_OK && pPager->fullSync ){
  41456. /* Make sure the new file size is written into the inode right away.
  41457. ** Otherwise the journal might resurrect following a power loss and
  41458. ** cause the last transaction to roll back. See
  41459. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  41460. */
  41461. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  41462. }
  41463. }
  41464. pPager->journalOff = 0;
  41465. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  41466. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  41467. ){
  41468. rc = zeroJournalHdr(pPager, hasMaster);
  41469. pPager->journalOff = 0;
  41470. }else{
  41471. /* This branch may be executed with Pager.journalMode==MEMORY if
  41472. ** a hot-journal was just rolled back. In this case the journal
  41473. ** file should be closed and deleted. If this connection writes to
  41474. ** the database file, it will do so using an in-memory journal.
  41475. */
  41476. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  41477. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  41478. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  41479. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  41480. );
  41481. sqlite3OsClose(pPager->jfd);
  41482. if( bDelete ){
  41483. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  41484. }
  41485. }
  41486. }
  41487. #ifdef SQLITE_CHECK_PAGES
  41488. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  41489. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  41490. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  41491. if( p ){
  41492. p->pageHash = 0;
  41493. sqlite3PagerUnrefNotNull(p);
  41494. }
  41495. }
  41496. #endif
  41497. sqlite3BitvecDestroy(pPager->pInJournal);
  41498. pPager->pInJournal = 0;
  41499. pPager->nRec = 0;
  41500. sqlite3PcacheCleanAll(pPager->pPCache);
  41501. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  41502. if( pagerUseWal(pPager) ){
  41503. /* Drop the WAL write-lock, if any. Also, if the connection was in
  41504. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  41505. ** lock held on the database file.
  41506. */
  41507. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  41508. assert( rc2==SQLITE_OK );
  41509. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  41510. /* This branch is taken when committing a transaction in rollback-journal
  41511. ** mode if the database file on disk is larger than the database image.
  41512. ** At this point the journal has been finalized and the transaction
  41513. ** successfully committed, but the EXCLUSIVE lock is still held on the
  41514. ** file. So it is safe to truncate the database file to its minimum
  41515. ** required size. */
  41516. assert( pPager->eLock==EXCLUSIVE_LOCK );
  41517. rc = pager_truncate(pPager, pPager->dbSize);
  41518. }
  41519. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  41520. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  41521. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  41522. }
  41523. if( !pPager->exclusiveMode
  41524. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  41525. ){
  41526. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  41527. pPager->changeCountDone = 0;
  41528. }
  41529. pPager->eState = PAGER_READER;
  41530. pPager->setMaster = 0;
  41531. return (rc==SQLITE_OK?rc2:rc);
  41532. }
  41533. /*
  41534. ** Execute a rollback if a transaction is active and unlock the
  41535. ** database file.
  41536. **
  41537. ** If the pager has already entered the ERROR state, do not attempt
  41538. ** the rollback at this time. Instead, pager_unlock() is called. The
  41539. ** call to pager_unlock() will discard all in-memory pages, unlock
  41540. ** the database file and move the pager back to OPEN state. If this
  41541. ** means that there is a hot-journal left in the file-system, the next
  41542. ** connection to obtain a shared lock on the pager (which may be this one)
  41543. ** will roll it back.
  41544. **
  41545. ** If the pager has not already entered the ERROR state, but an IO or
  41546. ** malloc error occurs during a rollback, then this will itself cause
  41547. ** the pager to enter the ERROR state. Which will be cleared by the
  41548. ** call to pager_unlock(), as described above.
  41549. */
  41550. static void pagerUnlockAndRollback(Pager *pPager){
  41551. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  41552. assert( assert_pager_state(pPager) );
  41553. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  41554. sqlite3BeginBenignMalloc();
  41555. sqlite3PagerRollback(pPager);
  41556. sqlite3EndBenignMalloc();
  41557. }else if( !pPager->exclusiveMode ){
  41558. assert( pPager->eState==PAGER_READER );
  41559. pager_end_transaction(pPager, 0, 0);
  41560. }
  41561. }
  41562. pager_unlock(pPager);
  41563. }
  41564. /*
  41565. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  41566. ** of data. Compute and return a checksum based ont the contents of the
  41567. ** page of data and the current value of pPager->cksumInit.
  41568. **
  41569. ** This is not a real checksum. It is really just the sum of the
  41570. ** random initial value (pPager->cksumInit) and every 200th byte
  41571. ** of the page data, starting with byte offset (pPager->pageSize%200).
  41572. ** Each byte is interpreted as an 8-bit unsigned integer.
  41573. **
  41574. ** Changing the formula used to compute this checksum results in an
  41575. ** incompatible journal file format.
  41576. **
  41577. ** If journal corruption occurs due to a power failure, the most likely
  41578. ** scenario is that one end or the other of the record will be changed.
  41579. ** It is much less likely that the two ends of the journal record will be
  41580. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  41581. ** though fast and simple, catches the mostly likely kind of corruption.
  41582. */
  41583. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  41584. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  41585. int i = pPager->pageSize-200; /* Loop counter */
  41586. while( i>0 ){
  41587. cksum += aData[i];
  41588. i -= 200;
  41589. }
  41590. return cksum;
  41591. }
  41592. /*
  41593. ** Report the current page size and number of reserved bytes back
  41594. ** to the codec.
  41595. */
  41596. #ifdef SQLITE_HAS_CODEC
  41597. static void pagerReportSize(Pager *pPager){
  41598. if( pPager->xCodecSizeChng ){
  41599. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  41600. (int)pPager->nReserve);
  41601. }
  41602. }
  41603. #else
  41604. # define pagerReportSize(X) /* No-op if we do not support a codec */
  41605. #endif
  41606. /*
  41607. ** Read a single page from either the journal file (if isMainJrnl==1) or
  41608. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  41609. ** The page begins at offset *pOffset into the file. The *pOffset
  41610. ** value is increased to the start of the next page in the journal.
  41611. **
  41612. ** The main rollback journal uses checksums - the statement journal does
  41613. ** not.
  41614. **
  41615. ** If the page number of the page record read from the (sub-)journal file
  41616. ** is greater than the current value of Pager.dbSize, then playback is
  41617. ** skipped and SQLITE_OK is returned.
  41618. **
  41619. ** If pDone is not NULL, then it is a record of pages that have already
  41620. ** been played back. If the page at *pOffset has already been played back
  41621. ** (if the corresponding pDone bit is set) then skip the playback.
  41622. ** Make sure the pDone bit corresponding to the *pOffset page is set
  41623. ** prior to returning.
  41624. **
  41625. ** If the page record is successfully read from the (sub-)journal file
  41626. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  41627. ** while reading the record from the (sub-)journal file or while writing
  41628. ** to the database file, then the IO error code is returned. If data
  41629. ** is successfully read from the (sub-)journal file but appears to be
  41630. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  41631. ** two circumstances:
  41632. **
  41633. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  41634. ** * If the record is being rolled back from the main journal file
  41635. ** and the checksum field does not match the record content.
  41636. **
  41637. ** Neither of these two scenarios are possible during a savepoint rollback.
  41638. **
  41639. ** If this is a savepoint rollback, then memory may have to be dynamically
  41640. ** allocated by this function. If this is the case and an allocation fails,
  41641. ** SQLITE_NOMEM is returned.
  41642. */
  41643. static int pager_playback_one_page(
  41644. Pager *pPager, /* The pager being played back */
  41645. i64 *pOffset, /* Offset of record to playback */
  41646. Bitvec *pDone, /* Bitvec of pages already played back */
  41647. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  41648. int isSavepnt /* True for a savepoint rollback */
  41649. ){
  41650. int rc;
  41651. PgHdr *pPg; /* An existing page in the cache */
  41652. Pgno pgno; /* The page number of a page in journal */
  41653. u32 cksum; /* Checksum used for sanity checking */
  41654. char *aData; /* Temporary storage for the page */
  41655. sqlite3_file *jfd; /* The file descriptor for the journal file */
  41656. int isSynced; /* True if journal page is synced */
  41657. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  41658. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  41659. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  41660. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  41661. aData = pPager->pTmpSpace;
  41662. assert( aData ); /* Temp storage must have already been allocated */
  41663. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  41664. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  41665. ** or savepoint rollback done at the request of the caller) or this is
  41666. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  41667. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  41668. ** only reads from the main journal, not the sub-journal.
  41669. */
  41670. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  41671. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  41672. );
  41673. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  41674. /* Read the page number and page data from the journal or sub-journal
  41675. ** file. Return an error code to the caller if an IO error occurs.
  41676. */
  41677. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  41678. rc = read32bits(jfd, *pOffset, &pgno);
  41679. if( rc!=SQLITE_OK ) return rc;
  41680. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  41681. if( rc!=SQLITE_OK ) return rc;
  41682. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  41683. /* Sanity checking on the page. This is more important that I originally
  41684. ** thought. If a power failure occurs while the journal is being written,
  41685. ** it could cause invalid data to be written into the journal. We need to
  41686. ** detect this invalid data (with high probability) and ignore it.
  41687. */
  41688. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  41689. assert( !isSavepnt );
  41690. return SQLITE_DONE;
  41691. }
  41692. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  41693. return SQLITE_OK;
  41694. }
  41695. if( isMainJrnl ){
  41696. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  41697. if( rc ) return rc;
  41698. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  41699. return SQLITE_DONE;
  41700. }
  41701. }
  41702. /* If this page has already been played back before during the current
  41703. ** rollback, then don't bother to play it back again.
  41704. */
  41705. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  41706. return rc;
  41707. }
  41708. /* When playing back page 1, restore the nReserve setting
  41709. */
  41710. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  41711. pPager->nReserve = ((u8*)aData)[20];
  41712. pagerReportSize(pPager);
  41713. }
  41714. /* If the pager is in CACHEMOD state, then there must be a copy of this
  41715. ** page in the pager cache. In this case just update the pager cache,
  41716. ** not the database file. The page is left marked dirty in this case.
  41717. **
  41718. ** An exception to the above rule: If the database is in no-sync mode
  41719. ** and a page is moved during an incremental vacuum then the page may
  41720. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  41721. ** during a Movepage() call, then the page may not be in the cache
  41722. ** either. So the condition described in the above paragraph is not
  41723. ** assert()able.
  41724. **
  41725. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  41726. ** pager cache if it exists and the main file. The page is then marked
  41727. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  41728. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  41729. ** if the pager is in OPEN state.
  41730. **
  41731. ** Ticket #1171: The statement journal might contain page content that is
  41732. ** different from the page content at the start of the transaction.
  41733. ** This occurs when a page is changed prior to the start of a statement
  41734. ** then changed again within the statement. When rolling back such a
  41735. ** statement we must not write to the original database unless we know
  41736. ** for certain that original page contents are synced into the main rollback
  41737. ** journal. Otherwise, a power loss might leave modified data in the
  41738. ** database file without an entry in the rollback journal that can
  41739. ** restore the database to its original form. Two conditions must be
  41740. ** met before writing to the database files. (1) the database must be
  41741. ** locked. (2) we know that the original page content is fully synced
  41742. ** in the main journal either because the page is not in cache or else
  41743. ** the page is marked as needSync==0.
  41744. **
  41745. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  41746. ** is possible to fail a statement on a database that does not yet exist.
  41747. ** Do not attempt to write if database file has never been opened.
  41748. */
  41749. if( pagerUseWal(pPager) ){
  41750. pPg = 0;
  41751. }else{
  41752. pPg = sqlite3PagerLookup(pPager, pgno);
  41753. }
  41754. assert( pPg || !MEMDB );
  41755. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  41756. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  41757. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  41758. (isMainJrnl?"main-journal":"sub-journal")
  41759. ));
  41760. if( isMainJrnl ){
  41761. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  41762. }else{
  41763. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  41764. }
  41765. if( isOpen(pPager->fd)
  41766. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41767. && isSynced
  41768. ){
  41769. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  41770. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  41771. assert( !pagerUseWal(pPager) );
  41772. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  41773. if( pgno>pPager->dbFileSize ){
  41774. pPager->dbFileSize = pgno;
  41775. }
  41776. if( pPager->pBackup ){
  41777. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  41778. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  41779. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  41780. }
  41781. }else if( !isMainJrnl && pPg==0 ){
  41782. /* If this is a rollback of a savepoint and data was not written to
  41783. ** the database and the page is not in-memory, there is a potential
  41784. ** problem. When the page is next fetched by the b-tree layer, it
  41785. ** will be read from the database file, which may or may not be
  41786. ** current.
  41787. **
  41788. ** There are a couple of different ways this can happen. All are quite
  41789. ** obscure. When running in synchronous mode, this can only happen
  41790. ** if the page is on the free-list at the start of the transaction, then
  41791. ** populated, then moved using sqlite3PagerMovepage().
  41792. **
  41793. ** The solution is to add an in-memory page to the cache containing
  41794. ** the data just read from the sub-journal. Mark the page as dirty
  41795. ** and if the pager requires a journal-sync, then mark the page as
  41796. ** requiring a journal-sync before it is written.
  41797. */
  41798. assert( isSavepnt );
  41799. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  41800. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  41801. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  41802. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  41803. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  41804. if( rc!=SQLITE_OK ) return rc;
  41805. pPg->flags &= ~PGHDR_NEED_READ;
  41806. sqlite3PcacheMakeDirty(pPg);
  41807. }
  41808. if( pPg ){
  41809. /* No page should ever be explicitly rolled back that is in use, except
  41810. ** for page 1 which is held in use in order to keep the lock on the
  41811. ** database active. However such a page may be rolled back as a result
  41812. ** of an internal error resulting in an automatic call to
  41813. ** sqlite3PagerRollback().
  41814. */
  41815. void *pData;
  41816. pData = pPg->pData;
  41817. memcpy(pData, (u8*)aData, pPager->pageSize);
  41818. pPager->xReiniter(pPg);
  41819. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  41820. /* If the contents of this page were just restored from the main
  41821. ** journal file, then its content must be as they were when the
  41822. ** transaction was first opened. In this case we can mark the page
  41823. ** as clean, since there will be no need to write it out to the
  41824. ** database.
  41825. **
  41826. ** There is one exception to this rule. If the page is being rolled
  41827. ** back as part of a savepoint (or statement) rollback from an
  41828. ** unsynced portion of the main journal file, then it is not safe
  41829. ** to mark the page as clean. This is because marking the page as
  41830. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  41831. ** already in the journal file (recorded in Pager.pInJournal) and
  41832. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  41833. ** again within this transaction, it will be marked as dirty but
  41834. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  41835. ** be written out into the database file before its journal file
  41836. ** segment is synced. If a crash occurs during or following this,
  41837. ** database corruption may ensue.
  41838. */
  41839. assert( !pagerUseWal(pPager) );
  41840. sqlite3PcacheMakeClean(pPg);
  41841. }
  41842. pager_set_pagehash(pPg);
  41843. /* If this was page 1, then restore the value of Pager.dbFileVers.
  41844. ** Do this before any decoding. */
  41845. if( pgno==1 ){
  41846. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  41847. }
  41848. /* Decode the page just read from disk */
  41849. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  41850. sqlite3PcacheRelease(pPg);
  41851. }
  41852. return rc;
  41853. }
  41854. /*
  41855. ** Parameter zMaster is the name of a master journal file. A single journal
  41856. ** file that referred to the master journal file has just been rolled back.
  41857. ** This routine checks if it is possible to delete the master journal file,
  41858. ** and does so if it is.
  41859. **
  41860. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  41861. ** available for use within this function.
  41862. **
  41863. ** When a master journal file is created, it is populated with the names
  41864. ** of all of its child journals, one after another, formatted as utf-8
  41865. ** encoded text. The end of each child journal file is marked with a
  41866. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  41867. ** file for a transaction involving two databases might be:
  41868. **
  41869. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  41870. **
  41871. ** A master journal file may only be deleted once all of its child
  41872. ** journals have been rolled back.
  41873. **
  41874. ** This function reads the contents of the master-journal file into
  41875. ** memory and loops through each of the child journal names. For
  41876. ** each child journal, it checks if:
  41877. **
  41878. ** * if the child journal exists, and if so
  41879. ** * if the child journal contains a reference to master journal
  41880. ** file zMaster
  41881. **
  41882. ** If a child journal can be found that matches both of the criteria
  41883. ** above, this function returns without doing anything. Otherwise, if
  41884. ** no such child journal can be found, file zMaster is deleted from
  41885. ** the file-system using sqlite3OsDelete().
  41886. **
  41887. ** If an IO error within this function, an error code is returned. This
  41888. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  41889. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  41890. ** occur, SQLITE_OK is returned.
  41891. **
  41892. ** TODO: This function allocates a single block of memory to load
  41893. ** the entire contents of the master journal file. This could be
  41894. ** a couple of kilobytes or so - potentially larger than the page
  41895. ** size.
  41896. */
  41897. static int pager_delmaster(Pager *pPager, const char *zMaster){
  41898. sqlite3_vfs *pVfs = pPager->pVfs;
  41899. int rc; /* Return code */
  41900. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  41901. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  41902. char *zMasterJournal = 0; /* Contents of master journal file */
  41903. i64 nMasterJournal; /* Size of master journal file */
  41904. char *zJournal; /* Pointer to one journal within MJ file */
  41905. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  41906. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  41907. /* Allocate space for both the pJournal and pMaster file descriptors.
  41908. ** If successful, open the master journal file for reading.
  41909. */
  41910. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  41911. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  41912. if( !pMaster ){
  41913. rc = SQLITE_NOMEM;
  41914. }else{
  41915. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  41916. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  41917. }
  41918. if( rc!=SQLITE_OK ) goto delmaster_out;
  41919. /* Load the entire master journal file into space obtained from
  41920. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  41921. ** sufficient space (in zMasterPtr) to hold the names of master
  41922. ** journal files extracted from regular rollback-journals.
  41923. */
  41924. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  41925. if( rc!=SQLITE_OK ) goto delmaster_out;
  41926. nMasterPtr = pVfs->mxPathname+1;
  41927. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  41928. if( !zMasterJournal ){
  41929. rc = SQLITE_NOMEM;
  41930. goto delmaster_out;
  41931. }
  41932. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  41933. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  41934. if( rc!=SQLITE_OK ) goto delmaster_out;
  41935. zMasterJournal[nMasterJournal] = 0;
  41936. zJournal = zMasterJournal;
  41937. while( (zJournal-zMasterJournal)<nMasterJournal ){
  41938. int exists;
  41939. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  41940. if( rc!=SQLITE_OK ){
  41941. goto delmaster_out;
  41942. }
  41943. if( exists ){
  41944. /* One of the journals pointed to by the master journal exists.
  41945. ** Open it and check if it points at the master journal. If
  41946. ** so, return without deleting the master journal file.
  41947. */
  41948. int c;
  41949. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  41950. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  41951. if( rc!=SQLITE_OK ){
  41952. goto delmaster_out;
  41953. }
  41954. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  41955. sqlite3OsClose(pJournal);
  41956. if( rc!=SQLITE_OK ){
  41957. goto delmaster_out;
  41958. }
  41959. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  41960. if( c ){
  41961. /* We have a match. Do not delete the master journal file. */
  41962. goto delmaster_out;
  41963. }
  41964. }
  41965. zJournal += (sqlite3Strlen30(zJournal)+1);
  41966. }
  41967. sqlite3OsClose(pMaster);
  41968. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  41969. delmaster_out:
  41970. sqlite3_free(zMasterJournal);
  41971. if( pMaster ){
  41972. sqlite3OsClose(pMaster);
  41973. assert( !isOpen(pJournal) );
  41974. sqlite3_free(pMaster);
  41975. }
  41976. return rc;
  41977. }
  41978. /*
  41979. ** This function is used to change the actual size of the database
  41980. ** file in the file-system. This only happens when committing a transaction,
  41981. ** or rolling back a transaction (including rolling back a hot-journal).
  41982. **
  41983. ** If the main database file is not open, or the pager is not in either
  41984. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  41985. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  41986. ** If the file on disk is currently larger than nPage pages, then use the VFS
  41987. ** xTruncate() method to truncate it.
  41988. **
  41989. ** Or, it might be the case that the file on disk is smaller than
  41990. ** nPage pages. Some operating system implementations can get confused if
  41991. ** you try to truncate a file to some size that is larger than it
  41992. ** currently is, so detect this case and write a single zero byte to
  41993. ** the end of the new file instead.
  41994. **
  41995. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  41996. ** the database file, return the error code to the caller.
  41997. */
  41998. static int pager_truncate(Pager *pPager, Pgno nPage){
  41999. int rc = SQLITE_OK;
  42000. assert( pPager->eState!=PAGER_ERROR );
  42001. assert( pPager->eState!=PAGER_READER );
  42002. if( isOpen(pPager->fd)
  42003. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  42004. ){
  42005. i64 currentSize, newSize;
  42006. int szPage = pPager->pageSize;
  42007. assert( pPager->eLock==EXCLUSIVE_LOCK );
  42008. /* TODO: Is it safe to use Pager.dbFileSize here? */
  42009. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  42010. newSize = szPage*(i64)nPage;
  42011. if( rc==SQLITE_OK && currentSize!=newSize ){
  42012. if( currentSize>newSize ){
  42013. rc = sqlite3OsTruncate(pPager->fd, newSize);
  42014. }else if( (currentSize+szPage)<=newSize ){
  42015. char *pTmp = pPager->pTmpSpace;
  42016. memset(pTmp, 0, szPage);
  42017. testcase( (newSize-szPage) == currentSize );
  42018. testcase( (newSize-szPage) > currentSize );
  42019. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  42020. }
  42021. if( rc==SQLITE_OK ){
  42022. pPager->dbFileSize = nPage;
  42023. }
  42024. }
  42025. }
  42026. return rc;
  42027. }
  42028. /*
  42029. ** Return a sanitized version of the sector-size of OS file pFile. The
  42030. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  42031. */
  42032. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  42033. int iRet = sqlite3OsSectorSize(pFile);
  42034. if( iRet<32 ){
  42035. iRet = 512;
  42036. }else if( iRet>MAX_SECTOR_SIZE ){
  42037. assert( MAX_SECTOR_SIZE>=512 );
  42038. iRet = MAX_SECTOR_SIZE;
  42039. }
  42040. return iRet;
  42041. }
  42042. /*
  42043. ** Set the value of the Pager.sectorSize variable for the given
  42044. ** pager based on the value returned by the xSectorSize method
  42045. ** of the open database file. The sector size will be used
  42046. ** to determine the size and alignment of journal header and
  42047. ** master journal pointers within created journal files.
  42048. **
  42049. ** For temporary files the effective sector size is always 512 bytes.
  42050. **
  42051. ** Otherwise, for non-temporary files, the effective sector size is
  42052. ** the value returned by the xSectorSize() method rounded up to 32 if
  42053. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  42054. ** is greater than MAX_SECTOR_SIZE.
  42055. **
  42056. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  42057. ** the effective sector size to its minimum value (512). The purpose of
  42058. ** pPager->sectorSize is to define the "blast radius" of bytes that
  42059. ** might change if a crash occurs while writing to a single byte in
  42060. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  42061. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  42062. ** size. For backwards compatibility of the rollback journal file format,
  42063. ** we cannot reduce the effective sector size below 512.
  42064. */
  42065. static void setSectorSize(Pager *pPager){
  42066. assert( isOpen(pPager->fd) || pPager->tempFile );
  42067. if( pPager->tempFile
  42068. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  42069. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  42070. ){
  42071. /* Sector size doesn't matter for temporary files. Also, the file
  42072. ** may not have been opened yet, in which case the OsSectorSize()
  42073. ** call will segfault. */
  42074. pPager->sectorSize = 512;
  42075. }else{
  42076. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  42077. }
  42078. }
  42079. /*
  42080. ** Playback the journal and thus restore the database file to
  42081. ** the state it was in before we started making changes.
  42082. **
  42083. ** The journal file format is as follows:
  42084. **
  42085. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  42086. ** (2) 4 byte big-endian integer which is the number of valid page records
  42087. ** in the journal. If this value is 0xffffffff, then compute the
  42088. ** number of page records from the journal size.
  42089. ** (3) 4 byte big-endian integer which is the initial value for the
  42090. ** sanity checksum.
  42091. ** (4) 4 byte integer which is the number of pages to truncate the
  42092. ** database to during a rollback.
  42093. ** (5) 4 byte big-endian integer which is the sector size. The header
  42094. ** is this many bytes in size.
  42095. ** (6) 4 byte big-endian integer which is the page size.
  42096. ** (7) zero padding out to the next sector size.
  42097. ** (8) Zero or more pages instances, each as follows:
  42098. ** + 4 byte page number.
  42099. ** + pPager->pageSize bytes of data.
  42100. ** + 4 byte checksum
  42101. **
  42102. ** When we speak of the journal header, we mean the first 7 items above.
  42103. ** Each entry in the journal is an instance of the 8th item.
  42104. **
  42105. ** Call the value from the second bullet "nRec". nRec is the number of
  42106. ** valid page entries in the journal. In most cases, you can compute the
  42107. ** value of nRec from the size of the journal file. But if a power
  42108. ** failure occurred while the journal was being written, it could be the
  42109. ** case that the size of the journal file had already been increased but
  42110. ** the extra entries had not yet made it safely to disk. In such a case,
  42111. ** the value of nRec computed from the file size would be too large. For
  42112. ** that reason, we always use the nRec value in the header.
  42113. **
  42114. ** If the nRec value is 0xffffffff it means that nRec should be computed
  42115. ** from the file size. This value is used when the user selects the
  42116. ** no-sync option for the journal. A power failure could lead to corruption
  42117. ** in this case. But for things like temporary table (which will be
  42118. ** deleted when the power is restored) we don't care.
  42119. **
  42120. ** If the file opened as the journal file is not a well-formed
  42121. ** journal file then all pages up to the first corrupted page are rolled
  42122. ** back (or no pages if the journal header is corrupted). The journal file
  42123. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  42124. ** been encountered.
  42125. **
  42126. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  42127. ** and an error code is returned.
  42128. **
  42129. ** The isHot parameter indicates that we are trying to rollback a journal
  42130. ** that might be a hot journal. Or, it could be that the journal is
  42131. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  42132. ** If the journal really is hot, reset the pager cache prior rolling
  42133. ** back any content. If the journal is merely persistent, no reset is
  42134. ** needed.
  42135. */
  42136. static int pager_playback(Pager *pPager, int isHot){
  42137. sqlite3_vfs *pVfs = pPager->pVfs;
  42138. i64 szJ; /* Size of the journal file in bytes */
  42139. u32 nRec; /* Number of Records in the journal */
  42140. u32 u; /* Unsigned loop counter */
  42141. Pgno mxPg = 0; /* Size of the original file in pages */
  42142. int rc; /* Result code of a subroutine */
  42143. int res = 1; /* Value returned by sqlite3OsAccess() */
  42144. char *zMaster = 0; /* Name of master journal file if any */
  42145. int needPagerReset; /* True to reset page prior to first page rollback */
  42146. int nPlayback = 0; /* Total number of pages restored from journal */
  42147. /* Figure out how many records are in the journal. Abort early if
  42148. ** the journal is empty.
  42149. */
  42150. assert( isOpen(pPager->jfd) );
  42151. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  42152. if( rc!=SQLITE_OK ){
  42153. goto end_playback;
  42154. }
  42155. /* Read the master journal name from the journal, if it is present.
  42156. ** If a master journal file name is specified, but the file is not
  42157. ** present on disk, then the journal is not hot and does not need to be
  42158. ** played back.
  42159. **
  42160. ** TODO: Technically the following is an error because it assumes that
  42161. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  42162. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  42163. ** mxPathname is 512, which is the same as the minimum allowable value
  42164. ** for pageSize.
  42165. */
  42166. zMaster = pPager->pTmpSpace;
  42167. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  42168. if( rc==SQLITE_OK && zMaster[0] ){
  42169. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  42170. }
  42171. zMaster = 0;
  42172. if( rc!=SQLITE_OK || !res ){
  42173. goto end_playback;
  42174. }
  42175. pPager->journalOff = 0;
  42176. needPagerReset = isHot;
  42177. /* This loop terminates either when a readJournalHdr() or
  42178. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  42179. ** occurs.
  42180. */
  42181. while( 1 ){
  42182. /* Read the next journal header from the journal file. If there are
  42183. ** not enough bytes left in the journal file for a complete header, or
  42184. ** it is corrupted, then a process must have failed while writing it.
  42185. ** This indicates nothing more needs to be rolled back.
  42186. */
  42187. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  42188. if( rc!=SQLITE_OK ){
  42189. if( rc==SQLITE_DONE ){
  42190. rc = SQLITE_OK;
  42191. }
  42192. goto end_playback;
  42193. }
  42194. /* If nRec is 0xffffffff, then this journal was created by a process
  42195. ** working in no-sync mode. This means that the rest of the journal
  42196. ** file consists of pages, there are no more journal headers. Compute
  42197. ** the value of nRec based on this assumption.
  42198. */
  42199. if( nRec==0xffffffff ){
  42200. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  42201. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  42202. }
  42203. /* If nRec is 0 and this rollback is of a transaction created by this
  42204. ** process and if this is the final header in the journal, then it means
  42205. ** that this part of the journal was being filled but has not yet been
  42206. ** synced to disk. Compute the number of pages based on the remaining
  42207. ** size of the file.
  42208. **
  42209. ** The third term of the test was added to fix ticket #2565.
  42210. ** When rolling back a hot journal, nRec==0 always means that the next
  42211. ** chunk of the journal contains zero pages to be rolled back. But
  42212. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  42213. ** the journal, it means that the journal might contain additional
  42214. ** pages that need to be rolled back and that the number of pages
  42215. ** should be computed based on the journal file size.
  42216. */
  42217. if( nRec==0 && !isHot &&
  42218. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  42219. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  42220. }
  42221. /* If this is the first header read from the journal, truncate the
  42222. ** database file back to its original size.
  42223. */
  42224. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  42225. rc = pager_truncate(pPager, mxPg);
  42226. if( rc!=SQLITE_OK ){
  42227. goto end_playback;
  42228. }
  42229. pPager->dbSize = mxPg;
  42230. }
  42231. /* Copy original pages out of the journal and back into the
  42232. ** database file and/or page cache.
  42233. */
  42234. for(u=0; u<nRec; u++){
  42235. if( needPagerReset ){
  42236. pager_reset(pPager);
  42237. needPagerReset = 0;
  42238. }
  42239. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  42240. if( rc==SQLITE_OK ){
  42241. nPlayback++;
  42242. }else{
  42243. if( rc==SQLITE_DONE ){
  42244. pPager->journalOff = szJ;
  42245. break;
  42246. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  42247. /* If the journal has been truncated, simply stop reading and
  42248. ** processing the journal. This might happen if the journal was
  42249. ** not completely written and synced prior to a crash. In that
  42250. ** case, the database should have never been written in the
  42251. ** first place so it is OK to simply abandon the rollback. */
  42252. rc = SQLITE_OK;
  42253. goto end_playback;
  42254. }else{
  42255. /* If we are unable to rollback, quit and return the error
  42256. ** code. This will cause the pager to enter the error state
  42257. ** so that no further harm will be done. Perhaps the next
  42258. ** process to come along will be able to rollback the database.
  42259. */
  42260. goto end_playback;
  42261. }
  42262. }
  42263. }
  42264. }
  42265. /*NOTREACHED*/
  42266. assert( 0 );
  42267. end_playback:
  42268. /* Following a rollback, the database file should be back in its original
  42269. ** state prior to the start of the transaction, so invoke the
  42270. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  42271. ** assertion that the transaction counter was modified.
  42272. */
  42273. #ifdef SQLITE_DEBUG
  42274. if( pPager->fd->pMethods ){
  42275. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  42276. }
  42277. #endif
  42278. /* If this playback is happening automatically as a result of an IO or
  42279. ** malloc error that occurred after the change-counter was updated but
  42280. ** before the transaction was committed, then the change-counter
  42281. ** modification may just have been reverted. If this happens in exclusive
  42282. ** mode, then subsequent transactions performed by the connection will not
  42283. ** update the change-counter at all. This may lead to cache inconsistency
  42284. ** problems for other processes at some point in the future. So, just
  42285. ** in case this has happened, clear the changeCountDone flag now.
  42286. */
  42287. pPager->changeCountDone = pPager->tempFile;
  42288. if( rc==SQLITE_OK ){
  42289. zMaster = pPager->pTmpSpace;
  42290. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  42291. testcase( rc!=SQLITE_OK );
  42292. }
  42293. if( rc==SQLITE_OK
  42294. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  42295. ){
  42296. rc = sqlite3PagerSync(pPager, 0);
  42297. }
  42298. if( rc==SQLITE_OK ){
  42299. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  42300. testcase( rc!=SQLITE_OK );
  42301. }
  42302. if( rc==SQLITE_OK && zMaster[0] && res ){
  42303. /* If there was a master journal and this routine will return success,
  42304. ** see if it is possible to delete the master journal.
  42305. */
  42306. rc = pager_delmaster(pPager, zMaster);
  42307. testcase( rc!=SQLITE_OK );
  42308. }
  42309. if( isHot && nPlayback ){
  42310. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  42311. nPlayback, pPager->zJournal);
  42312. }
  42313. /* The Pager.sectorSize variable may have been updated while rolling
  42314. ** back a journal created by a process with a different sector size
  42315. ** value. Reset it to the correct value for this process.
  42316. */
  42317. setSectorSize(pPager);
  42318. return rc;
  42319. }
  42320. /*
  42321. ** Read the content for page pPg out of the database file and into
  42322. ** pPg->pData. A shared lock or greater must be held on the database
  42323. ** file before this function is called.
  42324. **
  42325. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  42326. ** the value read from the database file.
  42327. **
  42328. ** If an IO error occurs, then the IO error is returned to the caller.
  42329. ** Otherwise, SQLITE_OK is returned.
  42330. */
  42331. static int readDbPage(PgHdr *pPg, u32 iFrame){
  42332. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  42333. Pgno pgno = pPg->pgno; /* Page number to read */
  42334. int rc = SQLITE_OK; /* Return code */
  42335. int pgsz = pPager->pageSize; /* Number of bytes to read */
  42336. assert( pPager->eState>=PAGER_READER && !MEMDB );
  42337. assert( isOpen(pPager->fd) );
  42338. #ifndef SQLITE_OMIT_WAL
  42339. if( iFrame ){
  42340. /* Try to pull the page from the write-ahead log. */
  42341. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  42342. }else
  42343. #endif
  42344. {
  42345. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  42346. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  42347. if( rc==SQLITE_IOERR_SHORT_READ ){
  42348. rc = SQLITE_OK;
  42349. }
  42350. }
  42351. if( pgno==1 ){
  42352. if( rc ){
  42353. /* If the read is unsuccessful, set the dbFileVers[] to something
  42354. ** that will never be a valid file version. dbFileVers[] is a copy
  42355. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  42356. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  42357. ** should be page numbers which are never 0xffffffff. So filling
  42358. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  42359. **
  42360. ** For an encrypted database, the situation is more complex: bytes
  42361. ** 24..39 of the database are white noise. But the probability of
  42362. ** white noise equaling 16 bytes of 0xff is vanishingly small so
  42363. ** we should still be ok.
  42364. */
  42365. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  42366. }else{
  42367. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  42368. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  42369. }
  42370. }
  42371. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  42372. PAGER_INCR(sqlite3_pager_readdb_count);
  42373. PAGER_INCR(pPager->nRead);
  42374. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  42375. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  42376. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  42377. return rc;
  42378. }
  42379. /*
  42380. ** Update the value of the change-counter at offsets 24 and 92 in
  42381. ** the header and the sqlite version number at offset 96.
  42382. **
  42383. ** This is an unconditional update. See also the pager_incr_changecounter()
  42384. ** routine which only updates the change-counter if the update is actually
  42385. ** needed, as determined by the pPager->changeCountDone state variable.
  42386. */
  42387. static void pager_write_changecounter(PgHdr *pPg){
  42388. u32 change_counter;
  42389. /* Increment the value just read and write it back to byte 24. */
  42390. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  42391. put32bits(((char*)pPg->pData)+24, change_counter);
  42392. /* Also store the SQLite version number in bytes 96..99 and in
  42393. ** bytes 92..95 store the change counter for which the version number
  42394. ** is valid. */
  42395. put32bits(((char*)pPg->pData)+92, change_counter);
  42396. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  42397. }
  42398. #ifndef SQLITE_OMIT_WAL
  42399. /*
  42400. ** This function is invoked once for each page that has already been
  42401. ** written into the log file when a WAL transaction is rolled back.
  42402. ** Parameter iPg is the page number of said page. The pCtx argument
  42403. ** is actually a pointer to the Pager structure.
  42404. **
  42405. ** If page iPg is present in the cache, and has no outstanding references,
  42406. ** it is discarded. Otherwise, if there are one or more outstanding
  42407. ** references, the page content is reloaded from the database. If the
  42408. ** attempt to reload content from the database is required and fails,
  42409. ** return an SQLite error code. Otherwise, SQLITE_OK.
  42410. */
  42411. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  42412. int rc = SQLITE_OK;
  42413. Pager *pPager = (Pager *)pCtx;
  42414. PgHdr *pPg;
  42415. assert( pagerUseWal(pPager) );
  42416. pPg = sqlite3PagerLookup(pPager, iPg);
  42417. if( pPg ){
  42418. if( sqlite3PcachePageRefcount(pPg)==1 ){
  42419. sqlite3PcacheDrop(pPg);
  42420. }else{
  42421. u32 iFrame = 0;
  42422. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  42423. if( rc==SQLITE_OK ){
  42424. rc = readDbPage(pPg, iFrame);
  42425. }
  42426. if( rc==SQLITE_OK ){
  42427. pPager->xReiniter(pPg);
  42428. }
  42429. sqlite3PagerUnrefNotNull(pPg);
  42430. }
  42431. }
  42432. /* Normally, if a transaction is rolled back, any backup processes are
  42433. ** updated as data is copied out of the rollback journal and into the
  42434. ** database. This is not generally possible with a WAL database, as
  42435. ** rollback involves simply truncating the log file. Therefore, if one
  42436. ** or more frames have already been written to the log (and therefore
  42437. ** also copied into the backup databases) as part of this transaction,
  42438. ** the backups must be restarted.
  42439. */
  42440. sqlite3BackupRestart(pPager->pBackup);
  42441. return rc;
  42442. }
  42443. /*
  42444. ** This function is called to rollback a transaction on a WAL database.
  42445. */
  42446. static int pagerRollbackWal(Pager *pPager){
  42447. int rc; /* Return Code */
  42448. PgHdr *pList; /* List of dirty pages to revert */
  42449. /* For all pages in the cache that are currently dirty or have already
  42450. ** been written (but not committed) to the log file, do one of the
  42451. ** following:
  42452. **
  42453. ** + Discard the cached page (if refcount==0), or
  42454. ** + Reload page content from the database (if refcount>0).
  42455. */
  42456. pPager->dbSize = pPager->dbOrigSize;
  42457. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  42458. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  42459. while( pList && rc==SQLITE_OK ){
  42460. PgHdr *pNext = pList->pDirty;
  42461. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  42462. pList = pNext;
  42463. }
  42464. return rc;
  42465. }
  42466. /*
  42467. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  42468. ** the contents of the list of pages headed by pList (connected by pDirty),
  42469. ** this function notifies any active backup processes that the pages have
  42470. ** changed.
  42471. **
  42472. ** The list of pages passed into this routine is always sorted by page number.
  42473. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  42474. */
  42475. static int pagerWalFrames(
  42476. Pager *pPager, /* Pager object */
  42477. PgHdr *pList, /* List of frames to log */
  42478. Pgno nTruncate, /* Database size after this commit */
  42479. int isCommit /* True if this is a commit */
  42480. ){
  42481. int rc; /* Return code */
  42482. int nList; /* Number of pages in pList */
  42483. PgHdr *p; /* For looping over pages */
  42484. assert( pPager->pWal );
  42485. assert( pList );
  42486. #ifdef SQLITE_DEBUG
  42487. /* Verify that the page list is in accending order */
  42488. for(p=pList; p && p->pDirty; p=p->pDirty){
  42489. assert( p->pgno < p->pDirty->pgno );
  42490. }
  42491. #endif
  42492. assert( pList->pDirty==0 || isCommit );
  42493. if( isCommit ){
  42494. /* If a WAL transaction is being committed, there is no point in writing
  42495. ** any pages with page numbers greater than nTruncate into the WAL file.
  42496. ** They will never be read by any client. So remove them from the pDirty
  42497. ** list here. */
  42498. PgHdr **ppNext = &pList;
  42499. nList = 0;
  42500. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  42501. if( p->pgno<=nTruncate ){
  42502. ppNext = &p->pDirty;
  42503. nList++;
  42504. }
  42505. }
  42506. assert( pList );
  42507. }else{
  42508. nList = 1;
  42509. }
  42510. pPager->aStat[PAGER_STAT_WRITE] += nList;
  42511. if( pList->pgno==1 ) pager_write_changecounter(pList);
  42512. rc = sqlite3WalFrames(pPager->pWal,
  42513. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  42514. );
  42515. if( rc==SQLITE_OK && pPager->pBackup ){
  42516. for(p=pList; p; p=p->pDirty){
  42517. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  42518. }
  42519. }
  42520. #ifdef SQLITE_CHECK_PAGES
  42521. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  42522. for(p=pList; p; p=p->pDirty){
  42523. pager_set_pagehash(p);
  42524. }
  42525. #endif
  42526. return rc;
  42527. }
  42528. /*
  42529. ** Begin a read transaction on the WAL.
  42530. **
  42531. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  42532. ** makes a snapshot of the database at the current point in time and preserves
  42533. ** that snapshot for use by the reader in spite of concurrently changes by
  42534. ** other writers or checkpointers.
  42535. */
  42536. static int pagerBeginReadTransaction(Pager *pPager){
  42537. int rc; /* Return code */
  42538. int changed = 0; /* True if cache must be reset */
  42539. assert( pagerUseWal(pPager) );
  42540. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  42541. /* sqlite3WalEndReadTransaction() was not called for the previous
  42542. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  42543. ** are in locking_mode=NORMAL and EndRead() was previously called,
  42544. ** the duplicate call is harmless.
  42545. */
  42546. sqlite3WalEndReadTransaction(pPager->pWal);
  42547. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  42548. if( rc!=SQLITE_OK || changed ){
  42549. pager_reset(pPager);
  42550. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  42551. }
  42552. return rc;
  42553. }
  42554. #endif
  42555. /*
  42556. ** This function is called as part of the transition from PAGER_OPEN
  42557. ** to PAGER_READER state to determine the size of the database file
  42558. ** in pages (assuming the page size currently stored in Pager.pageSize).
  42559. **
  42560. ** If no error occurs, SQLITE_OK is returned and the size of the database
  42561. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  42562. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  42563. */
  42564. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  42565. Pgno nPage; /* Value to return via *pnPage */
  42566. /* Query the WAL sub-system for the database size. The WalDbsize()
  42567. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  42568. ** if the database size is not available. The database size is not
  42569. ** available from the WAL sub-system if the log file is empty or
  42570. ** contains no valid committed transactions.
  42571. */
  42572. assert( pPager->eState==PAGER_OPEN );
  42573. assert( pPager->eLock>=SHARED_LOCK );
  42574. nPage = sqlite3WalDbsize(pPager->pWal);
  42575. /* If the number of pages in the database is not available from the
  42576. ** WAL sub-system, determine the page counte based on the size of
  42577. ** the database file. If the size of the database file is not an
  42578. ** integer multiple of the page-size, round up the result.
  42579. */
  42580. if( nPage==0 ){
  42581. i64 n = 0; /* Size of db file in bytes */
  42582. assert( isOpen(pPager->fd) || pPager->tempFile );
  42583. if( isOpen(pPager->fd) ){
  42584. int rc = sqlite3OsFileSize(pPager->fd, &n);
  42585. if( rc!=SQLITE_OK ){
  42586. return rc;
  42587. }
  42588. }
  42589. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  42590. }
  42591. /* If the current number of pages in the file is greater than the
  42592. ** configured maximum pager number, increase the allowed limit so
  42593. ** that the file can be read.
  42594. */
  42595. if( nPage>pPager->mxPgno ){
  42596. pPager->mxPgno = (Pgno)nPage;
  42597. }
  42598. *pnPage = nPage;
  42599. return SQLITE_OK;
  42600. }
  42601. #ifndef SQLITE_OMIT_WAL
  42602. /*
  42603. ** Check if the *-wal file that corresponds to the database opened by pPager
  42604. ** exists if the database is not empy, or verify that the *-wal file does
  42605. ** not exist (by deleting it) if the database file is empty.
  42606. **
  42607. ** If the database is not empty and the *-wal file exists, open the pager
  42608. ** in WAL mode. If the database is empty or if no *-wal file exists and
  42609. ** if no error occurs, make sure Pager.journalMode is not set to
  42610. ** PAGER_JOURNALMODE_WAL.
  42611. **
  42612. ** Return SQLITE_OK or an error code.
  42613. **
  42614. ** The caller must hold a SHARED lock on the database file to call this
  42615. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  42616. ** a WAL on a none-empty database, this ensures there is no race condition
  42617. ** between the xAccess() below and an xDelete() being executed by some
  42618. ** other connection.
  42619. */
  42620. static int pagerOpenWalIfPresent(Pager *pPager){
  42621. int rc = SQLITE_OK;
  42622. assert( pPager->eState==PAGER_OPEN );
  42623. assert( pPager->eLock>=SHARED_LOCK );
  42624. if( !pPager->tempFile ){
  42625. int isWal; /* True if WAL file exists */
  42626. Pgno nPage; /* Size of the database file */
  42627. rc = pagerPagecount(pPager, &nPage);
  42628. if( rc ) return rc;
  42629. if( nPage==0 ){
  42630. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  42631. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  42632. isWal = 0;
  42633. }else{
  42634. rc = sqlite3OsAccess(
  42635. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  42636. );
  42637. }
  42638. if( rc==SQLITE_OK ){
  42639. if( isWal ){
  42640. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  42641. rc = sqlite3PagerOpenWal(pPager, 0);
  42642. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  42643. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  42644. }
  42645. }
  42646. }
  42647. return rc;
  42648. }
  42649. #endif
  42650. /*
  42651. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  42652. ** the entire master journal file. The case pSavepoint==NULL occurs when
  42653. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  42654. ** savepoint.
  42655. **
  42656. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  42657. ** being rolled back), then the rollback consists of up to three stages,
  42658. ** performed in the order specified:
  42659. **
  42660. ** * Pages are played back from the main journal starting at byte
  42661. ** offset PagerSavepoint.iOffset and continuing to
  42662. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  42663. ** file if PagerSavepoint.iHdrOffset is zero.
  42664. **
  42665. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  42666. ** back starting from the journal header immediately following
  42667. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  42668. **
  42669. ** * Pages are then played back from the sub-journal file, starting
  42670. ** with the PagerSavepoint.iSubRec and continuing to the end of
  42671. ** the journal file.
  42672. **
  42673. ** Throughout the rollback process, each time a page is rolled back, the
  42674. ** corresponding bit is set in a bitvec structure (variable pDone in the
  42675. ** implementation below). This is used to ensure that a page is only
  42676. ** rolled back the first time it is encountered in either journal.
  42677. **
  42678. ** If pSavepoint is NULL, then pages are only played back from the main
  42679. ** journal file. There is no need for a bitvec in this case.
  42680. **
  42681. ** In either case, before playback commences the Pager.dbSize variable
  42682. ** is reset to the value that it held at the start of the savepoint
  42683. ** (or transaction). No page with a page-number greater than this value
  42684. ** is played back. If one is encountered it is simply skipped.
  42685. */
  42686. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  42687. i64 szJ; /* Effective size of the main journal */
  42688. i64 iHdrOff; /* End of first segment of main-journal records */
  42689. int rc = SQLITE_OK; /* Return code */
  42690. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  42691. assert( pPager->eState!=PAGER_ERROR );
  42692. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  42693. /* Allocate a bitvec to use to store the set of pages rolled back */
  42694. if( pSavepoint ){
  42695. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  42696. if( !pDone ){
  42697. return SQLITE_NOMEM;
  42698. }
  42699. }
  42700. /* Set the database size back to the value it was before the savepoint
  42701. ** being reverted was opened.
  42702. */
  42703. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  42704. pPager->changeCountDone = pPager->tempFile;
  42705. if( !pSavepoint && pagerUseWal(pPager) ){
  42706. return pagerRollbackWal(pPager);
  42707. }
  42708. /* Use pPager->journalOff as the effective size of the main rollback
  42709. ** journal. The actual file might be larger than this in
  42710. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  42711. ** past pPager->journalOff is off-limits to us.
  42712. */
  42713. szJ = pPager->journalOff;
  42714. assert( pagerUseWal(pPager)==0 || szJ==0 );
  42715. /* Begin by rolling back records from the main journal starting at
  42716. ** PagerSavepoint.iOffset and continuing to the next journal header.
  42717. ** There might be records in the main journal that have a page number
  42718. ** greater than the current database size (pPager->dbSize) but those
  42719. ** will be skipped automatically. Pages are added to pDone as they
  42720. ** are played back.
  42721. */
  42722. if( pSavepoint && !pagerUseWal(pPager) ){
  42723. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  42724. pPager->journalOff = pSavepoint->iOffset;
  42725. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  42726. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42727. }
  42728. assert( rc!=SQLITE_DONE );
  42729. }else{
  42730. pPager->journalOff = 0;
  42731. }
  42732. /* Continue rolling back records out of the main journal starting at
  42733. ** the first journal header seen and continuing until the effective end
  42734. ** of the main journal file. Continue to skip out-of-range pages and
  42735. ** continue adding pages rolled back to pDone.
  42736. */
  42737. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  42738. u32 ii; /* Loop counter */
  42739. u32 nJRec = 0; /* Number of Journal Records */
  42740. u32 dummy;
  42741. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  42742. assert( rc!=SQLITE_DONE );
  42743. /*
  42744. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  42745. ** test is related to ticket #2565. See the discussion in the
  42746. ** pager_playback() function for additional information.
  42747. */
  42748. if( nJRec==0
  42749. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  42750. ){
  42751. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  42752. }
  42753. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  42754. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42755. }
  42756. assert( rc!=SQLITE_DONE );
  42757. }
  42758. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  42759. /* Finally, rollback pages from the sub-journal. Page that were
  42760. ** previously rolled back out of the main journal (and are hence in pDone)
  42761. ** will be skipped. Out-of-range pages are also skipped.
  42762. */
  42763. if( pSavepoint ){
  42764. u32 ii; /* Loop counter */
  42765. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  42766. if( pagerUseWal(pPager) ){
  42767. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  42768. }
  42769. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  42770. assert( offset==(i64)ii*(4+pPager->pageSize) );
  42771. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  42772. }
  42773. assert( rc!=SQLITE_DONE );
  42774. }
  42775. sqlite3BitvecDestroy(pDone);
  42776. if( rc==SQLITE_OK ){
  42777. pPager->journalOff = szJ;
  42778. }
  42779. return rc;
  42780. }
  42781. /*
  42782. ** Change the maximum number of in-memory pages that are allowed.
  42783. */
  42784. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  42785. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  42786. }
  42787. /*
  42788. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  42789. */
  42790. static void pagerFixMaplimit(Pager *pPager){
  42791. #if SQLITE_MAX_MMAP_SIZE>0
  42792. sqlite3_file *fd = pPager->fd;
  42793. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  42794. sqlite3_int64 sz;
  42795. sz = pPager->szMmap;
  42796. pPager->bUseFetch = (sz>0);
  42797. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  42798. }
  42799. #endif
  42800. }
  42801. /*
  42802. ** Change the maximum size of any memory mapping made of the database file.
  42803. */
  42804. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  42805. pPager->szMmap = szMmap;
  42806. pagerFixMaplimit(pPager);
  42807. }
  42808. /*
  42809. ** Free as much memory as possible from the pager.
  42810. */
  42811. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  42812. sqlite3PcacheShrink(pPager->pPCache);
  42813. }
  42814. /*
  42815. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  42816. **
  42817. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  42818. ** of the database to damage due to OS crashes or power failures by
  42819. ** changing the number of syncs()s when writing the journals.
  42820. ** There are three levels:
  42821. **
  42822. ** OFF sqlite3OsSync() is never called. This is the default
  42823. ** for temporary and transient files.
  42824. **
  42825. ** NORMAL The journal is synced once before writes begin on the
  42826. ** database. This is normally adequate protection, but
  42827. ** it is theoretically possible, though very unlikely,
  42828. ** that an inopertune power failure could leave the journal
  42829. ** in a state which would cause damage to the database
  42830. ** when it is rolled back.
  42831. **
  42832. ** FULL The journal is synced twice before writes begin on the
  42833. ** database (with some additional information - the nRec field
  42834. ** of the journal header - being written in between the two
  42835. ** syncs). If we assume that writing a
  42836. ** single disk sector is atomic, then this mode provides
  42837. ** assurance that the journal will not be corrupted to the
  42838. ** point of causing damage to the database during rollback.
  42839. **
  42840. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  42841. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  42842. ** prior to the start of checkpoint and that the database file is synced
  42843. ** at the conclusion of the checkpoint if the entire content of the WAL
  42844. ** was written back into the database. But no sync operations occur for
  42845. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  42846. ** file is synced following each commit operation, in addition to the
  42847. ** syncs associated with NORMAL.
  42848. **
  42849. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  42850. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  42851. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  42852. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  42853. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  42854. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  42855. ** the xSync primitive is called and is relevant to all platforms.
  42856. **
  42857. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  42858. ** and FULL=3.
  42859. */
  42860. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  42861. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  42862. Pager *pPager, /* The pager to set safety level for */
  42863. unsigned pgFlags /* Various flags */
  42864. ){
  42865. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  42866. assert( level>=1 && level<=3 );
  42867. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  42868. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  42869. if( pPager->noSync ){
  42870. pPager->syncFlags = 0;
  42871. pPager->ckptSyncFlags = 0;
  42872. }else if( pgFlags & PAGER_FULLFSYNC ){
  42873. pPager->syncFlags = SQLITE_SYNC_FULL;
  42874. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42875. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  42876. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42877. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42878. }else{
  42879. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42880. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  42881. }
  42882. pPager->walSyncFlags = pPager->syncFlags;
  42883. if( pPager->fullSync ){
  42884. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  42885. }
  42886. if( pgFlags & PAGER_CACHESPILL ){
  42887. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  42888. }else{
  42889. pPager->doNotSpill |= SPILLFLAG_OFF;
  42890. }
  42891. }
  42892. #endif
  42893. /*
  42894. ** The following global variable is incremented whenever the library
  42895. ** attempts to open a temporary file. This information is used for
  42896. ** testing and analysis only.
  42897. */
  42898. #ifdef SQLITE_TEST
  42899. SQLITE_API int sqlite3_opentemp_count = 0;
  42900. #endif
  42901. /*
  42902. ** Open a temporary file.
  42903. **
  42904. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  42905. ** or some other error code if we fail. The OS will automatically
  42906. ** delete the temporary file when it is closed.
  42907. **
  42908. ** The flags passed to the VFS layer xOpen() call are those specified
  42909. ** by parameter vfsFlags ORed with the following:
  42910. **
  42911. ** SQLITE_OPEN_READWRITE
  42912. ** SQLITE_OPEN_CREATE
  42913. ** SQLITE_OPEN_EXCLUSIVE
  42914. ** SQLITE_OPEN_DELETEONCLOSE
  42915. */
  42916. static int pagerOpentemp(
  42917. Pager *pPager, /* The pager object */
  42918. sqlite3_file *pFile, /* Write the file descriptor here */
  42919. int vfsFlags /* Flags passed through to the VFS */
  42920. ){
  42921. int rc; /* Return code */
  42922. #ifdef SQLITE_TEST
  42923. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  42924. #endif
  42925. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  42926. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  42927. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  42928. assert( rc!=SQLITE_OK || isOpen(pFile) );
  42929. return rc;
  42930. }
  42931. /*
  42932. ** Set the busy handler function.
  42933. **
  42934. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  42935. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  42936. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  42937. ** lock. It does *not* invoke the busy handler when upgrading from
  42938. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  42939. ** (which occurs during hot-journal rollback). Summary:
  42940. **
  42941. ** Transition | Invokes xBusyHandler
  42942. ** --------------------------------------------------------
  42943. ** NO_LOCK -> SHARED_LOCK | Yes
  42944. ** SHARED_LOCK -> RESERVED_LOCK | No
  42945. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  42946. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  42947. **
  42948. ** If the busy-handler callback returns non-zero, the lock is
  42949. ** retried. If it returns zero, then the SQLITE_BUSY error is
  42950. ** returned to the caller of the pager API function.
  42951. */
  42952. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  42953. Pager *pPager, /* Pager object */
  42954. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  42955. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  42956. ){
  42957. pPager->xBusyHandler = xBusyHandler;
  42958. pPager->pBusyHandlerArg = pBusyHandlerArg;
  42959. if( isOpen(pPager->fd) ){
  42960. void **ap = (void **)&pPager->xBusyHandler;
  42961. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  42962. assert( ap[1]==pBusyHandlerArg );
  42963. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  42964. }
  42965. }
  42966. /*
  42967. ** Change the page size used by the Pager object. The new page size
  42968. ** is passed in *pPageSize.
  42969. **
  42970. ** If the pager is in the error state when this function is called, it
  42971. ** is a no-op. The value returned is the error state error code (i.e.
  42972. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  42973. **
  42974. ** Otherwise, if all of the following are true:
  42975. **
  42976. ** * the new page size (value of *pPageSize) is valid (a power
  42977. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  42978. **
  42979. ** * there are no outstanding page references, and
  42980. **
  42981. ** * the database is either not an in-memory database or it is
  42982. ** an in-memory database that currently consists of zero pages.
  42983. **
  42984. ** then the pager object page size is set to *pPageSize.
  42985. **
  42986. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  42987. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  42988. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  42989. ** In all other cases, SQLITE_OK is returned.
  42990. **
  42991. ** If the page size is not changed, either because one of the enumerated
  42992. ** conditions above is not true, the pager was in error state when this
  42993. ** function was called, or because the memory allocation attempt failed,
  42994. ** then *pPageSize is set to the old, retained page size before returning.
  42995. */
  42996. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  42997. int rc = SQLITE_OK;
  42998. /* It is not possible to do a full assert_pager_state() here, as this
  42999. ** function may be called from within PagerOpen(), before the state
  43000. ** of the Pager object is internally consistent.
  43001. **
  43002. ** At one point this function returned an error if the pager was in
  43003. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  43004. ** there is at least one outstanding page reference, this function
  43005. ** is a no-op for that case anyhow.
  43006. */
  43007. u32 pageSize = *pPageSize;
  43008. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  43009. if( (pPager->memDb==0 || pPager->dbSize==0)
  43010. && sqlite3PcacheRefCount(pPager->pPCache)==0
  43011. && pageSize && pageSize!=(u32)pPager->pageSize
  43012. ){
  43013. char *pNew = NULL; /* New temp space */
  43014. i64 nByte = 0;
  43015. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  43016. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  43017. }
  43018. if( rc==SQLITE_OK ){
  43019. pNew = (char *)sqlite3PageMalloc(pageSize);
  43020. if( !pNew ) rc = SQLITE_NOMEM;
  43021. }
  43022. if( rc==SQLITE_OK ){
  43023. pager_reset(pPager);
  43024. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  43025. }
  43026. if( rc==SQLITE_OK ){
  43027. sqlite3PageFree(pPager->pTmpSpace);
  43028. pPager->pTmpSpace = pNew;
  43029. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  43030. pPager->pageSize = pageSize;
  43031. }else{
  43032. sqlite3PageFree(pNew);
  43033. }
  43034. }
  43035. *pPageSize = pPager->pageSize;
  43036. if( rc==SQLITE_OK ){
  43037. if( nReserve<0 ) nReserve = pPager->nReserve;
  43038. assert( nReserve>=0 && nReserve<1000 );
  43039. pPager->nReserve = (i16)nReserve;
  43040. pagerReportSize(pPager);
  43041. pagerFixMaplimit(pPager);
  43042. }
  43043. return rc;
  43044. }
  43045. /*
  43046. ** Return a pointer to the "temporary page" buffer held internally
  43047. ** by the pager. This is a buffer that is big enough to hold the
  43048. ** entire content of a database page. This buffer is used internally
  43049. ** during rollback and will be overwritten whenever a rollback
  43050. ** occurs. But other modules are free to use it too, as long as
  43051. ** no rollbacks are happening.
  43052. */
  43053. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  43054. return pPager->pTmpSpace;
  43055. }
  43056. /*
  43057. ** Attempt to set the maximum database page count if mxPage is positive.
  43058. ** Make no changes if mxPage is zero or negative. And never reduce the
  43059. ** maximum page count below the current size of the database.
  43060. **
  43061. ** Regardless of mxPage, return the current maximum page count.
  43062. */
  43063. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  43064. if( mxPage>0 ){
  43065. pPager->mxPgno = mxPage;
  43066. }
  43067. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  43068. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  43069. return pPager->mxPgno;
  43070. }
  43071. /*
  43072. ** The following set of routines are used to disable the simulated
  43073. ** I/O error mechanism. These routines are used to avoid simulated
  43074. ** errors in places where we do not care about errors.
  43075. **
  43076. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  43077. ** and generate no code.
  43078. */
  43079. #ifdef SQLITE_TEST
  43080. SQLITE_API extern int sqlite3_io_error_pending;
  43081. SQLITE_API extern int sqlite3_io_error_hit;
  43082. static int saved_cnt;
  43083. void disable_simulated_io_errors(void){
  43084. saved_cnt = sqlite3_io_error_pending;
  43085. sqlite3_io_error_pending = -1;
  43086. }
  43087. void enable_simulated_io_errors(void){
  43088. sqlite3_io_error_pending = saved_cnt;
  43089. }
  43090. #else
  43091. # define disable_simulated_io_errors()
  43092. # define enable_simulated_io_errors()
  43093. #endif
  43094. /*
  43095. ** Read the first N bytes from the beginning of the file into memory
  43096. ** that pDest points to.
  43097. **
  43098. ** If the pager was opened on a transient file (zFilename==""), or
  43099. ** opened on a file less than N bytes in size, the output buffer is
  43100. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  43101. ** function is used to read database headers, and a new transient or
  43102. ** zero sized database has a header than consists entirely of zeroes.
  43103. **
  43104. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  43105. ** the error code is returned to the caller and the contents of the
  43106. ** output buffer undefined.
  43107. */
  43108. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  43109. int rc = SQLITE_OK;
  43110. memset(pDest, 0, N);
  43111. assert( isOpen(pPager->fd) || pPager->tempFile );
  43112. /* This routine is only called by btree immediately after creating
  43113. ** the Pager object. There has not been an opportunity to transition
  43114. ** to WAL mode yet.
  43115. */
  43116. assert( !pagerUseWal(pPager) );
  43117. if( isOpen(pPager->fd) ){
  43118. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  43119. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  43120. if( rc==SQLITE_IOERR_SHORT_READ ){
  43121. rc = SQLITE_OK;
  43122. }
  43123. }
  43124. return rc;
  43125. }
  43126. /*
  43127. ** This function may only be called when a read-transaction is open on
  43128. ** the pager. It returns the total number of pages in the database.
  43129. **
  43130. ** However, if the file is between 1 and <page-size> bytes in size, then
  43131. ** this is considered a 1 page file.
  43132. */
  43133. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  43134. assert( pPager->eState>=PAGER_READER );
  43135. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  43136. *pnPage = (int)pPager->dbSize;
  43137. }
  43138. /*
  43139. ** Try to obtain a lock of type locktype on the database file. If
  43140. ** a similar or greater lock is already held, this function is a no-op
  43141. ** (returning SQLITE_OK immediately).
  43142. **
  43143. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  43144. ** the busy callback if the lock is currently not available. Repeat
  43145. ** until the busy callback returns false or until the attempt to
  43146. ** obtain the lock succeeds.
  43147. **
  43148. ** Return SQLITE_OK on success and an error code if we cannot obtain
  43149. ** the lock. If the lock is obtained successfully, set the Pager.state
  43150. ** variable to locktype before returning.
  43151. */
  43152. static int pager_wait_on_lock(Pager *pPager, int locktype){
  43153. int rc; /* Return code */
  43154. /* Check that this is either a no-op (because the requested lock is
  43155. ** already held), or one of the transitions that the busy-handler
  43156. ** may be invoked during, according to the comment above
  43157. ** sqlite3PagerSetBusyhandler().
  43158. */
  43159. assert( (pPager->eLock>=locktype)
  43160. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  43161. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  43162. );
  43163. do {
  43164. rc = pagerLockDb(pPager, locktype);
  43165. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  43166. return rc;
  43167. }
  43168. /*
  43169. ** Function assertTruncateConstraint(pPager) checks that one of the
  43170. ** following is true for all dirty pages currently in the page-cache:
  43171. **
  43172. ** a) The page number is less than or equal to the size of the
  43173. ** current database image, in pages, OR
  43174. **
  43175. ** b) if the page content were written at this time, it would not
  43176. ** be necessary to write the current content out to the sub-journal
  43177. ** (as determined by function subjRequiresPage()).
  43178. **
  43179. ** If the condition asserted by this function were not true, and the
  43180. ** dirty page were to be discarded from the cache via the pagerStress()
  43181. ** routine, pagerStress() would not write the current page content to
  43182. ** the database file. If a savepoint transaction were rolled back after
  43183. ** this happened, the correct behavior would be to restore the current
  43184. ** content of the page. However, since this content is not present in either
  43185. ** the database file or the portion of the rollback journal and
  43186. ** sub-journal rolled back the content could not be restored and the
  43187. ** database image would become corrupt. It is therefore fortunate that
  43188. ** this circumstance cannot arise.
  43189. */
  43190. #if defined(SQLITE_DEBUG)
  43191. static void assertTruncateConstraintCb(PgHdr *pPg){
  43192. assert( pPg->flags&PGHDR_DIRTY );
  43193. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  43194. }
  43195. static void assertTruncateConstraint(Pager *pPager){
  43196. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  43197. }
  43198. #else
  43199. # define assertTruncateConstraint(pPager)
  43200. #endif
  43201. /*
  43202. ** Truncate the in-memory database file image to nPage pages. This
  43203. ** function does not actually modify the database file on disk. It
  43204. ** just sets the internal state of the pager object so that the
  43205. ** truncation will be done when the current transaction is committed.
  43206. **
  43207. ** This function is only called right before committing a transaction.
  43208. ** Once this function has been called, the transaction must either be
  43209. ** rolled back or committed. It is not safe to call this function and
  43210. ** then continue writing to the database.
  43211. */
  43212. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  43213. assert( pPager->dbSize>=nPage );
  43214. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  43215. pPager->dbSize = nPage;
  43216. /* At one point the code here called assertTruncateConstraint() to
  43217. ** ensure that all pages being truncated away by this operation are,
  43218. ** if one or more savepoints are open, present in the savepoint
  43219. ** journal so that they can be restored if the savepoint is rolled
  43220. ** back. This is no longer necessary as this function is now only
  43221. ** called right before committing a transaction. So although the
  43222. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  43223. ** they cannot be rolled back. So the assertTruncateConstraint() call
  43224. ** is no longer correct. */
  43225. }
  43226. /*
  43227. ** This function is called before attempting a hot-journal rollback. It
  43228. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  43229. ** size of the journal file so that the pager_playback() routine knows
  43230. ** that the entire journal file has been synced.
  43231. **
  43232. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  43233. ** that if a power-failure occurs during the rollback, the process that
  43234. ** attempts rollback following system recovery sees the same journal
  43235. ** content as this process.
  43236. **
  43237. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  43238. ** an SQLite error code.
  43239. */
  43240. static int pagerSyncHotJournal(Pager *pPager){
  43241. int rc = SQLITE_OK;
  43242. if( !pPager->noSync ){
  43243. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  43244. }
  43245. if( rc==SQLITE_OK ){
  43246. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  43247. }
  43248. return rc;
  43249. }
  43250. /*
  43251. ** Obtain a reference to a memory mapped page object for page number pgno.
  43252. ** The new object will use the pointer pData, obtained from xFetch().
  43253. ** If successful, set *ppPage to point to the new page reference
  43254. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  43255. ** *ppPage to zero.
  43256. **
  43257. ** Page references obtained by calling this function should be released
  43258. ** by calling pagerReleaseMapPage().
  43259. */
  43260. static int pagerAcquireMapPage(
  43261. Pager *pPager, /* Pager object */
  43262. Pgno pgno, /* Page number */
  43263. void *pData, /* xFetch()'d data for this page */
  43264. PgHdr **ppPage /* OUT: Acquired page object */
  43265. ){
  43266. PgHdr *p; /* Memory mapped page to return */
  43267. if( pPager->pMmapFreelist ){
  43268. *ppPage = p = pPager->pMmapFreelist;
  43269. pPager->pMmapFreelist = p->pDirty;
  43270. p->pDirty = 0;
  43271. memset(p->pExtra, 0, pPager->nExtra);
  43272. }else{
  43273. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  43274. if( p==0 ){
  43275. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  43276. return SQLITE_NOMEM;
  43277. }
  43278. p->pExtra = (void *)&p[1];
  43279. p->flags = PGHDR_MMAP;
  43280. p->nRef = 1;
  43281. p->pPager = pPager;
  43282. }
  43283. assert( p->pExtra==(void *)&p[1] );
  43284. assert( p->pPage==0 );
  43285. assert( p->flags==PGHDR_MMAP );
  43286. assert( p->pPager==pPager );
  43287. assert( p->nRef==1 );
  43288. p->pgno = pgno;
  43289. p->pData = pData;
  43290. pPager->nMmapOut++;
  43291. return SQLITE_OK;
  43292. }
  43293. /*
  43294. ** Release a reference to page pPg. pPg must have been returned by an
  43295. ** earlier call to pagerAcquireMapPage().
  43296. */
  43297. static void pagerReleaseMapPage(PgHdr *pPg){
  43298. Pager *pPager = pPg->pPager;
  43299. pPager->nMmapOut--;
  43300. pPg->pDirty = pPager->pMmapFreelist;
  43301. pPager->pMmapFreelist = pPg;
  43302. assert( pPager->fd->pMethods->iVersion>=3 );
  43303. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  43304. }
  43305. /*
  43306. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  43307. */
  43308. static void pagerFreeMapHdrs(Pager *pPager){
  43309. PgHdr *p;
  43310. PgHdr *pNext;
  43311. for(p=pPager->pMmapFreelist; p; p=pNext){
  43312. pNext = p->pDirty;
  43313. sqlite3_free(p);
  43314. }
  43315. }
  43316. /*
  43317. ** Shutdown the page cache. Free all memory and close all files.
  43318. **
  43319. ** If a transaction was in progress when this routine is called, that
  43320. ** transaction is rolled back. All outstanding pages are invalidated
  43321. ** and their memory is freed. Any attempt to use a page associated
  43322. ** with this page cache after this function returns will likely
  43323. ** result in a coredump.
  43324. **
  43325. ** This function always succeeds. If a transaction is active an attempt
  43326. ** is made to roll it back. If an error occurs during the rollback
  43327. ** a hot journal may be left in the filesystem but no error is returned
  43328. ** to the caller.
  43329. */
  43330. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  43331. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  43332. assert( assert_pager_state(pPager) );
  43333. disable_simulated_io_errors();
  43334. sqlite3BeginBenignMalloc();
  43335. pagerFreeMapHdrs(pPager);
  43336. /* pPager->errCode = 0; */
  43337. pPager->exclusiveMode = 0;
  43338. #ifndef SQLITE_OMIT_WAL
  43339. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  43340. pPager->pWal = 0;
  43341. #endif
  43342. pager_reset(pPager);
  43343. if( MEMDB ){
  43344. pager_unlock(pPager);
  43345. }else{
  43346. /* If it is open, sync the journal file before calling UnlockAndRollback.
  43347. ** If this is not done, then an unsynced portion of the open journal
  43348. ** file may be played back into the database. If a power failure occurs
  43349. ** while this is happening, the database could become corrupt.
  43350. **
  43351. ** If an error occurs while trying to sync the journal, shift the pager
  43352. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  43353. ** database and close the journal file without attempting to roll it
  43354. ** back or finalize it. The next database user will have to do hot-journal
  43355. ** rollback before accessing the database file.
  43356. */
  43357. if( isOpen(pPager->jfd) ){
  43358. pager_error(pPager, pagerSyncHotJournal(pPager));
  43359. }
  43360. pagerUnlockAndRollback(pPager);
  43361. }
  43362. sqlite3EndBenignMalloc();
  43363. enable_simulated_io_errors();
  43364. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  43365. IOTRACE(("CLOSE %p\n", pPager))
  43366. sqlite3OsClose(pPager->jfd);
  43367. sqlite3OsClose(pPager->fd);
  43368. sqlite3PageFree(pTmp);
  43369. sqlite3PcacheClose(pPager->pPCache);
  43370. #ifdef SQLITE_HAS_CODEC
  43371. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  43372. #endif
  43373. assert( !pPager->aSavepoint && !pPager->pInJournal );
  43374. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  43375. sqlite3_free(pPager);
  43376. return SQLITE_OK;
  43377. }
  43378. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  43379. /*
  43380. ** Return the page number for page pPg.
  43381. */
  43382. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  43383. return pPg->pgno;
  43384. }
  43385. #endif
  43386. /*
  43387. ** Increment the reference count for page pPg.
  43388. */
  43389. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  43390. sqlite3PcacheRef(pPg);
  43391. }
  43392. /*
  43393. ** Sync the journal. In other words, make sure all the pages that have
  43394. ** been written to the journal have actually reached the surface of the
  43395. ** disk and can be restored in the event of a hot-journal rollback.
  43396. **
  43397. ** If the Pager.noSync flag is set, then this function is a no-op.
  43398. ** Otherwise, the actions required depend on the journal-mode and the
  43399. ** device characteristics of the file-system, as follows:
  43400. **
  43401. ** * If the journal file is an in-memory journal file, no action need
  43402. ** be taken.
  43403. **
  43404. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  43405. ** then the nRec field of the most recently written journal header
  43406. ** is updated to contain the number of journal records that have
  43407. ** been written following it. If the pager is operating in full-sync
  43408. ** mode, then the journal file is synced before this field is updated.
  43409. **
  43410. ** * If the device does not support the SEQUENTIAL property, then
  43411. ** journal file is synced.
  43412. **
  43413. ** Or, in pseudo-code:
  43414. **
  43415. ** if( NOT <in-memory journal> ){
  43416. ** if( NOT SAFE_APPEND ){
  43417. ** if( <full-sync mode> ) xSync(<journal file>);
  43418. ** <update nRec field>
  43419. ** }
  43420. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  43421. ** }
  43422. **
  43423. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  43424. ** page currently held in memory before returning SQLITE_OK. If an IO
  43425. ** error is encountered, then the IO error code is returned to the caller.
  43426. */
  43427. static int syncJournal(Pager *pPager, int newHdr){
  43428. int rc; /* Return code */
  43429. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  43430. || pPager->eState==PAGER_WRITER_DBMOD
  43431. );
  43432. assert( assert_pager_state(pPager) );
  43433. assert( !pagerUseWal(pPager) );
  43434. rc = sqlite3PagerExclusiveLock(pPager);
  43435. if( rc!=SQLITE_OK ) return rc;
  43436. if( !pPager->noSync ){
  43437. assert( !pPager->tempFile );
  43438. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  43439. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  43440. assert( isOpen(pPager->jfd) );
  43441. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  43442. /* This block deals with an obscure problem. If the last connection
  43443. ** that wrote to this database was operating in persistent-journal
  43444. ** mode, then the journal file may at this point actually be larger
  43445. ** than Pager.journalOff bytes. If the next thing in the journal
  43446. ** file happens to be a journal-header (written as part of the
  43447. ** previous connection's transaction), and a crash or power-failure
  43448. ** occurs after nRec is updated but before this connection writes
  43449. ** anything else to the journal file (or commits/rolls back its
  43450. ** transaction), then SQLite may become confused when doing the
  43451. ** hot-journal rollback following recovery. It may roll back all
  43452. ** of this connections data, then proceed to rolling back the old,
  43453. ** out-of-date data that follows it. Database corruption.
  43454. **
  43455. ** To work around this, if the journal file does appear to contain
  43456. ** a valid header following Pager.journalOff, then write a 0x00
  43457. ** byte to the start of it to prevent it from being recognized.
  43458. **
  43459. ** Variable iNextHdrOffset is set to the offset at which this
  43460. ** problematic header will occur, if it exists. aMagic is used
  43461. ** as a temporary buffer to inspect the first couple of bytes of
  43462. ** the potential journal header.
  43463. */
  43464. i64 iNextHdrOffset;
  43465. u8 aMagic[8];
  43466. u8 zHeader[sizeof(aJournalMagic)+4];
  43467. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  43468. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  43469. iNextHdrOffset = journalHdrOffset(pPager);
  43470. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  43471. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  43472. static const u8 zerobyte = 0;
  43473. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  43474. }
  43475. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  43476. return rc;
  43477. }
  43478. /* Write the nRec value into the journal file header. If in
  43479. ** full-synchronous mode, sync the journal first. This ensures that
  43480. ** all data has really hit the disk before nRec is updated to mark
  43481. ** it as a candidate for rollback.
  43482. **
  43483. ** This is not required if the persistent media supports the
  43484. ** SAFE_APPEND property. Because in this case it is not possible
  43485. ** for garbage data to be appended to the file, the nRec field
  43486. ** is populated with 0xFFFFFFFF when the journal header is written
  43487. ** and never needs to be updated.
  43488. */
  43489. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  43490. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  43491. IOTRACE(("JSYNC %p\n", pPager))
  43492. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  43493. if( rc!=SQLITE_OK ) return rc;
  43494. }
  43495. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  43496. rc = sqlite3OsWrite(
  43497. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  43498. );
  43499. if( rc!=SQLITE_OK ) return rc;
  43500. }
  43501. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  43502. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  43503. IOTRACE(("JSYNC %p\n", pPager))
  43504. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  43505. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  43506. );
  43507. if( rc!=SQLITE_OK ) return rc;
  43508. }
  43509. pPager->journalHdr = pPager->journalOff;
  43510. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  43511. pPager->nRec = 0;
  43512. rc = writeJournalHdr(pPager);
  43513. if( rc!=SQLITE_OK ) return rc;
  43514. }
  43515. }else{
  43516. pPager->journalHdr = pPager->journalOff;
  43517. }
  43518. }
  43519. /* Unless the pager is in noSync mode, the journal file was just
  43520. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  43521. ** all pages.
  43522. */
  43523. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  43524. pPager->eState = PAGER_WRITER_DBMOD;
  43525. assert( assert_pager_state(pPager) );
  43526. return SQLITE_OK;
  43527. }
  43528. /*
  43529. ** The argument is the first in a linked list of dirty pages connected
  43530. ** by the PgHdr.pDirty pointer. This function writes each one of the
  43531. ** in-memory pages in the list to the database file. The argument may
  43532. ** be NULL, representing an empty list. In this case this function is
  43533. ** a no-op.
  43534. **
  43535. ** The pager must hold at least a RESERVED lock when this function
  43536. ** is called. Before writing anything to the database file, this lock
  43537. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  43538. ** SQLITE_BUSY is returned and no data is written to the database file.
  43539. **
  43540. ** If the pager is a temp-file pager and the actual file-system file
  43541. ** is not yet open, it is created and opened before any data is
  43542. ** written out.
  43543. **
  43544. ** Once the lock has been upgraded and, if necessary, the file opened,
  43545. ** the pages are written out to the database file in list order. Writing
  43546. ** a page is skipped if it meets either of the following criteria:
  43547. **
  43548. ** * The page number is greater than Pager.dbSize, or
  43549. ** * The PGHDR_DONT_WRITE flag is set on the page.
  43550. **
  43551. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  43552. ** is updated accordingly. If page 1 is written out, then the value cached
  43553. ** in Pager.dbFileVers[] is updated to match the new value stored in
  43554. ** the database file.
  43555. **
  43556. ** If everything is successful, SQLITE_OK is returned. If an IO error
  43557. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  43558. ** be obtained, SQLITE_BUSY is returned.
  43559. */
  43560. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  43561. int rc = SQLITE_OK; /* Return code */
  43562. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  43563. assert( !pagerUseWal(pPager) );
  43564. assert( pPager->eState==PAGER_WRITER_DBMOD );
  43565. assert( pPager->eLock==EXCLUSIVE_LOCK );
  43566. /* If the file is a temp-file has not yet been opened, open it now. It
  43567. ** is not possible for rc to be other than SQLITE_OK if this branch
  43568. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  43569. */
  43570. if( !isOpen(pPager->fd) ){
  43571. assert( pPager->tempFile && rc==SQLITE_OK );
  43572. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  43573. }
  43574. /* Before the first write, give the VFS a hint of what the final
  43575. ** file size will be.
  43576. */
  43577. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  43578. if( rc==SQLITE_OK
  43579. && pPager->dbHintSize<pPager->dbSize
  43580. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  43581. ){
  43582. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  43583. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  43584. pPager->dbHintSize = pPager->dbSize;
  43585. }
  43586. while( rc==SQLITE_OK && pList ){
  43587. Pgno pgno = pList->pgno;
  43588. /* If there are dirty pages in the page cache with page numbers greater
  43589. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  43590. ** make the file smaller (presumably by auto-vacuum code). Do not write
  43591. ** any such pages to the file.
  43592. **
  43593. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  43594. ** set (set by sqlite3PagerDontWrite()).
  43595. */
  43596. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  43597. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  43598. char *pData; /* Data to write */
  43599. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  43600. if( pList->pgno==1 ) pager_write_changecounter(pList);
  43601. /* Encode the database */
  43602. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  43603. /* Write out the page data. */
  43604. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  43605. /* If page 1 was just written, update Pager.dbFileVers to match
  43606. ** the value now stored in the database file. If writing this
  43607. ** page caused the database file to grow, update dbFileSize.
  43608. */
  43609. if( pgno==1 ){
  43610. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  43611. }
  43612. if( pgno>pPager->dbFileSize ){
  43613. pPager->dbFileSize = pgno;
  43614. }
  43615. pPager->aStat[PAGER_STAT_WRITE]++;
  43616. /* Update any backup objects copying the contents of this pager. */
  43617. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  43618. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  43619. PAGERID(pPager), pgno, pager_pagehash(pList)));
  43620. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  43621. PAGER_INCR(sqlite3_pager_writedb_count);
  43622. }else{
  43623. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  43624. }
  43625. pager_set_pagehash(pList);
  43626. pList = pList->pDirty;
  43627. }
  43628. return rc;
  43629. }
  43630. /*
  43631. ** Ensure that the sub-journal file is open. If it is already open, this
  43632. ** function is a no-op.
  43633. **
  43634. ** SQLITE_OK is returned if everything goes according to plan. An
  43635. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  43636. ** fails.
  43637. */
  43638. static int openSubJournal(Pager *pPager){
  43639. int rc = SQLITE_OK;
  43640. if( !isOpen(pPager->sjfd) ){
  43641. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  43642. sqlite3MemJournalOpen(pPager->sjfd);
  43643. }else{
  43644. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  43645. }
  43646. }
  43647. return rc;
  43648. }
  43649. /*
  43650. ** Append a record of the current state of page pPg to the sub-journal.
  43651. **
  43652. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  43653. ** for all open savepoints before returning.
  43654. **
  43655. ** This function returns SQLITE_OK if everything is successful, an IO
  43656. ** error code if the attempt to write to the sub-journal fails, or
  43657. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  43658. ** bitvec.
  43659. */
  43660. static int subjournalPage(PgHdr *pPg){
  43661. int rc = SQLITE_OK;
  43662. Pager *pPager = pPg->pPager;
  43663. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  43664. /* Open the sub-journal, if it has not already been opened */
  43665. assert( pPager->useJournal );
  43666. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  43667. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  43668. assert( pagerUseWal(pPager)
  43669. || pageInJournal(pPager, pPg)
  43670. || pPg->pgno>pPager->dbOrigSize
  43671. );
  43672. rc = openSubJournal(pPager);
  43673. /* If the sub-journal was opened successfully (or was already open),
  43674. ** write the journal record into the file. */
  43675. if( rc==SQLITE_OK ){
  43676. void *pData = pPg->pData;
  43677. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  43678. char *pData2;
  43679. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  43680. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  43681. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  43682. if( rc==SQLITE_OK ){
  43683. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  43684. }
  43685. }
  43686. }
  43687. if( rc==SQLITE_OK ){
  43688. pPager->nSubRec++;
  43689. assert( pPager->nSavepoint>0 );
  43690. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  43691. }
  43692. return rc;
  43693. }
  43694. static int subjournalPageIfRequired(PgHdr *pPg){
  43695. if( subjRequiresPage(pPg) ){
  43696. return subjournalPage(pPg);
  43697. }else{
  43698. return SQLITE_OK;
  43699. }
  43700. }
  43701. /*
  43702. ** This function is called by the pcache layer when it has reached some
  43703. ** soft memory limit. The first argument is a pointer to a Pager object
  43704. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  43705. ** database). The second argument is a reference to a page that is
  43706. ** currently dirty but has no outstanding references. The page
  43707. ** is always associated with the Pager object passed as the first
  43708. ** argument.
  43709. **
  43710. ** The job of this function is to make pPg clean by writing its contents
  43711. ** out to the database file, if possible. This may involve syncing the
  43712. ** journal file.
  43713. **
  43714. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  43715. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  43716. ** page clean, the IO error code is returned. If the page cannot be
  43717. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  43718. ** is returned by sqlite3PcacheMakeClean() is not called.
  43719. */
  43720. static int pagerStress(void *p, PgHdr *pPg){
  43721. Pager *pPager = (Pager *)p;
  43722. int rc = SQLITE_OK;
  43723. assert( pPg->pPager==pPager );
  43724. assert( pPg->flags&PGHDR_DIRTY );
  43725. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  43726. ** journal (and adding a new header) is not allowed. This occurs
  43727. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  43728. ** pages belonging to the same sector.
  43729. **
  43730. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  43731. ** regardless of whether or not a sync is required. This is set during
  43732. ** a rollback or by user request, respectively.
  43733. **
  43734. ** Spilling is also prohibited when in an error state since that could
  43735. ** lead to database corruption. In the current implementation it
  43736. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  43737. ** while in the error state, hence it is impossible for this routine to
  43738. ** be called in the error state. Nevertheless, we include a NEVER()
  43739. ** test for the error state as a safeguard against future changes.
  43740. */
  43741. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  43742. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  43743. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  43744. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  43745. if( pPager->doNotSpill
  43746. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  43747. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  43748. ){
  43749. return SQLITE_OK;
  43750. }
  43751. pPg->pDirty = 0;
  43752. if( pagerUseWal(pPager) ){
  43753. /* Write a single frame for this page to the log. */
  43754. rc = subjournalPageIfRequired(pPg);
  43755. if( rc==SQLITE_OK ){
  43756. rc = pagerWalFrames(pPager, pPg, 0, 0);
  43757. }
  43758. }else{
  43759. /* Sync the journal file if required. */
  43760. if( pPg->flags&PGHDR_NEED_SYNC
  43761. || pPager->eState==PAGER_WRITER_CACHEMOD
  43762. ){
  43763. rc = syncJournal(pPager, 1);
  43764. }
  43765. /* Write the contents of the page out to the database file. */
  43766. if( rc==SQLITE_OK ){
  43767. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  43768. rc = pager_write_pagelist(pPager, pPg);
  43769. }
  43770. }
  43771. /* Mark the page as clean. */
  43772. if( rc==SQLITE_OK ){
  43773. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  43774. sqlite3PcacheMakeClean(pPg);
  43775. }
  43776. return pager_error(pPager, rc);
  43777. }
  43778. /*
  43779. ** Allocate and initialize a new Pager object and put a pointer to it
  43780. ** in *ppPager. The pager should eventually be freed by passing it
  43781. ** to sqlite3PagerClose().
  43782. **
  43783. ** The zFilename argument is the path to the database file to open.
  43784. ** If zFilename is NULL then a randomly-named temporary file is created
  43785. ** and used as the file to be cached. Temporary files are be deleted
  43786. ** automatically when they are closed. If zFilename is ":memory:" then
  43787. ** all information is held in cache. It is never written to disk.
  43788. ** This can be used to implement an in-memory database.
  43789. **
  43790. ** The nExtra parameter specifies the number of bytes of space allocated
  43791. ** along with each page reference. This space is available to the user
  43792. ** via the sqlite3PagerGetExtra() API.
  43793. **
  43794. ** The flags argument is used to specify properties that affect the
  43795. ** operation of the pager. It should be passed some bitwise combination
  43796. ** of the PAGER_* flags.
  43797. **
  43798. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  43799. ** of the xOpen() method of the supplied VFS when opening files.
  43800. **
  43801. ** If the pager object is allocated and the specified file opened
  43802. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  43803. ** the new pager object. If an error occurs, *ppPager is set to NULL
  43804. ** and error code returned. This function may return SQLITE_NOMEM
  43805. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  43806. ** various SQLITE_IO_XXX errors.
  43807. */
  43808. SQLITE_PRIVATE int sqlite3PagerOpen(
  43809. sqlite3_vfs *pVfs, /* The virtual file system to use */
  43810. Pager **ppPager, /* OUT: Return the Pager structure here */
  43811. const char *zFilename, /* Name of the database file to open */
  43812. int nExtra, /* Extra bytes append to each in-memory page */
  43813. int flags, /* flags controlling this file */
  43814. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  43815. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  43816. ){
  43817. u8 *pPtr;
  43818. Pager *pPager = 0; /* Pager object to allocate and return */
  43819. int rc = SQLITE_OK; /* Return code */
  43820. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  43821. int memDb = 0; /* True if this is an in-memory file */
  43822. int readOnly = 0; /* True if this is a read-only file */
  43823. int journalFileSize; /* Bytes to allocate for each journal fd */
  43824. char *zPathname = 0; /* Full path to database file */
  43825. int nPathname = 0; /* Number of bytes in zPathname */
  43826. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  43827. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  43828. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  43829. const char *zUri = 0; /* URI args to copy */
  43830. int nUri = 0; /* Number of bytes of URI args at *zUri */
  43831. /* Figure out how much space is required for each journal file-handle
  43832. ** (there are two of them, the main journal and the sub-journal). This
  43833. ** is the maximum space required for an in-memory journal file handle
  43834. ** and a regular journal file-handle. Note that a "regular journal-handle"
  43835. ** may be a wrapper capable of caching the first portion of the journal
  43836. ** file in memory to implement the atomic-write optimization (see
  43837. ** source file journal.c).
  43838. */
  43839. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  43840. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  43841. }else{
  43842. journalFileSize = ROUND8(sqlite3MemJournalSize());
  43843. }
  43844. /* Set the output variable to NULL in case an error occurs. */
  43845. *ppPager = 0;
  43846. #ifndef SQLITE_OMIT_MEMORYDB
  43847. if( flags & PAGER_MEMORY ){
  43848. memDb = 1;
  43849. if( zFilename && zFilename[0] ){
  43850. zPathname = sqlite3DbStrDup(0, zFilename);
  43851. if( zPathname==0 ) return SQLITE_NOMEM;
  43852. nPathname = sqlite3Strlen30(zPathname);
  43853. zFilename = 0;
  43854. }
  43855. }
  43856. #endif
  43857. /* Compute and store the full pathname in an allocated buffer pointed
  43858. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  43859. ** leave both nPathname and zPathname set to 0.
  43860. */
  43861. if( zFilename && zFilename[0] ){
  43862. const char *z;
  43863. nPathname = pVfs->mxPathname+1;
  43864. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  43865. if( zPathname==0 ){
  43866. return SQLITE_NOMEM;
  43867. }
  43868. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  43869. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  43870. nPathname = sqlite3Strlen30(zPathname);
  43871. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  43872. while( *z ){
  43873. z += sqlite3Strlen30(z)+1;
  43874. z += sqlite3Strlen30(z)+1;
  43875. }
  43876. nUri = (int)(&z[1] - zUri);
  43877. assert( nUri>=0 );
  43878. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  43879. /* This branch is taken when the journal path required by
  43880. ** the database being opened will be more than pVfs->mxPathname
  43881. ** bytes in length. This means the database cannot be opened,
  43882. ** as it will not be possible to open the journal file or even
  43883. ** check for a hot-journal before reading.
  43884. */
  43885. rc = SQLITE_CANTOPEN_BKPT;
  43886. }
  43887. if( rc!=SQLITE_OK ){
  43888. sqlite3DbFree(0, zPathname);
  43889. return rc;
  43890. }
  43891. }
  43892. /* Allocate memory for the Pager structure, PCache object, the
  43893. ** three file descriptors, the database file name and the journal
  43894. ** file name. The layout in memory is as follows:
  43895. **
  43896. ** Pager object (sizeof(Pager) bytes)
  43897. ** PCache object (sqlite3PcacheSize() bytes)
  43898. ** Database file handle (pVfs->szOsFile bytes)
  43899. ** Sub-journal file handle (journalFileSize bytes)
  43900. ** Main journal file handle (journalFileSize bytes)
  43901. ** Database file name (nPathname+1 bytes)
  43902. ** Journal file name (nPathname+8+1 bytes)
  43903. */
  43904. pPtr = (u8 *)sqlite3MallocZero(
  43905. ROUND8(sizeof(*pPager)) + /* Pager structure */
  43906. ROUND8(pcacheSize) + /* PCache object */
  43907. ROUND8(pVfs->szOsFile) + /* The main db file */
  43908. journalFileSize * 2 + /* The two journal files */
  43909. nPathname + 1 + nUri + /* zFilename */
  43910. nPathname + 8 + 2 /* zJournal */
  43911. #ifndef SQLITE_OMIT_WAL
  43912. + nPathname + 4 + 2 /* zWal */
  43913. #endif
  43914. );
  43915. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  43916. if( !pPtr ){
  43917. sqlite3DbFree(0, zPathname);
  43918. return SQLITE_NOMEM;
  43919. }
  43920. pPager = (Pager*)(pPtr);
  43921. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  43922. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  43923. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  43924. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  43925. pPager->zFilename = (char*)(pPtr += journalFileSize);
  43926. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  43927. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  43928. if( zPathname ){
  43929. assert( nPathname>0 );
  43930. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  43931. memcpy(pPager->zFilename, zPathname, nPathname);
  43932. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  43933. memcpy(pPager->zJournal, zPathname, nPathname);
  43934. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  43935. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  43936. #ifndef SQLITE_OMIT_WAL
  43937. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  43938. memcpy(pPager->zWal, zPathname, nPathname);
  43939. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  43940. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  43941. #endif
  43942. sqlite3DbFree(0, zPathname);
  43943. }
  43944. pPager->pVfs = pVfs;
  43945. pPager->vfsFlags = vfsFlags;
  43946. /* Open the pager file.
  43947. */
  43948. if( zFilename && zFilename[0] ){
  43949. int fout = 0; /* VFS flags returned by xOpen() */
  43950. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  43951. assert( !memDb );
  43952. readOnly = (fout&SQLITE_OPEN_READONLY);
  43953. /* If the file was successfully opened for read/write access,
  43954. ** choose a default page size in case we have to create the
  43955. ** database file. The default page size is the maximum of:
  43956. **
  43957. ** + SQLITE_DEFAULT_PAGE_SIZE,
  43958. ** + The value returned by sqlite3OsSectorSize()
  43959. ** + The largest page size that can be written atomically.
  43960. */
  43961. if( rc==SQLITE_OK ){
  43962. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  43963. if( !readOnly ){
  43964. setSectorSize(pPager);
  43965. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  43966. if( szPageDflt<pPager->sectorSize ){
  43967. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  43968. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  43969. }else{
  43970. szPageDflt = (u32)pPager->sectorSize;
  43971. }
  43972. }
  43973. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  43974. {
  43975. int ii;
  43976. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  43977. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  43978. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  43979. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  43980. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  43981. szPageDflt = ii;
  43982. }
  43983. }
  43984. }
  43985. #endif
  43986. }
  43987. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  43988. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  43989. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  43990. vfsFlags |= SQLITE_OPEN_READONLY;
  43991. goto act_like_temp_file;
  43992. }
  43993. }
  43994. }else{
  43995. /* If a temporary file is requested, it is not opened immediately.
  43996. ** In this case we accept the default page size and delay actually
  43997. ** opening the file until the first call to OsWrite().
  43998. **
  43999. ** This branch is also run for an in-memory database. An in-memory
  44000. ** database is the same as a temp-file that is never written out to
  44001. ** disk and uses an in-memory rollback journal.
  44002. **
  44003. ** This branch also runs for files marked as immutable.
  44004. */
  44005. act_like_temp_file:
  44006. tempFile = 1;
  44007. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  44008. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
  44009. pPager->noLock = 1; /* Do no locking */
  44010. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  44011. }
  44012. /* The following call to PagerSetPagesize() serves to set the value of
  44013. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  44014. */
  44015. if( rc==SQLITE_OK ){
  44016. assert( pPager->memDb==0 );
  44017. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  44018. testcase( rc!=SQLITE_OK );
  44019. }
  44020. /* Initialize the PCache object. */
  44021. if( rc==SQLITE_OK ){
  44022. assert( nExtra<1000 );
  44023. nExtra = ROUND8(nExtra);
  44024. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  44025. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  44026. }
  44027. /* If an error occurred above, free the Pager structure and close the file.
  44028. */
  44029. if( rc!=SQLITE_OK ){
  44030. sqlite3OsClose(pPager->fd);
  44031. sqlite3PageFree(pPager->pTmpSpace);
  44032. sqlite3_free(pPager);
  44033. return rc;
  44034. }
  44035. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  44036. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  44037. pPager->useJournal = (u8)useJournal;
  44038. /* pPager->stmtOpen = 0; */
  44039. /* pPager->stmtInUse = 0; */
  44040. /* pPager->nRef = 0; */
  44041. /* pPager->stmtSize = 0; */
  44042. /* pPager->stmtJSize = 0; */
  44043. /* pPager->nPage = 0; */
  44044. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  44045. /* pPager->state = PAGER_UNLOCK; */
  44046. /* pPager->errMask = 0; */
  44047. pPager->tempFile = (u8)tempFile;
  44048. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  44049. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  44050. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  44051. pPager->exclusiveMode = (u8)tempFile;
  44052. pPager->changeCountDone = pPager->tempFile;
  44053. pPager->memDb = (u8)memDb;
  44054. pPager->readOnly = (u8)readOnly;
  44055. assert( useJournal || pPager->tempFile );
  44056. pPager->noSync = pPager->tempFile;
  44057. if( pPager->noSync ){
  44058. assert( pPager->fullSync==0 );
  44059. assert( pPager->syncFlags==0 );
  44060. assert( pPager->walSyncFlags==0 );
  44061. assert( pPager->ckptSyncFlags==0 );
  44062. }else{
  44063. pPager->fullSync = 1;
  44064. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  44065. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  44066. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  44067. }
  44068. /* pPager->pFirst = 0; */
  44069. /* pPager->pFirstSynced = 0; */
  44070. /* pPager->pLast = 0; */
  44071. pPager->nExtra = (u16)nExtra;
  44072. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  44073. assert( isOpen(pPager->fd) || tempFile );
  44074. setSectorSize(pPager);
  44075. if( !useJournal ){
  44076. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  44077. }else if( memDb ){
  44078. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  44079. }
  44080. /* pPager->xBusyHandler = 0; */
  44081. /* pPager->pBusyHandlerArg = 0; */
  44082. pPager->xReiniter = xReinit;
  44083. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  44084. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  44085. *ppPager = pPager;
  44086. return SQLITE_OK;
  44087. }
  44088. /* Verify that the database file has not be deleted or renamed out from
  44089. ** under the pager. Return SQLITE_OK if the database is still were it ought
  44090. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  44091. ** code from sqlite3OsAccess()) if the database has gone missing.
  44092. */
  44093. static int databaseIsUnmoved(Pager *pPager){
  44094. int bHasMoved = 0;
  44095. int rc;
  44096. if( pPager->tempFile ) return SQLITE_OK;
  44097. if( pPager->dbSize==0 ) return SQLITE_OK;
  44098. assert( pPager->zFilename && pPager->zFilename[0] );
  44099. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  44100. if( rc==SQLITE_NOTFOUND ){
  44101. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  44102. ** has not been moved. That is the historical behavior of SQLite: prior to
  44103. ** version 3.8.3, it never checked */
  44104. rc = SQLITE_OK;
  44105. }else if( rc==SQLITE_OK && bHasMoved ){
  44106. rc = SQLITE_READONLY_DBMOVED;
  44107. }
  44108. return rc;
  44109. }
  44110. /*
  44111. ** This function is called after transitioning from PAGER_UNLOCK to
  44112. ** PAGER_SHARED state. It tests if there is a hot journal present in
  44113. ** the file-system for the given pager. A hot journal is one that
  44114. ** needs to be played back. According to this function, a hot-journal
  44115. ** file exists if the following criteria are met:
  44116. **
  44117. ** * The journal file exists in the file system, and
  44118. ** * No process holds a RESERVED or greater lock on the database file, and
  44119. ** * The database file itself is greater than 0 bytes in size, and
  44120. ** * The first byte of the journal file exists and is not 0x00.
  44121. **
  44122. ** If the current size of the database file is 0 but a journal file
  44123. ** exists, that is probably an old journal left over from a prior
  44124. ** database with the same name. In this case the journal file is
  44125. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  44126. ** is returned.
  44127. **
  44128. ** This routine does not check if there is a master journal filename
  44129. ** at the end of the file. If there is, and that master journal file
  44130. ** does not exist, then the journal file is not really hot. In this
  44131. ** case this routine will return a false-positive. The pager_playback()
  44132. ** routine will discover that the journal file is not really hot and
  44133. ** will not roll it back.
  44134. **
  44135. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  44136. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  44137. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  44138. ** to determine whether or not a hot-journal file exists, the IO error
  44139. ** code is returned and the value of *pExists is undefined.
  44140. */
  44141. static int hasHotJournal(Pager *pPager, int *pExists){
  44142. sqlite3_vfs * const pVfs = pPager->pVfs;
  44143. int rc = SQLITE_OK; /* Return code */
  44144. int exists = 1; /* True if a journal file is present */
  44145. int jrnlOpen = !!isOpen(pPager->jfd);
  44146. assert( pPager->useJournal );
  44147. assert( isOpen(pPager->fd) );
  44148. assert( pPager->eState==PAGER_OPEN );
  44149. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  44150. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  44151. ));
  44152. *pExists = 0;
  44153. if( !jrnlOpen ){
  44154. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  44155. }
  44156. if( rc==SQLITE_OK && exists ){
  44157. int locked = 0; /* True if some process holds a RESERVED lock */
  44158. /* Race condition here: Another process might have been holding the
  44159. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  44160. ** call above, but then delete the journal and drop the lock before
  44161. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  44162. ** is the case, this routine might think there is a hot journal when
  44163. ** in fact there is none. This results in a false-positive which will
  44164. ** be dealt with by the playback routine. Ticket #3883.
  44165. */
  44166. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  44167. if( rc==SQLITE_OK && !locked ){
  44168. Pgno nPage; /* Number of pages in database file */
  44169. rc = pagerPagecount(pPager, &nPage);
  44170. if( rc==SQLITE_OK ){
  44171. /* If the database is zero pages in size, that means that either (1) the
  44172. ** journal is a remnant from a prior database with the same name where
  44173. ** the database file but not the journal was deleted, or (2) the initial
  44174. ** transaction that populates a new database is being rolled back.
  44175. ** In either case, the journal file can be deleted. However, take care
  44176. ** not to delete the journal file if it is already open due to
  44177. ** journal_mode=PERSIST.
  44178. */
  44179. if( nPage==0 && !jrnlOpen ){
  44180. sqlite3BeginBenignMalloc();
  44181. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  44182. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  44183. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  44184. }
  44185. sqlite3EndBenignMalloc();
  44186. }else{
  44187. /* The journal file exists and no other connection has a reserved
  44188. ** or greater lock on the database file. Now check that there is
  44189. ** at least one non-zero bytes at the start of the journal file.
  44190. ** If there is, then we consider this journal to be hot. If not,
  44191. ** it can be ignored.
  44192. */
  44193. if( !jrnlOpen ){
  44194. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  44195. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  44196. }
  44197. if( rc==SQLITE_OK ){
  44198. u8 first = 0;
  44199. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  44200. if( rc==SQLITE_IOERR_SHORT_READ ){
  44201. rc = SQLITE_OK;
  44202. }
  44203. if( !jrnlOpen ){
  44204. sqlite3OsClose(pPager->jfd);
  44205. }
  44206. *pExists = (first!=0);
  44207. }else if( rc==SQLITE_CANTOPEN ){
  44208. /* If we cannot open the rollback journal file in order to see if
  44209. ** it has a zero header, that might be due to an I/O error, or
  44210. ** it might be due to the race condition described above and in
  44211. ** ticket #3883. Either way, assume that the journal is hot.
  44212. ** This might be a false positive. But if it is, then the
  44213. ** automatic journal playback and recovery mechanism will deal
  44214. ** with it under an EXCLUSIVE lock where we do not need to
  44215. ** worry so much with race conditions.
  44216. */
  44217. *pExists = 1;
  44218. rc = SQLITE_OK;
  44219. }
  44220. }
  44221. }
  44222. }
  44223. }
  44224. return rc;
  44225. }
  44226. /*
  44227. ** This function is called to obtain a shared lock on the database file.
  44228. ** It is illegal to call sqlite3PagerAcquire() until after this function
  44229. ** has been successfully called. If a shared-lock is already held when
  44230. ** this function is called, it is a no-op.
  44231. **
  44232. ** The following operations are also performed by this function.
  44233. **
  44234. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  44235. ** on the database file), then an attempt is made to obtain a
  44236. ** SHARED lock on the database file. Immediately after obtaining
  44237. ** the SHARED lock, the file-system is checked for a hot-journal,
  44238. ** which is played back if present. Following any hot-journal
  44239. ** rollback, the contents of the cache are validated by checking
  44240. ** the 'change-counter' field of the database file header and
  44241. ** discarded if they are found to be invalid.
  44242. **
  44243. ** 2) If the pager is running in exclusive-mode, and there are currently
  44244. ** no outstanding references to any pages, and is in the error state,
  44245. ** then an attempt is made to clear the error state by discarding
  44246. ** the contents of the page cache and rolling back any open journal
  44247. ** file.
  44248. **
  44249. ** If everything is successful, SQLITE_OK is returned. If an IO error
  44250. ** occurs while locking the database, checking for a hot-journal file or
  44251. ** rolling back a journal file, the IO error code is returned.
  44252. */
  44253. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  44254. int rc = SQLITE_OK; /* Return code */
  44255. /* This routine is only called from b-tree and only when there are no
  44256. ** outstanding pages. This implies that the pager state should either
  44257. ** be OPEN or READER. READER is only possible if the pager is or was in
  44258. ** exclusive access mode.
  44259. */
  44260. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  44261. assert( assert_pager_state(pPager) );
  44262. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  44263. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  44264. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  44265. int bHotJournal = 1; /* True if there exists a hot journal-file */
  44266. assert( !MEMDB );
  44267. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  44268. if( rc!=SQLITE_OK ){
  44269. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  44270. goto failed;
  44271. }
  44272. /* If a journal file exists, and there is no RESERVED lock on the
  44273. ** database file, then it either needs to be played back or deleted.
  44274. */
  44275. if( pPager->eLock<=SHARED_LOCK ){
  44276. rc = hasHotJournal(pPager, &bHotJournal);
  44277. }
  44278. if( rc!=SQLITE_OK ){
  44279. goto failed;
  44280. }
  44281. if( bHotJournal ){
  44282. if( pPager->readOnly ){
  44283. rc = SQLITE_READONLY_ROLLBACK;
  44284. goto failed;
  44285. }
  44286. /* Get an EXCLUSIVE lock on the database file. At this point it is
  44287. ** important that a RESERVED lock is not obtained on the way to the
  44288. ** EXCLUSIVE lock. If it were, another process might open the
  44289. ** database file, detect the RESERVED lock, and conclude that the
  44290. ** database is safe to read while this process is still rolling the
  44291. ** hot-journal back.
  44292. **
  44293. ** Because the intermediate RESERVED lock is not requested, any
  44294. ** other process attempting to access the database file will get to
  44295. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  44296. ** on the database file.
  44297. **
  44298. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  44299. ** downgraded to SHARED_LOCK before this function returns.
  44300. */
  44301. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44302. if( rc!=SQLITE_OK ){
  44303. goto failed;
  44304. }
  44305. /* If it is not already open and the file exists on disk, open the
  44306. ** journal for read/write access. Write access is required because
  44307. ** in exclusive-access mode the file descriptor will be kept open
  44308. ** and possibly used for a transaction later on. Also, write-access
  44309. ** is usually required to finalize the journal in journal_mode=persist
  44310. ** mode (and also for journal_mode=truncate on some systems).
  44311. **
  44312. ** If the journal does not exist, it usually means that some
  44313. ** other connection managed to get in and roll it back before
  44314. ** this connection obtained the exclusive lock above. Or, it
  44315. ** may mean that the pager was in the error-state when this
  44316. ** function was called and the journal file does not exist.
  44317. */
  44318. if( !isOpen(pPager->jfd) ){
  44319. sqlite3_vfs * const pVfs = pPager->pVfs;
  44320. int bExists; /* True if journal file exists */
  44321. rc = sqlite3OsAccess(
  44322. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  44323. if( rc==SQLITE_OK && bExists ){
  44324. int fout = 0;
  44325. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  44326. assert( !pPager->tempFile );
  44327. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  44328. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  44329. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  44330. rc = SQLITE_CANTOPEN_BKPT;
  44331. sqlite3OsClose(pPager->jfd);
  44332. }
  44333. }
  44334. }
  44335. /* Playback and delete the journal. Drop the database write
  44336. ** lock and reacquire the read lock. Purge the cache before
  44337. ** playing back the hot-journal so that we don't end up with
  44338. ** an inconsistent cache. Sync the hot journal before playing
  44339. ** it back since the process that crashed and left the hot journal
  44340. ** probably did not sync it and we are required to always sync
  44341. ** the journal before playing it back.
  44342. */
  44343. if( isOpen(pPager->jfd) ){
  44344. assert( rc==SQLITE_OK );
  44345. rc = pagerSyncHotJournal(pPager);
  44346. if( rc==SQLITE_OK ){
  44347. rc = pager_playback(pPager, 1);
  44348. pPager->eState = PAGER_OPEN;
  44349. }
  44350. }else if( !pPager->exclusiveMode ){
  44351. pagerUnlockDb(pPager, SHARED_LOCK);
  44352. }
  44353. if( rc!=SQLITE_OK ){
  44354. /* This branch is taken if an error occurs while trying to open
  44355. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  44356. ** pager_unlock() routine will be called before returning to unlock
  44357. ** the file. If the unlock attempt fails, then Pager.eLock must be
  44358. ** set to UNKNOWN_LOCK (see the comment above the #define for
  44359. ** UNKNOWN_LOCK above for an explanation).
  44360. **
  44361. ** In order to get pager_unlock() to do this, set Pager.eState to
  44362. ** PAGER_ERROR now. This is not actually counted as a transition
  44363. ** to ERROR state in the state diagram at the top of this file,
  44364. ** since we know that the same call to pager_unlock() will very
  44365. ** shortly transition the pager object to the OPEN state. Calling
  44366. ** assert_pager_state() would fail now, as it should not be possible
  44367. ** to be in ERROR state when there are zero outstanding page
  44368. ** references.
  44369. */
  44370. pager_error(pPager, rc);
  44371. goto failed;
  44372. }
  44373. assert( pPager->eState==PAGER_OPEN );
  44374. assert( (pPager->eLock==SHARED_LOCK)
  44375. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  44376. );
  44377. }
  44378. if( !pPager->tempFile && pPager->hasBeenUsed ){
  44379. /* The shared-lock has just been acquired then check to
  44380. ** see if the database has been modified. If the database has changed,
  44381. ** flush the cache. The pPager->hasBeenUsed flag prevents this from
  44382. ** occurring on the very first access to a file, in order to save a
  44383. ** single unnecessary sqlite3OsRead() call at the start-up.
  44384. **
  44385. ** Database changes are detected by looking at 15 bytes beginning
  44386. ** at offset 24 into the file. The first 4 of these 16 bytes are
  44387. ** a 32-bit counter that is incremented with each change. The
  44388. ** other bytes change randomly with each file change when
  44389. ** a codec is in use.
  44390. **
  44391. ** There is a vanishingly small chance that a change will not be
  44392. ** detected. The chance of an undetected change is so small that
  44393. ** it can be neglected.
  44394. */
  44395. Pgno nPage = 0;
  44396. char dbFileVers[sizeof(pPager->dbFileVers)];
  44397. rc = pagerPagecount(pPager, &nPage);
  44398. if( rc ) goto failed;
  44399. if( nPage>0 ){
  44400. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  44401. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  44402. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  44403. goto failed;
  44404. }
  44405. }else{
  44406. memset(dbFileVers, 0, sizeof(dbFileVers));
  44407. }
  44408. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  44409. pager_reset(pPager);
  44410. /* Unmap the database file. It is possible that external processes
  44411. ** may have truncated the database file and then extended it back
  44412. ** to its original size while this process was not holding a lock.
  44413. ** In this case there may exist a Pager.pMap mapping that appears
  44414. ** to be the right size but is not actually valid. Avoid this
  44415. ** possibility by unmapping the db here. */
  44416. if( USEFETCH(pPager) ){
  44417. sqlite3OsUnfetch(pPager->fd, 0, 0);
  44418. }
  44419. }
  44420. }
  44421. /* If there is a WAL file in the file-system, open this database in WAL
  44422. ** mode. Otherwise, the following function call is a no-op.
  44423. */
  44424. rc = pagerOpenWalIfPresent(pPager);
  44425. #ifndef SQLITE_OMIT_WAL
  44426. assert( pPager->pWal==0 || rc==SQLITE_OK );
  44427. #endif
  44428. }
  44429. if( pagerUseWal(pPager) ){
  44430. assert( rc==SQLITE_OK );
  44431. rc = pagerBeginReadTransaction(pPager);
  44432. }
  44433. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  44434. rc = pagerPagecount(pPager, &pPager->dbSize);
  44435. }
  44436. failed:
  44437. if( rc!=SQLITE_OK ){
  44438. assert( !MEMDB );
  44439. pager_unlock(pPager);
  44440. assert( pPager->eState==PAGER_OPEN );
  44441. }else{
  44442. pPager->eState = PAGER_READER;
  44443. }
  44444. return rc;
  44445. }
  44446. /*
  44447. ** If the reference count has reached zero, rollback any active
  44448. ** transaction and unlock the pager.
  44449. **
  44450. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  44451. ** the rollback journal, the unlock is not performed and there is
  44452. ** nothing to rollback, so this routine is a no-op.
  44453. */
  44454. static void pagerUnlockIfUnused(Pager *pPager){
  44455. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  44456. pagerUnlockAndRollback(pPager);
  44457. }
  44458. }
  44459. /*
  44460. ** Acquire a reference to page number pgno in pager pPager (a page
  44461. ** reference has type DbPage*). If the requested reference is
  44462. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  44463. **
  44464. ** If the requested page is already in the cache, it is returned.
  44465. ** Otherwise, a new page object is allocated and populated with data
  44466. ** read from the database file. In some cases, the pcache module may
  44467. ** choose not to allocate a new page object and may reuse an existing
  44468. ** object with no outstanding references.
  44469. **
  44470. ** The extra data appended to a page is always initialized to zeros the
  44471. ** first time a page is loaded into memory. If the page requested is
  44472. ** already in the cache when this function is called, then the extra
  44473. ** data is left as it was when the page object was last used.
  44474. **
  44475. ** If the database image is smaller than the requested page or if a
  44476. ** non-zero value is passed as the noContent parameter and the
  44477. ** requested page is not already stored in the cache, then no
  44478. ** actual disk read occurs. In this case the memory image of the
  44479. ** page is initialized to all zeros.
  44480. **
  44481. ** If noContent is true, it means that we do not care about the contents
  44482. ** of the page. This occurs in two scenarios:
  44483. **
  44484. ** a) When reading a free-list leaf page from the database, and
  44485. **
  44486. ** b) When a savepoint is being rolled back and we need to load
  44487. ** a new page into the cache to be filled with the data read
  44488. ** from the savepoint journal.
  44489. **
  44490. ** If noContent is true, then the data returned is zeroed instead of
  44491. ** being read from the database. Additionally, the bits corresponding
  44492. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  44493. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  44494. ** savepoints are set. This means if the page is made writable at any
  44495. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  44496. ** will not be journaled. This saves IO.
  44497. **
  44498. ** The acquisition might fail for several reasons. In all cases,
  44499. ** an appropriate error code is returned and *ppPage is set to NULL.
  44500. **
  44501. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  44502. ** to find a page in the in-memory cache first. If the page is not already
  44503. ** in memory, this routine goes to disk to read it in whereas Lookup()
  44504. ** just returns 0. This routine acquires a read-lock the first time it
  44505. ** has to go to disk, and could also playback an old journal if necessary.
  44506. ** Since Lookup() never goes to disk, it never has to deal with locks
  44507. ** or journal files.
  44508. */
  44509. SQLITE_PRIVATE int sqlite3PagerAcquire(
  44510. Pager *pPager, /* The pager open on the database file */
  44511. Pgno pgno, /* Page number to fetch */
  44512. DbPage **ppPage, /* Write a pointer to the page here */
  44513. int flags /* PAGER_GET_XXX flags */
  44514. ){
  44515. int rc = SQLITE_OK;
  44516. PgHdr *pPg = 0;
  44517. u32 iFrame = 0; /* Frame to read from WAL file */
  44518. const int noContent = (flags & PAGER_GET_NOCONTENT);
  44519. /* It is acceptable to use a read-only (mmap) page for any page except
  44520. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  44521. ** flag was specified by the caller. And so long as the db is not a
  44522. ** temporary or in-memory database. */
  44523. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  44524. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  44525. #ifdef SQLITE_HAS_CODEC
  44526. && pPager->xCodec==0
  44527. #endif
  44528. );
  44529. assert( pPager->eState>=PAGER_READER );
  44530. assert( assert_pager_state(pPager) );
  44531. assert( noContent==0 || bMmapOk==0 );
  44532. if( pgno==0 ){
  44533. return SQLITE_CORRUPT_BKPT;
  44534. }
  44535. pPager->hasBeenUsed = 1;
  44536. /* If the pager is in the error state, return an error immediately.
  44537. ** Otherwise, request the page from the PCache layer. */
  44538. if( pPager->errCode!=SQLITE_OK ){
  44539. rc = pPager->errCode;
  44540. }else{
  44541. if( bMmapOk && pagerUseWal(pPager) ){
  44542. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  44543. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  44544. }
  44545. if( bMmapOk && iFrame==0 ){
  44546. void *pData = 0;
  44547. rc = sqlite3OsFetch(pPager->fd,
  44548. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  44549. );
  44550. if( rc==SQLITE_OK && pData ){
  44551. if( pPager->eState>PAGER_READER ){
  44552. pPg = sqlite3PagerLookup(pPager, pgno);
  44553. }
  44554. if( pPg==0 ){
  44555. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  44556. }else{
  44557. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  44558. }
  44559. if( pPg ){
  44560. assert( rc==SQLITE_OK );
  44561. *ppPage = pPg;
  44562. return SQLITE_OK;
  44563. }
  44564. }
  44565. if( rc!=SQLITE_OK ){
  44566. goto pager_acquire_err;
  44567. }
  44568. }
  44569. {
  44570. sqlite3_pcache_page *pBase;
  44571. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  44572. if( pBase==0 ){
  44573. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  44574. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  44575. if( pBase==0 ){
  44576. pPg = *ppPage = 0;
  44577. rc = SQLITE_NOMEM;
  44578. goto pager_acquire_err;
  44579. }
  44580. }
  44581. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  44582. assert( pPg!=0 );
  44583. }
  44584. }
  44585. if( rc!=SQLITE_OK ){
  44586. /* Either the call to sqlite3PcacheFetch() returned an error or the
  44587. ** pager was already in the error-state when this function was called.
  44588. ** Set pPg to 0 and jump to the exception handler. */
  44589. pPg = 0;
  44590. goto pager_acquire_err;
  44591. }
  44592. assert( pPg==(*ppPage) );
  44593. assert( pPg->pgno==pgno );
  44594. assert( pPg->pPager==pPager || pPg->pPager==0 );
  44595. if( pPg->pPager && !noContent ){
  44596. /* In this case the pcache already contains an initialized copy of
  44597. ** the page. Return without further ado. */
  44598. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  44599. pPager->aStat[PAGER_STAT_HIT]++;
  44600. return SQLITE_OK;
  44601. }else{
  44602. /* The pager cache has created a new page. Its content needs to
  44603. ** be initialized. */
  44604. pPg->pPager = pPager;
  44605. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  44606. ** number greater than this, or the unused locking-page, is requested. */
  44607. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  44608. rc = SQLITE_CORRUPT_BKPT;
  44609. goto pager_acquire_err;
  44610. }
  44611. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  44612. if( pgno>pPager->mxPgno ){
  44613. rc = SQLITE_FULL;
  44614. goto pager_acquire_err;
  44615. }
  44616. if( noContent ){
  44617. /* Failure to set the bits in the InJournal bit-vectors is benign.
  44618. ** It merely means that we might do some extra work to journal a
  44619. ** page that does not need to be journaled. Nevertheless, be sure
  44620. ** to test the case where a malloc error occurs while trying to set
  44621. ** a bit in a bit vector.
  44622. */
  44623. sqlite3BeginBenignMalloc();
  44624. if( pgno<=pPager->dbOrigSize ){
  44625. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  44626. testcase( rc==SQLITE_NOMEM );
  44627. }
  44628. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  44629. testcase( rc==SQLITE_NOMEM );
  44630. sqlite3EndBenignMalloc();
  44631. }
  44632. memset(pPg->pData, 0, pPager->pageSize);
  44633. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  44634. }else{
  44635. if( pagerUseWal(pPager) && bMmapOk==0 ){
  44636. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  44637. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  44638. }
  44639. assert( pPg->pPager==pPager );
  44640. pPager->aStat[PAGER_STAT_MISS]++;
  44641. rc = readDbPage(pPg, iFrame);
  44642. if( rc!=SQLITE_OK ){
  44643. goto pager_acquire_err;
  44644. }
  44645. }
  44646. pager_set_pagehash(pPg);
  44647. }
  44648. return SQLITE_OK;
  44649. pager_acquire_err:
  44650. assert( rc!=SQLITE_OK );
  44651. if( pPg ){
  44652. sqlite3PcacheDrop(pPg);
  44653. }
  44654. pagerUnlockIfUnused(pPager);
  44655. *ppPage = 0;
  44656. return rc;
  44657. }
  44658. /*
  44659. ** Acquire a page if it is already in the in-memory cache. Do
  44660. ** not read the page from disk. Return a pointer to the page,
  44661. ** or 0 if the page is not in cache.
  44662. **
  44663. ** See also sqlite3PagerGet(). The difference between this routine
  44664. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  44665. ** in the page if the page is not already in cache. This routine
  44666. ** returns NULL if the page is not in cache or if a disk I/O error
  44667. ** has ever happened.
  44668. */
  44669. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  44670. sqlite3_pcache_page *pPage;
  44671. assert( pPager!=0 );
  44672. assert( pgno!=0 );
  44673. assert( pPager->pPCache!=0 );
  44674. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  44675. assert( pPage==0 || pPager->hasBeenUsed );
  44676. if( pPage==0 ) return 0;
  44677. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  44678. }
  44679. /*
  44680. ** Release a page reference.
  44681. **
  44682. ** If the number of references to the page drop to zero, then the
  44683. ** page is added to the LRU list. When all references to all pages
  44684. ** are released, a rollback occurs and the lock on the database is
  44685. ** removed.
  44686. */
  44687. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  44688. Pager *pPager;
  44689. assert( pPg!=0 );
  44690. pPager = pPg->pPager;
  44691. if( pPg->flags & PGHDR_MMAP ){
  44692. pagerReleaseMapPage(pPg);
  44693. }else{
  44694. sqlite3PcacheRelease(pPg);
  44695. }
  44696. pagerUnlockIfUnused(pPager);
  44697. }
  44698. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  44699. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  44700. }
  44701. /*
  44702. ** This function is called at the start of every write transaction.
  44703. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  44704. ** file when this routine is called.
  44705. **
  44706. ** Open the journal file for pager pPager and write a journal header
  44707. ** to the start of it. If there are active savepoints, open the sub-journal
  44708. ** as well. This function is only used when the journal file is being
  44709. ** opened to write a rollback log for a transaction. It is not used
  44710. ** when opening a hot journal file to roll it back.
  44711. **
  44712. ** If the journal file is already open (as it may be in exclusive mode),
  44713. ** then this function just writes a journal header to the start of the
  44714. ** already open file.
  44715. **
  44716. ** Whether or not the journal file is opened by this function, the
  44717. ** Pager.pInJournal bitvec structure is allocated.
  44718. **
  44719. ** Return SQLITE_OK if everything is successful. Otherwise, return
  44720. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  44721. ** an IO error code if opening or writing the journal file fails.
  44722. */
  44723. static int pager_open_journal(Pager *pPager){
  44724. int rc = SQLITE_OK; /* Return code */
  44725. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  44726. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44727. assert( assert_pager_state(pPager) );
  44728. assert( pPager->pInJournal==0 );
  44729. /* If already in the error state, this function is a no-op. But on
  44730. ** the other hand, this routine is never called if we are already in
  44731. ** an error state. */
  44732. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44733. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  44734. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  44735. if( pPager->pInJournal==0 ){
  44736. return SQLITE_NOMEM;
  44737. }
  44738. /* Open the journal file if it is not already open. */
  44739. if( !isOpen(pPager->jfd) ){
  44740. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  44741. sqlite3MemJournalOpen(pPager->jfd);
  44742. }else{
  44743. const int flags = /* VFS flags to open journal file */
  44744. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  44745. (pPager->tempFile ?
  44746. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  44747. (SQLITE_OPEN_MAIN_JOURNAL)
  44748. );
  44749. /* Verify that the database still has the same name as it did when
  44750. ** it was originally opened. */
  44751. rc = databaseIsUnmoved(pPager);
  44752. if( rc==SQLITE_OK ){
  44753. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44754. rc = sqlite3JournalOpen(
  44755. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  44756. );
  44757. #else
  44758. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  44759. #endif
  44760. }
  44761. }
  44762. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  44763. }
  44764. /* Write the first journal header to the journal file and open
  44765. ** the sub-journal if necessary.
  44766. */
  44767. if( rc==SQLITE_OK ){
  44768. /* TODO: Check if all of these are really required. */
  44769. pPager->nRec = 0;
  44770. pPager->journalOff = 0;
  44771. pPager->setMaster = 0;
  44772. pPager->journalHdr = 0;
  44773. rc = writeJournalHdr(pPager);
  44774. }
  44775. }
  44776. if( rc!=SQLITE_OK ){
  44777. sqlite3BitvecDestroy(pPager->pInJournal);
  44778. pPager->pInJournal = 0;
  44779. }else{
  44780. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44781. pPager->eState = PAGER_WRITER_CACHEMOD;
  44782. }
  44783. return rc;
  44784. }
  44785. /*
  44786. ** Begin a write-transaction on the specified pager object. If a
  44787. ** write-transaction has already been opened, this function is a no-op.
  44788. **
  44789. ** If the exFlag argument is false, then acquire at least a RESERVED
  44790. ** lock on the database file. If exFlag is true, then acquire at least
  44791. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  44792. ** functions need be called.
  44793. **
  44794. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  44795. ** within this transaction will be opened as an in-memory file. This
  44796. ** has no effect if the sub-journal is already opened (as it may be when
  44797. ** running in exclusive mode) or if the transaction does not require a
  44798. ** sub-journal. If the subjInMemory argument is zero, then any required
  44799. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  44800. ** or using a temporary file otherwise.
  44801. */
  44802. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  44803. int rc = SQLITE_OK;
  44804. if( pPager->errCode ) return pPager->errCode;
  44805. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  44806. pPager->subjInMemory = (u8)subjInMemory;
  44807. if( ALWAYS(pPager->eState==PAGER_READER) ){
  44808. assert( pPager->pInJournal==0 );
  44809. if( pagerUseWal(pPager) ){
  44810. /* If the pager is configured to use locking_mode=exclusive, and an
  44811. ** exclusive lock on the database is not already held, obtain it now.
  44812. */
  44813. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  44814. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44815. if( rc!=SQLITE_OK ){
  44816. return rc;
  44817. }
  44818. sqlite3WalExclusiveMode(pPager->pWal, 1);
  44819. }
  44820. /* Grab the write lock on the log file. If successful, upgrade to
  44821. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  44822. ** The busy-handler is not invoked if another connection already
  44823. ** holds the write-lock. If possible, the upper layer will call it.
  44824. */
  44825. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  44826. }else{
  44827. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  44828. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  44829. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  44830. ** lock, but not when obtaining the RESERVED lock.
  44831. */
  44832. rc = pagerLockDb(pPager, RESERVED_LOCK);
  44833. if( rc==SQLITE_OK && exFlag ){
  44834. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  44835. }
  44836. }
  44837. if( rc==SQLITE_OK ){
  44838. /* Change to WRITER_LOCKED state.
  44839. **
  44840. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  44841. ** when it has an open transaction, but never to DBMOD or FINISHED.
  44842. ** This is because in those states the code to roll back savepoint
  44843. ** transactions may copy data from the sub-journal into the database
  44844. ** file as well as into the page cache. Which would be incorrect in
  44845. ** WAL mode.
  44846. */
  44847. pPager->eState = PAGER_WRITER_LOCKED;
  44848. pPager->dbHintSize = pPager->dbSize;
  44849. pPager->dbFileSize = pPager->dbSize;
  44850. pPager->dbOrigSize = pPager->dbSize;
  44851. pPager->journalOff = 0;
  44852. }
  44853. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  44854. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  44855. assert( assert_pager_state(pPager) );
  44856. }
  44857. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  44858. return rc;
  44859. }
  44860. /*
  44861. ** Write page pPg onto the end of the rollback journal.
  44862. */
  44863. static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg){
  44864. Pager *pPager = pPg->pPager;
  44865. int rc;
  44866. u32 cksum;
  44867. char *pData2;
  44868. i64 iOff = pPager->journalOff;
  44869. /* We should never write to the journal file the page that
  44870. ** contains the database locks. The following assert verifies
  44871. ** that we do not. */
  44872. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  44873. assert( pPager->journalHdr<=pPager->journalOff );
  44874. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  44875. cksum = pager_cksum(pPager, (u8*)pData2);
  44876. /* Even if an IO or diskfull error occurs while journalling the
  44877. ** page in the block above, set the need-sync flag for the page.
  44878. ** Otherwise, when the transaction is rolled back, the logic in
  44879. ** playback_one_page() will think that the page needs to be restored
  44880. ** in the database file. And if an IO error occurs while doing so,
  44881. ** then corruption may follow.
  44882. */
  44883. pPg->flags |= PGHDR_NEED_SYNC;
  44884. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  44885. if( rc!=SQLITE_OK ) return rc;
  44886. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  44887. if( rc!=SQLITE_OK ) return rc;
  44888. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  44889. if( rc!=SQLITE_OK ) return rc;
  44890. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  44891. pPager->journalOff, pPager->pageSize));
  44892. PAGER_INCR(sqlite3_pager_writej_count);
  44893. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  44894. PAGERID(pPager), pPg->pgno,
  44895. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  44896. pPager->journalOff += 8 + pPager->pageSize;
  44897. pPager->nRec++;
  44898. assert( pPager->pInJournal!=0 );
  44899. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  44900. testcase( rc==SQLITE_NOMEM );
  44901. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  44902. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  44903. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  44904. return rc;
  44905. }
  44906. /*
  44907. ** Mark a single data page as writeable. The page is written into the
  44908. ** main journal or sub-journal as required. If the page is written into
  44909. ** one of the journals, the corresponding bit is set in the
  44910. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  44911. ** of any open savepoints as appropriate.
  44912. */
  44913. static int pager_write(PgHdr *pPg){
  44914. Pager *pPager = pPg->pPager;
  44915. int rc = SQLITE_OK;
  44916. /* This routine is not called unless a write-transaction has already
  44917. ** been started. The journal file may or may not be open at this point.
  44918. ** It is never called in the ERROR state.
  44919. */
  44920. assert( pPager->eState==PAGER_WRITER_LOCKED
  44921. || pPager->eState==PAGER_WRITER_CACHEMOD
  44922. || pPager->eState==PAGER_WRITER_DBMOD
  44923. );
  44924. assert( assert_pager_state(pPager) );
  44925. assert( pPager->errCode==0 );
  44926. assert( pPager->readOnly==0 );
  44927. CHECK_PAGE(pPg);
  44928. /* The journal file needs to be opened. Higher level routines have already
  44929. ** obtained the necessary locks to begin the write-transaction, but the
  44930. ** rollback journal might not yet be open. Open it now if this is the case.
  44931. **
  44932. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  44933. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  44934. ** an error might occur and the pager would end up in WRITER_LOCKED state
  44935. ** with pages marked as dirty in the cache.
  44936. */
  44937. if( pPager->eState==PAGER_WRITER_LOCKED ){
  44938. rc = pager_open_journal(pPager);
  44939. if( rc!=SQLITE_OK ) return rc;
  44940. }
  44941. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  44942. assert( assert_pager_state(pPager) );
  44943. /* Mark the page that is about to be modified as dirty. */
  44944. sqlite3PcacheMakeDirty(pPg);
  44945. /* If a rollback journal is in use, them make sure the page that is about
  44946. ** to change is in the rollback journal, or if the page is a new page off
  44947. ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
  44948. */
  44949. assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
  44950. if( pPager->pInJournal!=0
  44951. && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
  44952. ){
  44953. assert( pagerUseWal(pPager)==0 );
  44954. if( pPg->pgno<=pPager->dbOrigSize ){
  44955. rc = pagerAddPageToRollbackJournal(pPg);
  44956. if( rc!=SQLITE_OK ){
  44957. return rc;
  44958. }
  44959. }else{
  44960. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  44961. pPg->flags |= PGHDR_NEED_SYNC;
  44962. }
  44963. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  44964. PAGERID(pPager), pPg->pgno,
  44965. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  44966. }
  44967. }
  44968. /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
  44969. ** and before writing the page into the rollback journal. Wait until now,
  44970. ** after the page has been successfully journalled, before setting the
  44971. ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
  44972. */
  44973. pPg->flags |= PGHDR_WRITEABLE;
  44974. /* If the statement journal is open and the page is not in it,
  44975. ** then write the page into the statement journal.
  44976. */
  44977. if( pPager->nSavepoint>0 ){
  44978. rc = subjournalPageIfRequired(pPg);
  44979. }
  44980. /* Update the database size and return. */
  44981. if( pPager->dbSize<pPg->pgno ){
  44982. pPager->dbSize = pPg->pgno;
  44983. }
  44984. return rc;
  44985. }
  44986. /*
  44987. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  44988. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  44989. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  44990. ** a sector need to be journalled in case of a power loss in the middle of
  44991. ** a write.
  44992. **
  44993. ** Usually, the sector size is less than or equal to the page size, in which
  44994. ** case pages can be individually written. This routine only runs in the
  44995. ** exceptional case where the page size is smaller than the sector size.
  44996. */
  44997. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  44998. int rc = SQLITE_OK; /* Return code */
  44999. Pgno nPageCount; /* Total number of pages in database file */
  45000. Pgno pg1; /* First page of the sector pPg is located on. */
  45001. int nPage = 0; /* Number of pages starting at pg1 to journal */
  45002. int ii; /* Loop counter */
  45003. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  45004. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  45005. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  45006. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  45007. ** a journal header to be written between the pages journaled by
  45008. ** this function.
  45009. */
  45010. assert( !MEMDB );
  45011. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  45012. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  45013. /* This trick assumes that both the page-size and sector-size are
  45014. ** an integer power of 2. It sets variable pg1 to the identifier
  45015. ** of the first page of the sector pPg is located on.
  45016. */
  45017. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  45018. nPageCount = pPager->dbSize;
  45019. if( pPg->pgno>nPageCount ){
  45020. nPage = (pPg->pgno - pg1)+1;
  45021. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  45022. nPage = nPageCount+1-pg1;
  45023. }else{
  45024. nPage = nPagePerSector;
  45025. }
  45026. assert(nPage>0);
  45027. assert(pg1<=pPg->pgno);
  45028. assert((pg1+nPage)>pPg->pgno);
  45029. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  45030. Pgno pg = pg1+ii;
  45031. PgHdr *pPage;
  45032. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  45033. if( pg!=PAGER_MJ_PGNO(pPager) ){
  45034. rc = sqlite3PagerGet(pPager, pg, &pPage);
  45035. if( rc==SQLITE_OK ){
  45036. rc = pager_write(pPage);
  45037. if( pPage->flags&PGHDR_NEED_SYNC ){
  45038. needSync = 1;
  45039. }
  45040. sqlite3PagerUnrefNotNull(pPage);
  45041. }
  45042. }
  45043. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  45044. if( pPage->flags&PGHDR_NEED_SYNC ){
  45045. needSync = 1;
  45046. }
  45047. sqlite3PagerUnrefNotNull(pPage);
  45048. }
  45049. }
  45050. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  45051. ** starting at pg1, then it needs to be set for all of them. Because
  45052. ** writing to any of these nPage pages may damage the others, the
  45053. ** journal file must contain sync()ed copies of all of them
  45054. ** before any of them can be written out to the database file.
  45055. */
  45056. if( rc==SQLITE_OK && needSync ){
  45057. assert( !MEMDB );
  45058. for(ii=0; ii<nPage; ii++){
  45059. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  45060. if( pPage ){
  45061. pPage->flags |= PGHDR_NEED_SYNC;
  45062. sqlite3PagerUnrefNotNull(pPage);
  45063. }
  45064. }
  45065. }
  45066. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  45067. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  45068. return rc;
  45069. }
  45070. /*
  45071. ** Mark a data page as writeable. This routine must be called before
  45072. ** making changes to a page. The caller must check the return value
  45073. ** of this function and be careful not to change any page data unless
  45074. ** this routine returns SQLITE_OK.
  45075. **
  45076. ** The difference between this function and pager_write() is that this
  45077. ** function also deals with the special case where 2 or more pages
  45078. ** fit on a single disk sector. In this case all co-resident pages
  45079. ** must have been written to the journal file before returning.
  45080. **
  45081. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  45082. ** as appropriate. Otherwise, SQLITE_OK.
  45083. */
  45084. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  45085. Pager *pPager = pPg->pPager;
  45086. assert( (pPg->flags & PGHDR_MMAP)==0 );
  45087. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  45088. assert( pPager->eState!=PAGER_ERROR );
  45089. assert( assert_pager_state(pPager) );
  45090. if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
  45091. if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
  45092. return SQLITE_OK;
  45093. }else if( pPager->sectorSize > (u32)pPager->pageSize ){
  45094. return pagerWriteLargeSector(pPg);
  45095. }else{
  45096. return pager_write(pPg);
  45097. }
  45098. }
  45099. /*
  45100. ** Return TRUE if the page given in the argument was previously passed
  45101. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  45102. ** to change the content of the page.
  45103. */
  45104. #ifndef NDEBUG
  45105. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  45106. return pPg->flags & PGHDR_WRITEABLE;
  45107. }
  45108. #endif
  45109. /*
  45110. ** A call to this routine tells the pager that it is not necessary to
  45111. ** write the information on page pPg back to the disk, even though
  45112. ** that page might be marked as dirty. This happens, for example, when
  45113. ** the page has been added as a leaf of the freelist and so its
  45114. ** content no longer matters.
  45115. **
  45116. ** The overlying software layer calls this routine when all of the data
  45117. ** on the given page is unused. The pager marks the page as clean so
  45118. ** that it does not get written to disk.
  45119. **
  45120. ** Tests show that this optimization can quadruple the speed of large
  45121. ** DELETE operations.
  45122. */
  45123. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  45124. Pager *pPager = pPg->pPager;
  45125. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  45126. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  45127. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  45128. pPg->flags |= PGHDR_DONT_WRITE;
  45129. pPg->flags &= ~PGHDR_WRITEABLE;
  45130. pager_set_pagehash(pPg);
  45131. }
  45132. }
  45133. /*
  45134. ** This routine is called to increment the value of the database file
  45135. ** change-counter, stored as a 4-byte big-endian integer starting at
  45136. ** byte offset 24 of the pager file. The secondary change counter at
  45137. ** 92 is also updated, as is the SQLite version number at offset 96.
  45138. **
  45139. ** But this only happens if the pPager->changeCountDone flag is false.
  45140. ** To avoid excess churning of page 1, the update only happens once.
  45141. ** See also the pager_write_changecounter() routine that does an
  45142. ** unconditional update of the change counters.
  45143. **
  45144. ** If the isDirectMode flag is zero, then this is done by calling
  45145. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  45146. ** page data. In this case the file will be updated when the current
  45147. ** transaction is committed.
  45148. **
  45149. ** The isDirectMode flag may only be non-zero if the library was compiled
  45150. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  45151. ** if isDirect is non-zero, then the database file is updated directly
  45152. ** by writing an updated version of page 1 using a call to the
  45153. ** sqlite3OsWrite() function.
  45154. */
  45155. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  45156. int rc = SQLITE_OK;
  45157. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45158. || pPager->eState==PAGER_WRITER_DBMOD
  45159. );
  45160. assert( assert_pager_state(pPager) );
  45161. /* Declare and initialize constant integer 'isDirect'. If the
  45162. ** atomic-write optimization is enabled in this build, then isDirect
  45163. ** is initialized to the value passed as the isDirectMode parameter
  45164. ** to this function. Otherwise, it is always set to zero.
  45165. **
  45166. ** The idea is that if the atomic-write optimization is not
  45167. ** enabled at compile time, the compiler can omit the tests of
  45168. ** 'isDirect' below, as well as the block enclosed in the
  45169. ** "if( isDirect )" condition.
  45170. */
  45171. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  45172. # define DIRECT_MODE 0
  45173. assert( isDirectMode==0 );
  45174. UNUSED_PARAMETER(isDirectMode);
  45175. #else
  45176. # define DIRECT_MODE isDirectMode
  45177. #endif
  45178. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  45179. PgHdr *pPgHdr; /* Reference to page 1 */
  45180. assert( !pPager->tempFile && isOpen(pPager->fd) );
  45181. /* Open page 1 of the file for writing. */
  45182. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  45183. assert( pPgHdr==0 || rc==SQLITE_OK );
  45184. /* If page one was fetched successfully, and this function is not
  45185. ** operating in direct-mode, make page 1 writable. When not in
  45186. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  45187. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  45188. */
  45189. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  45190. rc = sqlite3PagerWrite(pPgHdr);
  45191. }
  45192. if( rc==SQLITE_OK ){
  45193. /* Actually do the update of the change counter */
  45194. pager_write_changecounter(pPgHdr);
  45195. /* If running in direct mode, write the contents of page 1 to the file. */
  45196. if( DIRECT_MODE ){
  45197. const void *zBuf;
  45198. assert( pPager->dbFileSize>0 );
  45199. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  45200. if( rc==SQLITE_OK ){
  45201. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  45202. pPager->aStat[PAGER_STAT_WRITE]++;
  45203. }
  45204. if( rc==SQLITE_OK ){
  45205. /* Update the pager's copy of the change-counter. Otherwise, the
  45206. ** next time a read transaction is opened the cache will be
  45207. ** flushed (as the change-counter values will not match). */
  45208. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  45209. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  45210. pPager->changeCountDone = 1;
  45211. }
  45212. }else{
  45213. pPager->changeCountDone = 1;
  45214. }
  45215. }
  45216. /* Release the page reference. */
  45217. sqlite3PagerUnref(pPgHdr);
  45218. }
  45219. return rc;
  45220. }
  45221. /*
  45222. ** Sync the database file to disk. This is a no-op for in-memory databases
  45223. ** or pages with the Pager.noSync flag set.
  45224. **
  45225. ** If successful, or if called on a pager for which it is a no-op, this
  45226. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  45227. */
  45228. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  45229. int rc = SQLITE_OK;
  45230. if( isOpen(pPager->fd) ){
  45231. void *pArg = (void*)zMaster;
  45232. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  45233. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  45234. }
  45235. if( rc==SQLITE_OK && !pPager->noSync ){
  45236. assert( !MEMDB );
  45237. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  45238. }
  45239. return rc;
  45240. }
  45241. /*
  45242. ** This function may only be called while a write-transaction is active in
  45243. ** rollback. If the connection is in WAL mode, this call is a no-op.
  45244. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  45245. ** the database file, an attempt is made to obtain one.
  45246. **
  45247. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  45248. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  45249. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  45250. ** returned.
  45251. */
  45252. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  45253. int rc = SQLITE_OK;
  45254. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45255. || pPager->eState==PAGER_WRITER_DBMOD
  45256. || pPager->eState==PAGER_WRITER_LOCKED
  45257. );
  45258. assert( assert_pager_state(pPager) );
  45259. if( 0==pagerUseWal(pPager) ){
  45260. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  45261. }
  45262. return rc;
  45263. }
  45264. /*
  45265. ** Sync the database file for the pager pPager. zMaster points to the name
  45266. ** of a master journal file that should be written into the individual
  45267. ** journal file. zMaster may be NULL, which is interpreted as no master
  45268. ** journal (a single database transaction).
  45269. **
  45270. ** This routine ensures that:
  45271. **
  45272. ** * The database file change-counter is updated,
  45273. ** * the journal is synced (unless the atomic-write optimization is used),
  45274. ** * all dirty pages are written to the database file,
  45275. ** * the database file is truncated (if required), and
  45276. ** * the database file synced.
  45277. **
  45278. ** The only thing that remains to commit the transaction is to finalize
  45279. ** (delete, truncate or zero the first part of) the journal file (or
  45280. ** delete the master journal file if specified).
  45281. **
  45282. ** Note that if zMaster==NULL, this does not overwrite a previous value
  45283. ** passed to an sqlite3PagerCommitPhaseOne() call.
  45284. **
  45285. ** If the final parameter - noSync - is true, then the database file itself
  45286. ** is not synced. The caller must call sqlite3PagerSync() directly to
  45287. ** sync the database file before calling CommitPhaseTwo() to delete the
  45288. ** journal file in this case.
  45289. */
  45290. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  45291. Pager *pPager, /* Pager object */
  45292. const char *zMaster, /* If not NULL, the master journal name */
  45293. int noSync /* True to omit the xSync on the db file */
  45294. ){
  45295. int rc = SQLITE_OK; /* Return code */
  45296. assert( pPager->eState==PAGER_WRITER_LOCKED
  45297. || pPager->eState==PAGER_WRITER_CACHEMOD
  45298. || pPager->eState==PAGER_WRITER_DBMOD
  45299. || pPager->eState==PAGER_ERROR
  45300. );
  45301. assert( assert_pager_state(pPager) );
  45302. /* If a prior error occurred, report that error again. */
  45303. if( NEVER(pPager->errCode) ) return pPager->errCode;
  45304. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  45305. pPager->zFilename, zMaster, pPager->dbSize));
  45306. /* If no database changes have been made, return early. */
  45307. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  45308. if( MEMDB ){
  45309. /* If this is an in-memory db, or no pages have been written to, or this
  45310. ** function has already been called, it is mostly a no-op. However, any
  45311. ** backup in progress needs to be restarted.
  45312. */
  45313. sqlite3BackupRestart(pPager->pBackup);
  45314. }else{
  45315. if( pagerUseWal(pPager) ){
  45316. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  45317. PgHdr *pPageOne = 0;
  45318. if( pList==0 ){
  45319. /* Must have at least one page for the WAL commit flag.
  45320. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  45321. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  45322. pList = pPageOne;
  45323. pList->pDirty = 0;
  45324. }
  45325. assert( rc==SQLITE_OK );
  45326. if( ALWAYS(pList) ){
  45327. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  45328. }
  45329. sqlite3PagerUnref(pPageOne);
  45330. if( rc==SQLITE_OK ){
  45331. sqlite3PcacheCleanAll(pPager->pPCache);
  45332. }
  45333. }else{
  45334. /* The following block updates the change-counter. Exactly how it
  45335. ** does this depends on whether or not the atomic-update optimization
  45336. ** was enabled at compile time, and if this transaction meets the
  45337. ** runtime criteria to use the operation:
  45338. **
  45339. ** * The file-system supports the atomic-write property for
  45340. ** blocks of size page-size, and
  45341. ** * This commit is not part of a multi-file transaction, and
  45342. ** * Exactly one page has been modified and store in the journal file.
  45343. **
  45344. ** If the optimization was not enabled at compile time, then the
  45345. ** pager_incr_changecounter() function is called to update the change
  45346. ** counter in 'indirect-mode'. If the optimization is compiled in but
  45347. ** is not applicable to this transaction, call sqlite3JournalCreate()
  45348. ** to make sure the journal file has actually been created, then call
  45349. ** pager_incr_changecounter() to update the change-counter in indirect
  45350. ** mode.
  45351. **
  45352. ** Otherwise, if the optimization is both enabled and applicable,
  45353. ** then call pager_incr_changecounter() to update the change-counter
  45354. ** in 'direct' mode. In this case the journal file will never be
  45355. ** created for this transaction.
  45356. */
  45357. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  45358. PgHdr *pPg;
  45359. assert( isOpen(pPager->jfd)
  45360. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  45361. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  45362. );
  45363. if( !zMaster && isOpen(pPager->jfd)
  45364. && pPager->journalOff==jrnlBufferSize(pPager)
  45365. && pPager->dbSize>=pPager->dbOrigSize
  45366. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  45367. ){
  45368. /* Update the db file change counter via the direct-write method. The
  45369. ** following call will modify the in-memory representation of page 1
  45370. ** to include the updated change counter and then write page 1
  45371. ** directly to the database file. Because of the atomic-write
  45372. ** property of the host file-system, this is safe.
  45373. */
  45374. rc = pager_incr_changecounter(pPager, 1);
  45375. }else{
  45376. rc = sqlite3JournalCreate(pPager->jfd);
  45377. if( rc==SQLITE_OK ){
  45378. rc = pager_incr_changecounter(pPager, 0);
  45379. }
  45380. }
  45381. #else
  45382. rc = pager_incr_changecounter(pPager, 0);
  45383. #endif
  45384. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  45385. /* Write the master journal name into the journal file. If a master
  45386. ** journal file name has already been written to the journal file,
  45387. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  45388. */
  45389. rc = writeMasterJournal(pPager, zMaster);
  45390. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  45391. /* Sync the journal file and write all dirty pages to the database.
  45392. ** If the atomic-update optimization is being used, this sync will not
  45393. ** create the journal file or perform any real IO.
  45394. **
  45395. ** Because the change-counter page was just modified, unless the
  45396. ** atomic-update optimization is used it is almost certain that the
  45397. ** journal requires a sync here. However, in locking_mode=exclusive
  45398. ** on a system under memory pressure it is just possible that this is
  45399. ** not the case. In this case it is likely enough that the redundant
  45400. ** xSync() call will be changed to a no-op by the OS anyhow.
  45401. */
  45402. rc = syncJournal(pPager, 0);
  45403. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  45404. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  45405. if( rc!=SQLITE_OK ){
  45406. assert( rc!=SQLITE_IOERR_BLOCKED );
  45407. goto commit_phase_one_exit;
  45408. }
  45409. sqlite3PcacheCleanAll(pPager->pPCache);
  45410. /* If the file on disk is smaller than the database image, use
  45411. ** pager_truncate to grow the file here. This can happen if the database
  45412. ** image was extended as part of the current transaction and then the
  45413. ** last page in the db image moved to the free-list. In this case the
  45414. ** last page is never written out to disk, leaving the database file
  45415. ** undersized. Fix this now if it is the case. */
  45416. if( pPager->dbSize>pPager->dbFileSize ){
  45417. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  45418. assert( pPager->eState==PAGER_WRITER_DBMOD );
  45419. rc = pager_truncate(pPager, nNew);
  45420. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  45421. }
  45422. /* Finally, sync the database file. */
  45423. if( !noSync ){
  45424. rc = sqlite3PagerSync(pPager, zMaster);
  45425. }
  45426. IOTRACE(("DBSYNC %p\n", pPager))
  45427. }
  45428. }
  45429. commit_phase_one_exit:
  45430. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  45431. pPager->eState = PAGER_WRITER_FINISHED;
  45432. }
  45433. return rc;
  45434. }
  45435. /*
  45436. ** When this function is called, the database file has been completely
  45437. ** updated to reflect the changes made by the current transaction and
  45438. ** synced to disk. The journal file still exists in the file-system
  45439. ** though, and if a failure occurs at this point it will eventually
  45440. ** be used as a hot-journal and the current transaction rolled back.
  45441. **
  45442. ** This function finalizes the journal file, either by deleting,
  45443. ** truncating or partially zeroing it, so that it cannot be used
  45444. ** for hot-journal rollback. Once this is done the transaction is
  45445. ** irrevocably committed.
  45446. **
  45447. ** If an error occurs, an IO error code is returned and the pager
  45448. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  45449. */
  45450. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  45451. int rc = SQLITE_OK; /* Return code */
  45452. /* This routine should not be called if a prior error has occurred.
  45453. ** But if (due to a coding error elsewhere in the system) it does get
  45454. ** called, just return the same error code without doing anything. */
  45455. if( NEVER(pPager->errCode) ) return pPager->errCode;
  45456. assert( pPager->eState==PAGER_WRITER_LOCKED
  45457. || pPager->eState==PAGER_WRITER_FINISHED
  45458. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  45459. );
  45460. assert( assert_pager_state(pPager) );
  45461. /* An optimization. If the database was not actually modified during
  45462. ** this transaction, the pager is running in exclusive-mode and is
  45463. ** using persistent journals, then this function is a no-op.
  45464. **
  45465. ** The start of the journal file currently contains a single journal
  45466. ** header with the nRec field set to 0. If such a journal is used as
  45467. ** a hot-journal during hot-journal rollback, 0 changes will be made
  45468. ** to the database file. So there is no need to zero the journal
  45469. ** header. Since the pager is in exclusive mode, there is no need
  45470. ** to drop any locks either.
  45471. */
  45472. if( pPager->eState==PAGER_WRITER_LOCKED
  45473. && pPager->exclusiveMode
  45474. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  45475. ){
  45476. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  45477. pPager->eState = PAGER_READER;
  45478. return SQLITE_OK;
  45479. }
  45480. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  45481. pPager->iDataVersion++;
  45482. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  45483. return pager_error(pPager, rc);
  45484. }
  45485. /*
  45486. ** If a write transaction is open, then all changes made within the
  45487. ** transaction are reverted and the current write-transaction is closed.
  45488. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  45489. ** state if an error occurs.
  45490. **
  45491. ** If the pager is already in PAGER_ERROR state when this function is called,
  45492. ** it returns Pager.errCode immediately. No work is performed in this case.
  45493. **
  45494. ** Otherwise, in rollback mode, this function performs two functions:
  45495. **
  45496. ** 1) It rolls back the journal file, restoring all database file and
  45497. ** in-memory cache pages to the state they were in when the transaction
  45498. ** was opened, and
  45499. **
  45500. ** 2) It finalizes the journal file, so that it is not used for hot
  45501. ** rollback at any point in the future.
  45502. **
  45503. ** Finalization of the journal file (task 2) is only performed if the
  45504. ** rollback is successful.
  45505. **
  45506. ** In WAL mode, all cache-entries containing data modified within the
  45507. ** current transaction are either expelled from the cache or reverted to
  45508. ** their pre-transaction state by re-reading data from the database or
  45509. ** WAL files. The WAL transaction is then closed.
  45510. */
  45511. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  45512. int rc = SQLITE_OK; /* Return code */
  45513. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  45514. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  45515. ** the pager is already in the ERROR state, the rollback is not
  45516. ** attempted here. Instead, the error code is returned to the caller.
  45517. */
  45518. assert( assert_pager_state(pPager) );
  45519. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  45520. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  45521. if( pagerUseWal(pPager) ){
  45522. int rc2;
  45523. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  45524. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  45525. if( rc==SQLITE_OK ) rc = rc2;
  45526. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  45527. int eState = pPager->eState;
  45528. rc = pager_end_transaction(pPager, 0, 0);
  45529. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  45530. /* This can happen using journal_mode=off. Move the pager to the error
  45531. ** state to indicate that the contents of the cache may not be trusted.
  45532. ** Any active readers will get SQLITE_ABORT.
  45533. */
  45534. pPager->errCode = SQLITE_ABORT;
  45535. pPager->eState = PAGER_ERROR;
  45536. return rc;
  45537. }
  45538. }else{
  45539. rc = pager_playback(pPager, 0);
  45540. }
  45541. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  45542. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  45543. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  45544. || rc==SQLITE_CANTOPEN
  45545. );
  45546. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  45547. ** cache. So call pager_error() on the way out to make any error persistent.
  45548. */
  45549. return pager_error(pPager, rc);
  45550. }
  45551. /*
  45552. ** Return TRUE if the database file is opened read-only. Return FALSE
  45553. ** if the database is (in theory) writable.
  45554. */
  45555. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  45556. return pPager->readOnly;
  45557. }
  45558. #ifdef SQLITE_DEBUG
  45559. /*
  45560. ** Return the number of references to the pager.
  45561. */
  45562. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  45563. return sqlite3PcacheRefCount(pPager->pPCache);
  45564. }
  45565. #endif
  45566. /*
  45567. ** Return the approximate number of bytes of memory currently
  45568. ** used by the pager and its associated cache.
  45569. */
  45570. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  45571. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  45572. + 5*sizeof(void*);
  45573. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  45574. + sqlite3MallocSize(pPager)
  45575. + pPager->pageSize;
  45576. }
  45577. /*
  45578. ** Return the number of references to the specified page.
  45579. */
  45580. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  45581. return sqlite3PcachePageRefcount(pPage);
  45582. }
  45583. #ifdef SQLITE_TEST
  45584. /*
  45585. ** This routine is used for testing and analysis only.
  45586. */
  45587. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  45588. static int a[11];
  45589. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  45590. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  45591. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  45592. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  45593. a[4] = pPager->eState;
  45594. a[5] = pPager->errCode;
  45595. a[6] = pPager->aStat[PAGER_STAT_HIT];
  45596. a[7] = pPager->aStat[PAGER_STAT_MISS];
  45597. a[8] = 0; /* Used to be pPager->nOvfl */
  45598. a[9] = pPager->nRead;
  45599. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  45600. return a;
  45601. }
  45602. #endif
  45603. /*
  45604. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  45605. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  45606. ** current cache hit or miss count, according to the value of eStat. If the
  45607. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  45608. ** returning.
  45609. */
  45610. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  45611. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  45612. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  45613. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  45614. );
  45615. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  45616. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  45617. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  45618. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  45619. if( reset ){
  45620. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  45621. }
  45622. }
  45623. /*
  45624. ** Return true if this is an in-memory pager.
  45625. */
  45626. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  45627. return MEMDB;
  45628. }
  45629. /*
  45630. ** Check that there are at least nSavepoint savepoints open. If there are
  45631. ** currently less than nSavepoints open, then open one or more savepoints
  45632. ** to make up the difference. If the number of savepoints is already
  45633. ** equal to nSavepoint, then this function is a no-op.
  45634. **
  45635. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  45636. ** occurs while opening the sub-journal file, then an IO error code is
  45637. ** returned. Otherwise, SQLITE_OK.
  45638. */
  45639. static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
  45640. int rc = SQLITE_OK; /* Return code */
  45641. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  45642. int ii; /* Iterator variable */
  45643. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  45644. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  45645. assert( assert_pager_state(pPager) );
  45646. assert( nSavepoint>nCurrent && pPager->useJournal );
  45647. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  45648. ** if the allocation fails. Otherwise, zero the new portion in case a
  45649. ** malloc failure occurs while populating it in the for(...) loop below.
  45650. */
  45651. aNew = (PagerSavepoint *)sqlite3Realloc(
  45652. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  45653. );
  45654. if( !aNew ){
  45655. return SQLITE_NOMEM;
  45656. }
  45657. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  45658. pPager->aSavepoint = aNew;
  45659. /* Populate the PagerSavepoint structures just allocated. */
  45660. for(ii=nCurrent; ii<nSavepoint; ii++){
  45661. aNew[ii].nOrig = pPager->dbSize;
  45662. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  45663. aNew[ii].iOffset = pPager->journalOff;
  45664. }else{
  45665. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  45666. }
  45667. aNew[ii].iSubRec = pPager->nSubRec;
  45668. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  45669. if( !aNew[ii].pInSavepoint ){
  45670. return SQLITE_NOMEM;
  45671. }
  45672. if( pagerUseWal(pPager) ){
  45673. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  45674. }
  45675. pPager->nSavepoint = ii+1;
  45676. }
  45677. assert( pPager->nSavepoint==nSavepoint );
  45678. assertTruncateConstraint(pPager);
  45679. return rc;
  45680. }
  45681. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  45682. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  45683. assert( assert_pager_state(pPager) );
  45684. if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
  45685. return pagerOpenSavepoint(pPager, nSavepoint);
  45686. }else{
  45687. return SQLITE_OK;
  45688. }
  45689. }
  45690. /*
  45691. ** This function is called to rollback or release (commit) a savepoint.
  45692. ** The savepoint to release or rollback need not be the most recently
  45693. ** created savepoint.
  45694. **
  45695. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  45696. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  45697. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  45698. ** that have occurred since the specified savepoint was created.
  45699. **
  45700. ** The savepoint to rollback or release is identified by parameter
  45701. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  45702. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  45703. ** on the most recently created savepoint. If iSavepoint is greater than
  45704. ** (Pager.nSavepoint-1), then this function is a no-op.
  45705. **
  45706. ** If a negative value is passed to this function, then the current
  45707. ** transaction is rolled back. This is different to calling
  45708. ** sqlite3PagerRollback() because this function does not terminate
  45709. ** the transaction or unlock the database, it just restores the
  45710. ** contents of the database to its original state.
  45711. **
  45712. ** In any case, all savepoints with an index greater than iSavepoint
  45713. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  45714. ** then savepoint iSavepoint is also destroyed.
  45715. **
  45716. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  45717. ** or an IO error code if an IO error occurs while rolling back a
  45718. ** savepoint. If no errors occur, SQLITE_OK is returned.
  45719. */
  45720. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  45721. int rc = pPager->errCode; /* Return code */
  45722. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  45723. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  45724. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  45725. int ii; /* Iterator variable */
  45726. int nNew; /* Number of remaining savepoints after this op. */
  45727. /* Figure out how many savepoints will still be active after this
  45728. ** operation. Store this value in nNew. Then free resources associated
  45729. ** with any savepoints that are destroyed by this operation.
  45730. */
  45731. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  45732. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  45733. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  45734. }
  45735. pPager->nSavepoint = nNew;
  45736. /* If this is a release of the outermost savepoint, truncate
  45737. ** the sub-journal to zero bytes in size. */
  45738. if( op==SAVEPOINT_RELEASE ){
  45739. if( nNew==0 && isOpen(pPager->sjfd) ){
  45740. /* Only truncate if it is an in-memory sub-journal. */
  45741. if( sqlite3IsMemJournal(pPager->sjfd) ){
  45742. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  45743. assert( rc==SQLITE_OK );
  45744. }
  45745. pPager->nSubRec = 0;
  45746. }
  45747. }
  45748. /* Else this is a rollback operation, playback the specified savepoint.
  45749. ** If this is a temp-file, it is possible that the journal file has
  45750. ** not yet been opened. In this case there have been no changes to
  45751. ** the database file, so the playback operation can be skipped.
  45752. */
  45753. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  45754. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  45755. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  45756. assert(rc!=SQLITE_DONE);
  45757. }
  45758. }
  45759. return rc;
  45760. }
  45761. /*
  45762. ** Return the full pathname of the database file.
  45763. **
  45764. ** Except, if the pager is in-memory only, then return an empty string if
  45765. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  45766. ** used to report the filename to the user, for compatibility with legacy
  45767. ** behavior. But when the Btree needs to know the filename for matching to
  45768. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  45769. ** participate in shared-cache.
  45770. */
  45771. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  45772. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  45773. }
  45774. /*
  45775. ** Return the VFS structure for the pager.
  45776. */
  45777. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  45778. return pPager->pVfs;
  45779. }
  45780. /*
  45781. ** Return the file handle for the database file associated
  45782. ** with the pager. This might return NULL if the file has
  45783. ** not yet been opened.
  45784. */
  45785. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  45786. return pPager->fd;
  45787. }
  45788. /*
  45789. ** Return the full pathname of the journal file.
  45790. */
  45791. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  45792. return pPager->zJournal;
  45793. }
  45794. /*
  45795. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  45796. ** if fsync()s are executed normally.
  45797. */
  45798. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  45799. return pPager->noSync;
  45800. }
  45801. #ifdef SQLITE_HAS_CODEC
  45802. /*
  45803. ** Set or retrieve the codec for this pager
  45804. */
  45805. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  45806. Pager *pPager,
  45807. void *(*xCodec)(void*,void*,Pgno,int),
  45808. void (*xCodecSizeChng)(void*,int,int),
  45809. void (*xCodecFree)(void*),
  45810. void *pCodec
  45811. ){
  45812. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  45813. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  45814. pPager->xCodecSizeChng = xCodecSizeChng;
  45815. pPager->xCodecFree = xCodecFree;
  45816. pPager->pCodec = pCodec;
  45817. pagerReportSize(pPager);
  45818. }
  45819. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  45820. return pPager->pCodec;
  45821. }
  45822. /*
  45823. ** This function is called by the wal module when writing page content
  45824. ** into the log file.
  45825. **
  45826. ** This function returns a pointer to a buffer containing the encrypted
  45827. ** page content. If a malloc fails, this function may return NULL.
  45828. */
  45829. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  45830. void *aData = 0;
  45831. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  45832. return aData;
  45833. }
  45834. /*
  45835. ** Return the current pager state
  45836. */
  45837. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  45838. return pPager->eState;
  45839. }
  45840. #endif /* SQLITE_HAS_CODEC */
  45841. #ifndef SQLITE_OMIT_AUTOVACUUM
  45842. /*
  45843. ** Move the page pPg to location pgno in the file.
  45844. **
  45845. ** There must be no references to the page previously located at
  45846. ** pgno (which we call pPgOld) though that page is allowed to be
  45847. ** in cache. If the page previously located at pgno is not already
  45848. ** in the rollback journal, it is not put there by by this routine.
  45849. **
  45850. ** References to the page pPg remain valid. Updating any
  45851. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  45852. ** allocated along with the page) is the responsibility of the caller.
  45853. **
  45854. ** A transaction must be active when this routine is called. It used to be
  45855. ** required that a statement transaction was not active, but this restriction
  45856. ** has been removed (CREATE INDEX needs to move a page when a statement
  45857. ** transaction is active).
  45858. **
  45859. ** If the fourth argument, isCommit, is non-zero, then this page is being
  45860. ** moved as part of a database reorganization just before the transaction
  45861. ** is being committed. In this case, it is guaranteed that the database page
  45862. ** pPg refers to will not be written to again within this transaction.
  45863. **
  45864. ** This function may return SQLITE_NOMEM or an IO error code if an error
  45865. ** occurs. Otherwise, it returns SQLITE_OK.
  45866. */
  45867. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  45868. PgHdr *pPgOld; /* The page being overwritten. */
  45869. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  45870. int rc; /* Return code */
  45871. Pgno origPgno; /* The original page number */
  45872. assert( pPg->nRef>0 );
  45873. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45874. || pPager->eState==PAGER_WRITER_DBMOD
  45875. );
  45876. assert( assert_pager_state(pPager) );
  45877. /* In order to be able to rollback, an in-memory database must journal
  45878. ** the page we are moving from.
  45879. */
  45880. if( MEMDB ){
  45881. rc = sqlite3PagerWrite(pPg);
  45882. if( rc ) return rc;
  45883. }
  45884. /* If the page being moved is dirty and has not been saved by the latest
  45885. ** savepoint, then save the current contents of the page into the
  45886. ** sub-journal now. This is required to handle the following scenario:
  45887. **
  45888. ** BEGIN;
  45889. ** <journal page X, then modify it in memory>
  45890. ** SAVEPOINT one;
  45891. ** <Move page X to location Y>
  45892. ** ROLLBACK TO one;
  45893. **
  45894. ** If page X were not written to the sub-journal here, it would not
  45895. ** be possible to restore its contents when the "ROLLBACK TO one"
  45896. ** statement were is processed.
  45897. **
  45898. ** subjournalPage() may need to allocate space to store pPg->pgno into
  45899. ** one or more savepoint bitvecs. This is the reason this function
  45900. ** may return SQLITE_NOMEM.
  45901. */
  45902. if( (pPg->flags & PGHDR_DIRTY)!=0
  45903. && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
  45904. ){
  45905. return rc;
  45906. }
  45907. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  45908. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  45909. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  45910. /* If the journal needs to be sync()ed before page pPg->pgno can
  45911. ** be written to, store pPg->pgno in local variable needSyncPgno.
  45912. **
  45913. ** If the isCommit flag is set, there is no need to remember that
  45914. ** the journal needs to be sync()ed before database page pPg->pgno
  45915. ** can be written to. The caller has already promised not to write to it.
  45916. */
  45917. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  45918. needSyncPgno = pPg->pgno;
  45919. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  45920. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  45921. assert( pPg->flags&PGHDR_DIRTY );
  45922. }
  45923. /* If the cache contains a page with page-number pgno, remove it
  45924. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  45925. ** page pgno before the 'move' operation, it needs to be retained
  45926. ** for the page moved there.
  45927. */
  45928. pPg->flags &= ~PGHDR_NEED_SYNC;
  45929. pPgOld = sqlite3PagerLookup(pPager, pgno);
  45930. assert( !pPgOld || pPgOld->nRef==1 );
  45931. if( pPgOld ){
  45932. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  45933. if( MEMDB ){
  45934. /* Do not discard pages from an in-memory database since we might
  45935. ** need to rollback later. Just move the page out of the way. */
  45936. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  45937. }else{
  45938. sqlite3PcacheDrop(pPgOld);
  45939. }
  45940. }
  45941. origPgno = pPg->pgno;
  45942. sqlite3PcacheMove(pPg, pgno);
  45943. sqlite3PcacheMakeDirty(pPg);
  45944. /* For an in-memory database, make sure the original page continues
  45945. ** to exist, in case the transaction needs to roll back. Use pPgOld
  45946. ** as the original page since it has already been allocated.
  45947. */
  45948. if( MEMDB ){
  45949. assert( pPgOld );
  45950. sqlite3PcacheMove(pPgOld, origPgno);
  45951. sqlite3PagerUnrefNotNull(pPgOld);
  45952. }
  45953. if( needSyncPgno ){
  45954. /* If needSyncPgno is non-zero, then the journal file needs to be
  45955. ** sync()ed before any data is written to database file page needSyncPgno.
  45956. ** Currently, no such page exists in the page-cache and the
  45957. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  45958. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  45959. ** flag.
  45960. **
  45961. ** If the attempt to load the page into the page-cache fails, (due
  45962. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  45963. ** array. Otherwise, if the page is loaded and written again in
  45964. ** this transaction, it may be written to the database file before
  45965. ** it is synced into the journal file. This way, it may end up in
  45966. ** the journal file twice, but that is not a problem.
  45967. */
  45968. PgHdr *pPgHdr;
  45969. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  45970. if( rc!=SQLITE_OK ){
  45971. if( needSyncPgno<=pPager->dbOrigSize ){
  45972. assert( pPager->pTmpSpace!=0 );
  45973. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  45974. }
  45975. return rc;
  45976. }
  45977. pPgHdr->flags |= PGHDR_NEED_SYNC;
  45978. sqlite3PcacheMakeDirty(pPgHdr);
  45979. sqlite3PagerUnrefNotNull(pPgHdr);
  45980. }
  45981. return SQLITE_OK;
  45982. }
  45983. #endif
  45984. /*
  45985. ** The page handle passed as the first argument refers to a dirty page
  45986. ** with a page number other than iNew. This function changes the page's
  45987. ** page number to iNew and sets the value of the PgHdr.flags field to
  45988. ** the value passed as the third parameter.
  45989. */
  45990. SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
  45991. assert( pPg->pgno!=iNew );
  45992. pPg->flags = flags;
  45993. sqlite3PcacheMove(pPg, iNew);
  45994. }
  45995. /*
  45996. ** Return a pointer to the data for the specified page.
  45997. */
  45998. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  45999. assert( pPg->nRef>0 || pPg->pPager->memDb );
  46000. return pPg->pData;
  46001. }
  46002. /*
  46003. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  46004. ** allocated along with the specified page.
  46005. */
  46006. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  46007. return pPg->pExtra;
  46008. }
  46009. /*
  46010. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  46011. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  46012. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  46013. ** the locking-mode is set to the value specified.
  46014. **
  46015. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  46016. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  46017. ** locking-mode.
  46018. */
  46019. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  46020. assert( eMode==PAGER_LOCKINGMODE_QUERY
  46021. || eMode==PAGER_LOCKINGMODE_NORMAL
  46022. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  46023. assert( PAGER_LOCKINGMODE_QUERY<0 );
  46024. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  46025. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  46026. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  46027. pPager->exclusiveMode = (u8)eMode;
  46028. }
  46029. return (int)pPager->exclusiveMode;
  46030. }
  46031. /*
  46032. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  46033. **
  46034. ** PAGER_JOURNALMODE_DELETE
  46035. ** PAGER_JOURNALMODE_TRUNCATE
  46036. ** PAGER_JOURNALMODE_PERSIST
  46037. ** PAGER_JOURNALMODE_OFF
  46038. ** PAGER_JOURNALMODE_MEMORY
  46039. ** PAGER_JOURNALMODE_WAL
  46040. **
  46041. ** The journalmode is set to the value specified if the change is allowed.
  46042. ** The change may be disallowed for the following reasons:
  46043. **
  46044. ** * An in-memory database can only have its journal_mode set to _OFF
  46045. ** or _MEMORY.
  46046. **
  46047. ** * Temporary databases cannot have _WAL journalmode.
  46048. **
  46049. ** The returned indicate the current (possibly updated) journal-mode.
  46050. */
  46051. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  46052. u8 eOld = pPager->journalMode; /* Prior journalmode */
  46053. #ifdef SQLITE_DEBUG
  46054. /* The print_pager_state() routine is intended to be used by the debugger
  46055. ** only. We invoke it once here to suppress a compiler warning. */
  46056. print_pager_state(pPager);
  46057. #endif
  46058. /* The eMode parameter is always valid */
  46059. assert( eMode==PAGER_JOURNALMODE_DELETE
  46060. || eMode==PAGER_JOURNALMODE_TRUNCATE
  46061. || eMode==PAGER_JOURNALMODE_PERSIST
  46062. || eMode==PAGER_JOURNALMODE_OFF
  46063. || eMode==PAGER_JOURNALMODE_WAL
  46064. || eMode==PAGER_JOURNALMODE_MEMORY );
  46065. /* This routine is only called from the OP_JournalMode opcode, and
  46066. ** the logic there will never allow a temporary file to be changed
  46067. ** to WAL mode.
  46068. */
  46069. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  46070. /* Do allow the journalmode of an in-memory database to be set to
  46071. ** anything other than MEMORY or OFF
  46072. */
  46073. if( MEMDB ){
  46074. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  46075. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  46076. eMode = eOld;
  46077. }
  46078. }
  46079. if( eMode!=eOld ){
  46080. /* Change the journal mode. */
  46081. assert( pPager->eState!=PAGER_ERROR );
  46082. pPager->journalMode = (u8)eMode;
  46083. /* When transistioning from TRUNCATE or PERSIST to any other journal
  46084. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  46085. ** delete the journal file.
  46086. */
  46087. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  46088. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  46089. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  46090. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  46091. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  46092. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  46093. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  46094. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  46095. /* In this case we would like to delete the journal file. If it is
  46096. ** not possible, then that is not a problem. Deleting the journal file
  46097. ** here is an optimization only.
  46098. **
  46099. ** Before deleting the journal file, obtain a RESERVED lock on the
  46100. ** database file. This ensures that the journal file is not deleted
  46101. ** while it is in use by some other client.
  46102. */
  46103. sqlite3OsClose(pPager->jfd);
  46104. if( pPager->eLock>=RESERVED_LOCK ){
  46105. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  46106. }else{
  46107. int rc = SQLITE_OK;
  46108. int state = pPager->eState;
  46109. assert( state==PAGER_OPEN || state==PAGER_READER );
  46110. if( state==PAGER_OPEN ){
  46111. rc = sqlite3PagerSharedLock(pPager);
  46112. }
  46113. if( pPager->eState==PAGER_READER ){
  46114. assert( rc==SQLITE_OK );
  46115. rc = pagerLockDb(pPager, RESERVED_LOCK);
  46116. }
  46117. if( rc==SQLITE_OK ){
  46118. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  46119. }
  46120. if( rc==SQLITE_OK && state==PAGER_READER ){
  46121. pagerUnlockDb(pPager, SHARED_LOCK);
  46122. }else if( state==PAGER_OPEN ){
  46123. pager_unlock(pPager);
  46124. }
  46125. assert( state==pPager->eState );
  46126. }
  46127. }else if( eMode==PAGER_JOURNALMODE_OFF ){
  46128. sqlite3OsClose(pPager->jfd);
  46129. }
  46130. }
  46131. /* Return the new journal mode */
  46132. return (int)pPager->journalMode;
  46133. }
  46134. /*
  46135. ** Return the current journal mode.
  46136. */
  46137. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  46138. return (int)pPager->journalMode;
  46139. }
  46140. /*
  46141. ** Return TRUE if the pager is in a state where it is OK to change the
  46142. ** journalmode. Journalmode changes can only happen when the database
  46143. ** is unmodified.
  46144. */
  46145. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  46146. assert( assert_pager_state(pPager) );
  46147. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  46148. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  46149. return 1;
  46150. }
  46151. /*
  46152. ** Get/set the size-limit used for persistent journal files.
  46153. **
  46154. ** Setting the size limit to -1 means no limit is enforced.
  46155. ** An attempt to set a limit smaller than -1 is a no-op.
  46156. */
  46157. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  46158. if( iLimit>=-1 ){
  46159. pPager->journalSizeLimit = iLimit;
  46160. sqlite3WalLimit(pPager->pWal, iLimit);
  46161. }
  46162. return pPager->journalSizeLimit;
  46163. }
  46164. /*
  46165. ** Return a pointer to the pPager->pBackup variable. The backup module
  46166. ** in backup.c maintains the content of this variable. This module
  46167. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  46168. ** sqlite3BackupUpdate() only.
  46169. */
  46170. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  46171. return &pPager->pBackup;
  46172. }
  46173. #ifndef SQLITE_OMIT_VACUUM
  46174. /*
  46175. ** Unless this is an in-memory or temporary database, clear the pager cache.
  46176. */
  46177. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  46178. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  46179. }
  46180. #endif
  46181. #ifndef SQLITE_OMIT_WAL
  46182. /*
  46183. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  46184. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  46185. ** or wal_blocking_checkpoint() API functions.
  46186. **
  46187. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  46188. */
  46189. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  46190. int rc = SQLITE_OK;
  46191. if( pPager->pWal ){
  46192. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  46193. (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
  46194. pPager->pBusyHandlerArg,
  46195. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  46196. pnLog, pnCkpt
  46197. );
  46198. }
  46199. return rc;
  46200. }
  46201. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  46202. return sqlite3WalCallback(pPager->pWal);
  46203. }
  46204. /*
  46205. ** Return true if the underlying VFS for the given pager supports the
  46206. ** primitives necessary for write-ahead logging.
  46207. */
  46208. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  46209. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  46210. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  46211. }
  46212. /*
  46213. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  46214. ** is obtained instead, immediately release it.
  46215. */
  46216. static int pagerExclusiveLock(Pager *pPager){
  46217. int rc; /* Return code */
  46218. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  46219. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  46220. if( rc!=SQLITE_OK ){
  46221. /* If the attempt to grab the exclusive lock failed, release the
  46222. ** pending lock that may have been obtained instead. */
  46223. pagerUnlockDb(pPager, SHARED_LOCK);
  46224. }
  46225. return rc;
  46226. }
  46227. /*
  46228. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  46229. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  46230. ** lock on the database file and use heap-memory to store the wal-index
  46231. ** in. Otherwise, use the normal shared-memory.
  46232. */
  46233. static int pagerOpenWal(Pager *pPager){
  46234. int rc = SQLITE_OK;
  46235. assert( pPager->pWal==0 && pPager->tempFile==0 );
  46236. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  46237. /* If the pager is already in exclusive-mode, the WAL module will use
  46238. ** heap-memory for the wal-index instead of the VFS shared-memory
  46239. ** implementation. Take the exclusive lock now, before opening the WAL
  46240. ** file, to make sure this is safe.
  46241. */
  46242. if( pPager->exclusiveMode ){
  46243. rc = pagerExclusiveLock(pPager);
  46244. }
  46245. /* Open the connection to the log file. If this operation fails,
  46246. ** (e.g. due to malloc() failure), return an error code.
  46247. */
  46248. if( rc==SQLITE_OK ){
  46249. rc = sqlite3WalOpen(pPager->pVfs,
  46250. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  46251. pPager->journalSizeLimit, &pPager->pWal
  46252. );
  46253. }
  46254. pagerFixMaplimit(pPager);
  46255. return rc;
  46256. }
  46257. /*
  46258. ** The caller must be holding a SHARED lock on the database file to call
  46259. ** this function.
  46260. **
  46261. ** If the pager passed as the first argument is open on a real database
  46262. ** file (not a temp file or an in-memory database), and the WAL file
  46263. ** is not already open, make an attempt to open it now. If successful,
  46264. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  46265. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  46266. ** not modified in either case.
  46267. **
  46268. ** If the pager is open on a temp-file (or in-memory database), or if
  46269. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  46270. ** without doing anything.
  46271. */
  46272. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  46273. Pager *pPager, /* Pager object */
  46274. int *pbOpen /* OUT: Set to true if call is a no-op */
  46275. ){
  46276. int rc = SQLITE_OK; /* Return code */
  46277. assert( assert_pager_state(pPager) );
  46278. assert( pPager->eState==PAGER_OPEN || pbOpen );
  46279. assert( pPager->eState==PAGER_READER || !pbOpen );
  46280. assert( pbOpen==0 || *pbOpen==0 );
  46281. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  46282. if( !pPager->tempFile && !pPager->pWal ){
  46283. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  46284. /* Close any rollback journal previously open */
  46285. sqlite3OsClose(pPager->jfd);
  46286. rc = pagerOpenWal(pPager);
  46287. if( rc==SQLITE_OK ){
  46288. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  46289. pPager->eState = PAGER_OPEN;
  46290. }
  46291. }else{
  46292. *pbOpen = 1;
  46293. }
  46294. return rc;
  46295. }
  46296. /*
  46297. ** This function is called to close the connection to the log file prior
  46298. ** to switching from WAL to rollback mode.
  46299. **
  46300. ** Before closing the log file, this function attempts to take an
  46301. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  46302. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  46303. ** If successful, the EXCLUSIVE lock is not released before returning.
  46304. */
  46305. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  46306. int rc = SQLITE_OK;
  46307. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  46308. /* If the log file is not already open, but does exist in the file-system,
  46309. ** it may need to be checkpointed before the connection can switch to
  46310. ** rollback mode. Open it now so this can happen.
  46311. */
  46312. if( !pPager->pWal ){
  46313. int logexists = 0;
  46314. rc = pagerLockDb(pPager, SHARED_LOCK);
  46315. if( rc==SQLITE_OK ){
  46316. rc = sqlite3OsAccess(
  46317. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  46318. );
  46319. }
  46320. if( rc==SQLITE_OK && logexists ){
  46321. rc = pagerOpenWal(pPager);
  46322. }
  46323. }
  46324. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  46325. ** the database file, the log and log-summary files will be deleted.
  46326. */
  46327. if( rc==SQLITE_OK && pPager->pWal ){
  46328. rc = pagerExclusiveLock(pPager);
  46329. if( rc==SQLITE_OK ){
  46330. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  46331. pPager->pageSize, (u8*)pPager->pTmpSpace);
  46332. pPager->pWal = 0;
  46333. pagerFixMaplimit(pPager);
  46334. }
  46335. }
  46336. return rc;
  46337. }
  46338. #endif /* !SQLITE_OMIT_WAL */
  46339. #ifdef SQLITE_ENABLE_ZIPVFS
  46340. /*
  46341. ** A read-lock must be held on the pager when this function is called. If
  46342. ** the pager is in WAL mode and the WAL file currently contains one or more
  46343. ** frames, return the size in bytes of the page images stored within the
  46344. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  46345. ** is empty, return 0.
  46346. */
  46347. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  46348. assert( pPager->eState>=PAGER_READER );
  46349. return sqlite3WalFramesize(pPager->pWal);
  46350. }
  46351. #endif
  46352. #endif /* SQLITE_OMIT_DISKIO */
  46353. /************** End of pager.c ***********************************************/
  46354. /************** Begin file wal.c *********************************************/
  46355. /*
  46356. ** 2010 February 1
  46357. **
  46358. ** The author disclaims copyright to this source code. In place of
  46359. ** a legal notice, here is a blessing:
  46360. **
  46361. ** May you do good and not evil.
  46362. ** May you find forgiveness for yourself and forgive others.
  46363. ** May you share freely, never taking more than you give.
  46364. **
  46365. *************************************************************************
  46366. **
  46367. ** This file contains the implementation of a write-ahead log (WAL) used in
  46368. ** "journal_mode=WAL" mode.
  46369. **
  46370. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  46371. **
  46372. ** A WAL file consists of a header followed by zero or more "frames".
  46373. ** Each frame records the revised content of a single page from the
  46374. ** database file. All changes to the database are recorded by writing
  46375. ** frames into the WAL. Transactions commit when a frame is written that
  46376. ** contains a commit marker. A single WAL can and usually does record
  46377. ** multiple transactions. Periodically, the content of the WAL is
  46378. ** transferred back into the database file in an operation called a
  46379. ** "checkpoint".
  46380. **
  46381. ** A single WAL file can be used multiple times. In other words, the
  46382. ** WAL can fill up with frames and then be checkpointed and then new
  46383. ** frames can overwrite the old ones. A WAL always grows from beginning
  46384. ** toward the end. Checksums and counters attached to each frame are
  46385. ** used to determine which frames within the WAL are valid and which
  46386. ** are leftovers from prior checkpoints.
  46387. **
  46388. ** The WAL header is 32 bytes in size and consists of the following eight
  46389. ** big-endian 32-bit unsigned integer values:
  46390. **
  46391. ** 0: Magic number. 0x377f0682 or 0x377f0683
  46392. ** 4: File format version. Currently 3007000
  46393. ** 8: Database page size. Example: 1024
  46394. ** 12: Checkpoint sequence number
  46395. ** 16: Salt-1, random integer incremented with each checkpoint
  46396. ** 20: Salt-2, a different random integer changing with each ckpt
  46397. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  46398. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  46399. **
  46400. ** Immediately following the wal-header are zero or more frames. Each
  46401. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  46402. ** of page data. The frame-header is six big-endian 32-bit unsigned
  46403. ** integer values, as follows:
  46404. **
  46405. ** 0: Page number.
  46406. ** 4: For commit records, the size of the database image in pages
  46407. ** after the commit. For all other records, zero.
  46408. ** 8: Salt-1 (copied from the header)
  46409. ** 12: Salt-2 (copied from the header)
  46410. ** 16: Checksum-1.
  46411. ** 20: Checksum-2.
  46412. **
  46413. ** A frame is considered valid if and only if the following conditions are
  46414. ** true:
  46415. **
  46416. ** (1) The salt-1 and salt-2 values in the frame-header match
  46417. ** salt values in the wal-header
  46418. **
  46419. ** (2) The checksum values in the final 8 bytes of the frame-header
  46420. ** exactly match the checksum computed consecutively on the
  46421. ** WAL header and the first 8 bytes and the content of all frames
  46422. ** up to and including the current frame.
  46423. **
  46424. ** The checksum is computed using 32-bit big-endian integers if the
  46425. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  46426. ** is computed using little-endian if the magic number is 0x377f0682.
  46427. ** The checksum values are always stored in the frame header in a
  46428. ** big-endian format regardless of which byte order is used to compute
  46429. ** the checksum. The checksum is computed by interpreting the input as
  46430. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  46431. ** algorithm used for the checksum is as follows:
  46432. **
  46433. ** for i from 0 to n-1 step 2:
  46434. ** s0 += x[i] + s1;
  46435. ** s1 += x[i+1] + s0;
  46436. ** endfor
  46437. **
  46438. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  46439. ** in reverse order (the largest fibonacci weight occurs on the first element
  46440. ** of the sequence being summed.) The s1 value spans all 32-bit
  46441. ** terms of the sequence whereas s0 omits the final term.
  46442. **
  46443. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  46444. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  46445. ** The VFS.xSync operations serve as write barriers - all writes launched
  46446. ** before the xSync must complete before any write that launches after the
  46447. ** xSync begins.
  46448. **
  46449. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  46450. ** value is randomized. This prevents old and new frames in the WAL from
  46451. ** being considered valid at the same time and being checkpointing together
  46452. ** following a crash.
  46453. **
  46454. ** READER ALGORITHM
  46455. **
  46456. ** To read a page from the database (call it page number P), a reader
  46457. ** first checks the WAL to see if it contains page P. If so, then the
  46458. ** last valid instance of page P that is a followed by a commit frame
  46459. ** or is a commit frame itself becomes the value read. If the WAL
  46460. ** contains no copies of page P that are valid and which are a commit
  46461. ** frame or are followed by a commit frame, then page P is read from
  46462. ** the database file.
  46463. **
  46464. ** To start a read transaction, the reader records the index of the last
  46465. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  46466. ** for all subsequent read operations. New transactions can be appended
  46467. ** to the WAL, but as long as the reader uses its original mxFrame value
  46468. ** and ignores the newly appended content, it will see a consistent snapshot
  46469. ** of the database from a single point in time. This technique allows
  46470. ** multiple concurrent readers to view different versions of the database
  46471. ** content simultaneously.
  46472. **
  46473. ** The reader algorithm in the previous paragraphs works correctly, but
  46474. ** because frames for page P can appear anywhere within the WAL, the
  46475. ** reader has to scan the entire WAL looking for page P frames. If the
  46476. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  46477. ** and read performance suffers. To overcome this problem, a separate
  46478. ** data structure called the wal-index is maintained to expedite the
  46479. ** search for frames of a particular page.
  46480. **
  46481. ** WAL-INDEX FORMAT
  46482. **
  46483. ** Conceptually, the wal-index is shared memory, though VFS implementations
  46484. ** might choose to implement the wal-index using a mmapped file. Because
  46485. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  46486. ** on a network filesystem. All users of the database must be able to
  46487. ** share memory.
  46488. **
  46489. ** The wal-index is transient. After a crash, the wal-index can (and should
  46490. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  46491. ** to either truncate or zero the header of the wal-index when the last
  46492. ** connection to it closes. Because the wal-index is transient, it can
  46493. ** use an architecture-specific format; it does not have to be cross-platform.
  46494. ** Hence, unlike the database and WAL file formats which store all values
  46495. ** as big endian, the wal-index can store multi-byte values in the native
  46496. ** byte order of the host computer.
  46497. **
  46498. ** The purpose of the wal-index is to answer this question quickly: Given
  46499. ** a page number P and a maximum frame index M, return the index of the
  46500. ** last frame in the wal before frame M for page P in the WAL, or return
  46501. ** NULL if there are no frames for page P in the WAL prior to M.
  46502. **
  46503. ** The wal-index consists of a header region, followed by an one or
  46504. ** more index blocks.
  46505. **
  46506. ** The wal-index header contains the total number of frames within the WAL
  46507. ** in the mxFrame field.
  46508. **
  46509. ** Each index block except for the first contains information on
  46510. ** HASHTABLE_NPAGE frames. The first index block contains information on
  46511. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  46512. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  46513. ** first index block are the same size as all other index blocks in the
  46514. ** wal-index.
  46515. **
  46516. ** Each index block contains two sections, a page-mapping that contains the
  46517. ** database page number associated with each wal frame, and a hash-table
  46518. ** that allows readers to query an index block for a specific page number.
  46519. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  46520. ** for the first index block) 32-bit page numbers. The first entry in the
  46521. ** first index-block contains the database page number corresponding to the
  46522. ** first frame in the WAL file. The first entry in the second index block
  46523. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  46524. ** the log, and so on.
  46525. **
  46526. ** The last index block in a wal-index usually contains less than the full
  46527. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  46528. ** depending on the contents of the WAL file. This does not change the
  46529. ** allocated size of the page-mapping array - the page-mapping array merely
  46530. ** contains unused entries.
  46531. **
  46532. ** Even without using the hash table, the last frame for page P
  46533. ** can be found by scanning the page-mapping sections of each index block
  46534. ** starting with the last index block and moving toward the first, and
  46535. ** within each index block, starting at the end and moving toward the
  46536. ** beginning. The first entry that equals P corresponds to the frame
  46537. ** holding the content for that page.
  46538. **
  46539. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  46540. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  46541. ** hash table for each page number in the mapping section, so the hash
  46542. ** table is never more than half full. The expected number of collisions
  46543. ** prior to finding a match is 1. Each entry of the hash table is an
  46544. ** 1-based index of an entry in the mapping section of the same
  46545. ** index block. Let K be the 1-based index of the largest entry in
  46546. ** the mapping section. (For index blocks other than the last, K will
  46547. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  46548. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  46549. ** contain a value of 0.
  46550. **
  46551. ** To look for page P in the hash table, first compute a hash iKey on
  46552. ** P as follows:
  46553. **
  46554. ** iKey = (P * 383) % HASHTABLE_NSLOT
  46555. **
  46556. ** Then start scanning entries of the hash table, starting with iKey
  46557. ** (wrapping around to the beginning when the end of the hash table is
  46558. ** reached) until an unused hash slot is found. Let the first unused slot
  46559. ** be at index iUnused. (iUnused might be less than iKey if there was
  46560. ** wrap-around.) Because the hash table is never more than half full,
  46561. ** the search is guaranteed to eventually hit an unused entry. Let
  46562. ** iMax be the value between iKey and iUnused, closest to iUnused,
  46563. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  46564. ** no hash slot such that aHash[i]==p) then page P is not in the
  46565. ** current index block. Otherwise the iMax-th mapping entry of the
  46566. ** current index block corresponds to the last entry that references
  46567. ** page P.
  46568. **
  46569. ** A hash search begins with the last index block and moves toward the
  46570. ** first index block, looking for entries corresponding to page P. On
  46571. ** average, only two or three slots in each index block need to be
  46572. ** examined in order to either find the last entry for page P, or to
  46573. ** establish that no such entry exists in the block. Each index block
  46574. ** holds over 4000 entries. So two or three index blocks are sufficient
  46575. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  46576. ** comparisons (on average) suffice to either locate a frame in the
  46577. ** WAL or to establish that the frame does not exist in the WAL. This
  46578. ** is much faster than scanning the entire 10MB WAL.
  46579. **
  46580. ** Note that entries are added in order of increasing K. Hence, one
  46581. ** reader might be using some value K0 and a second reader that started
  46582. ** at a later time (after additional transactions were added to the WAL
  46583. ** and to the wal-index) might be using a different value K1, where K1>K0.
  46584. ** Both readers can use the same hash table and mapping section to get
  46585. ** the correct result. There may be entries in the hash table with
  46586. ** K>K0 but to the first reader, those entries will appear to be unused
  46587. ** slots in the hash table and so the first reader will get an answer as
  46588. ** if no values greater than K0 had ever been inserted into the hash table
  46589. ** in the first place - which is what reader one wants. Meanwhile, the
  46590. ** second reader using K1 will see additional values that were inserted
  46591. ** later, which is exactly what reader two wants.
  46592. **
  46593. ** When a rollback occurs, the value of K is decreased. Hash table entries
  46594. ** that correspond to frames greater than the new K value are removed
  46595. ** from the hash table at this point.
  46596. */
  46597. #ifndef SQLITE_OMIT_WAL
  46598. /* #include "wal.h" */
  46599. /*
  46600. ** Trace output macros
  46601. */
  46602. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  46603. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  46604. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  46605. #else
  46606. # define WALTRACE(X)
  46607. #endif
  46608. /*
  46609. ** The maximum (and only) versions of the wal and wal-index formats
  46610. ** that may be interpreted by this version of SQLite.
  46611. **
  46612. ** If a client begins recovering a WAL file and finds that (a) the checksum
  46613. ** values in the wal-header are correct and (b) the version field is not
  46614. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  46615. **
  46616. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  46617. ** checksum test is successful) and finds that the version field is not
  46618. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  46619. ** returns SQLITE_CANTOPEN.
  46620. */
  46621. #define WAL_MAX_VERSION 3007000
  46622. #define WALINDEX_MAX_VERSION 3007000
  46623. /*
  46624. ** Indices of various locking bytes. WAL_NREADER is the number
  46625. ** of available reader locks and should be at least 3.
  46626. */
  46627. #define WAL_WRITE_LOCK 0
  46628. #define WAL_ALL_BUT_WRITE 1
  46629. #define WAL_CKPT_LOCK 1
  46630. #define WAL_RECOVER_LOCK 2
  46631. #define WAL_READ_LOCK(I) (3+(I))
  46632. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  46633. /* Object declarations */
  46634. typedef struct WalIndexHdr WalIndexHdr;
  46635. typedef struct WalIterator WalIterator;
  46636. typedef struct WalCkptInfo WalCkptInfo;
  46637. /*
  46638. ** The following object holds a copy of the wal-index header content.
  46639. **
  46640. ** The actual header in the wal-index consists of two copies of this
  46641. ** object.
  46642. **
  46643. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  46644. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  46645. ** added in 3.7.1 when support for 64K pages was added.
  46646. */
  46647. struct WalIndexHdr {
  46648. u32 iVersion; /* Wal-index version */
  46649. u32 unused; /* Unused (padding) field */
  46650. u32 iChange; /* Counter incremented each transaction */
  46651. u8 isInit; /* 1 when initialized */
  46652. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  46653. u16 szPage; /* Database page size in bytes. 1==64K */
  46654. u32 mxFrame; /* Index of last valid frame in the WAL */
  46655. u32 nPage; /* Size of database in pages */
  46656. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  46657. u32 aSalt[2]; /* Two salt values copied from WAL header */
  46658. u32 aCksum[2]; /* Checksum over all prior fields */
  46659. };
  46660. /*
  46661. ** A copy of the following object occurs in the wal-index immediately
  46662. ** following the second copy of the WalIndexHdr. This object stores
  46663. ** information used by checkpoint.
  46664. **
  46665. ** nBackfill is the number of frames in the WAL that have been written
  46666. ** back into the database. (We call the act of moving content from WAL to
  46667. ** database "backfilling".) The nBackfill number is never greater than
  46668. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  46669. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  46670. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  46671. ** mxFrame back to zero when the WAL is reset.
  46672. **
  46673. ** There is one entry in aReadMark[] for each reader lock. If a reader
  46674. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  46675. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  46676. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  46677. ** a special case; its value is never used and it exists as a place-holder
  46678. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  46679. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  46680. ** directly from the database.
  46681. **
  46682. ** The value of aReadMark[K] may only be changed by a thread that
  46683. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  46684. ** aReadMark[K] cannot changed while there is a reader is using that mark
  46685. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  46686. **
  46687. ** The checkpointer may only transfer frames from WAL to database where
  46688. ** the frame numbers are less than or equal to every aReadMark[] that is
  46689. ** in use (that is, every aReadMark[j] for which there is a corresponding
  46690. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  46691. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  46692. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  46693. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  46694. ** in the WAL has been backfilled into the database) then new readers
  46695. ** will choose aReadMark[0] which has value 0 and hence such reader will
  46696. ** get all their all content directly from the database file and ignore
  46697. ** the WAL.
  46698. **
  46699. ** Writers normally append new frames to the end of the WAL. However,
  46700. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  46701. ** written back into the database) and if no readers are using the WAL
  46702. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  46703. ** the writer will first "reset" the WAL back to the beginning and start
  46704. ** writing new content beginning at frame 1.
  46705. **
  46706. ** We assume that 32-bit loads are atomic and so no locks are needed in
  46707. ** order to read from any aReadMark[] entries.
  46708. */
  46709. struct WalCkptInfo {
  46710. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  46711. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  46712. };
  46713. #define READMARK_NOT_USED 0xffffffff
  46714. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  46715. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  46716. ** only support mandatory file-locks, we do not read or write data
  46717. ** from the region of the file on which locks are applied.
  46718. */
  46719. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  46720. #define WALINDEX_LOCK_RESERVED 16
  46721. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  46722. /* Size of header before each frame in wal */
  46723. #define WAL_FRAME_HDRSIZE 24
  46724. /* Size of write ahead log header, including checksum. */
  46725. /* #define WAL_HDRSIZE 24 */
  46726. #define WAL_HDRSIZE 32
  46727. /* WAL magic value. Either this value, or the same value with the least
  46728. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  46729. ** big-endian format in the first 4 bytes of a WAL file.
  46730. **
  46731. ** If the LSB is set, then the checksums for each frame within the WAL
  46732. ** file are calculated by treating all data as an array of 32-bit
  46733. ** big-endian words. Otherwise, they are calculated by interpreting
  46734. ** all data as 32-bit little-endian words.
  46735. */
  46736. #define WAL_MAGIC 0x377f0682
  46737. /*
  46738. ** Return the offset of frame iFrame in the write-ahead log file,
  46739. ** assuming a database page size of szPage bytes. The offset returned
  46740. ** is to the start of the write-ahead log frame-header.
  46741. */
  46742. #define walFrameOffset(iFrame, szPage) ( \
  46743. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  46744. )
  46745. /*
  46746. ** An open write-ahead log file is represented by an instance of the
  46747. ** following object.
  46748. */
  46749. struct Wal {
  46750. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  46751. sqlite3_file *pDbFd; /* File handle for the database file */
  46752. sqlite3_file *pWalFd; /* File handle for WAL file */
  46753. u32 iCallback; /* Value to pass to log callback (or 0) */
  46754. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  46755. int nWiData; /* Size of array apWiData */
  46756. int szFirstBlock; /* Size of first block written to WAL file */
  46757. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  46758. u32 szPage; /* Database page size */
  46759. i16 readLock; /* Which read lock is being held. -1 for none */
  46760. u8 syncFlags; /* Flags to use to sync header writes */
  46761. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  46762. u8 writeLock; /* True if in a write transaction */
  46763. u8 ckptLock; /* True if holding a checkpoint lock */
  46764. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  46765. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  46766. u8 syncHeader; /* Fsync the WAL header if true */
  46767. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  46768. WalIndexHdr hdr; /* Wal-index header for current transaction */
  46769. const char *zWalName; /* Name of WAL file */
  46770. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  46771. #ifdef SQLITE_DEBUG
  46772. u8 lockError; /* True if a locking error has occurred */
  46773. #endif
  46774. };
  46775. /*
  46776. ** Candidate values for Wal.exclusiveMode.
  46777. */
  46778. #define WAL_NORMAL_MODE 0
  46779. #define WAL_EXCLUSIVE_MODE 1
  46780. #define WAL_HEAPMEMORY_MODE 2
  46781. /*
  46782. ** Possible values for WAL.readOnly
  46783. */
  46784. #define WAL_RDWR 0 /* Normal read/write connection */
  46785. #define WAL_RDONLY 1 /* The WAL file is readonly */
  46786. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  46787. /*
  46788. ** Each page of the wal-index mapping contains a hash-table made up of
  46789. ** an array of HASHTABLE_NSLOT elements of the following type.
  46790. */
  46791. typedef u16 ht_slot;
  46792. /*
  46793. ** This structure is used to implement an iterator that loops through
  46794. ** all frames in the WAL in database page order. Where two or more frames
  46795. ** correspond to the same database page, the iterator visits only the
  46796. ** frame most recently written to the WAL (in other words, the frame with
  46797. ** the largest index).
  46798. **
  46799. ** The internals of this structure are only accessed by:
  46800. **
  46801. ** walIteratorInit() - Create a new iterator,
  46802. ** walIteratorNext() - Step an iterator,
  46803. ** walIteratorFree() - Free an iterator.
  46804. **
  46805. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  46806. */
  46807. struct WalIterator {
  46808. int iPrior; /* Last result returned from the iterator */
  46809. int nSegment; /* Number of entries in aSegment[] */
  46810. struct WalSegment {
  46811. int iNext; /* Next slot in aIndex[] not yet returned */
  46812. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  46813. u32 *aPgno; /* Array of page numbers. */
  46814. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  46815. int iZero; /* Frame number associated with aPgno[0] */
  46816. } aSegment[1]; /* One for every 32KB page in the wal-index */
  46817. };
  46818. /*
  46819. ** Define the parameters of the hash tables in the wal-index file. There
  46820. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  46821. ** wal-index.
  46822. **
  46823. ** Changing any of these constants will alter the wal-index format and
  46824. ** create incompatibilities.
  46825. */
  46826. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  46827. #define HASHTABLE_HASH_1 383 /* Should be prime */
  46828. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  46829. /*
  46830. ** The block of page numbers associated with the first hash-table in a
  46831. ** wal-index is smaller than usual. This is so that there is a complete
  46832. ** hash-table on each aligned 32KB page of the wal-index.
  46833. */
  46834. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  46835. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  46836. #define WALINDEX_PGSZ ( \
  46837. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  46838. )
  46839. /*
  46840. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  46841. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  46842. ** numbered from zero.
  46843. **
  46844. ** If this call is successful, *ppPage is set to point to the wal-index
  46845. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  46846. ** then an SQLite error code is returned and *ppPage is set to 0.
  46847. */
  46848. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  46849. int rc = SQLITE_OK;
  46850. /* Enlarge the pWal->apWiData[] array if required */
  46851. if( pWal->nWiData<=iPage ){
  46852. int nByte = sizeof(u32*)*(iPage+1);
  46853. volatile u32 **apNew;
  46854. apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
  46855. if( !apNew ){
  46856. *ppPage = 0;
  46857. return SQLITE_NOMEM;
  46858. }
  46859. memset((void*)&apNew[pWal->nWiData], 0,
  46860. sizeof(u32*)*(iPage+1-pWal->nWiData));
  46861. pWal->apWiData = apNew;
  46862. pWal->nWiData = iPage+1;
  46863. }
  46864. /* Request a pointer to the required page from the VFS */
  46865. if( pWal->apWiData[iPage]==0 ){
  46866. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46867. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  46868. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  46869. }else{
  46870. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  46871. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  46872. );
  46873. if( rc==SQLITE_READONLY ){
  46874. pWal->readOnly |= WAL_SHM_RDONLY;
  46875. rc = SQLITE_OK;
  46876. }
  46877. }
  46878. }
  46879. *ppPage = pWal->apWiData[iPage];
  46880. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  46881. return rc;
  46882. }
  46883. /*
  46884. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  46885. */
  46886. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  46887. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46888. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  46889. }
  46890. /*
  46891. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  46892. */
  46893. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  46894. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46895. return (volatile WalIndexHdr*)pWal->apWiData[0];
  46896. }
  46897. /*
  46898. ** The argument to this macro must be of type u32. On a little-endian
  46899. ** architecture, it returns the u32 value that results from interpreting
  46900. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  46901. ** returns the value that would be produced by interpreting the 4 bytes
  46902. ** of the input value as a little-endian integer.
  46903. */
  46904. #define BYTESWAP32(x) ( \
  46905. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  46906. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  46907. )
  46908. /*
  46909. ** Generate or extend an 8 byte checksum based on the data in
  46910. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  46911. ** initial values of 0 and 0 if aIn==NULL).
  46912. **
  46913. ** The checksum is written back into aOut[] before returning.
  46914. **
  46915. ** nByte must be a positive multiple of 8.
  46916. */
  46917. static void walChecksumBytes(
  46918. int nativeCksum, /* True for native byte-order, false for non-native */
  46919. u8 *a, /* Content to be checksummed */
  46920. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  46921. const u32 *aIn, /* Initial checksum value input */
  46922. u32 *aOut /* OUT: Final checksum value output */
  46923. ){
  46924. u32 s1, s2;
  46925. u32 *aData = (u32 *)a;
  46926. u32 *aEnd = (u32 *)&a[nByte];
  46927. if( aIn ){
  46928. s1 = aIn[0];
  46929. s2 = aIn[1];
  46930. }else{
  46931. s1 = s2 = 0;
  46932. }
  46933. assert( nByte>=8 );
  46934. assert( (nByte&0x00000007)==0 );
  46935. if( nativeCksum ){
  46936. do {
  46937. s1 += *aData++ + s2;
  46938. s2 += *aData++ + s1;
  46939. }while( aData<aEnd );
  46940. }else{
  46941. do {
  46942. s1 += BYTESWAP32(aData[0]) + s2;
  46943. s2 += BYTESWAP32(aData[1]) + s1;
  46944. aData += 2;
  46945. }while( aData<aEnd );
  46946. }
  46947. aOut[0] = s1;
  46948. aOut[1] = s2;
  46949. }
  46950. static void walShmBarrier(Wal *pWal){
  46951. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  46952. sqlite3OsShmBarrier(pWal->pDbFd);
  46953. }
  46954. }
  46955. /*
  46956. ** Write the header information in pWal->hdr into the wal-index.
  46957. **
  46958. ** The checksum on pWal->hdr is updated before it is written.
  46959. */
  46960. static void walIndexWriteHdr(Wal *pWal){
  46961. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  46962. const int nCksum = offsetof(WalIndexHdr, aCksum);
  46963. assert( pWal->writeLock );
  46964. pWal->hdr.isInit = 1;
  46965. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  46966. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  46967. memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  46968. walShmBarrier(pWal);
  46969. memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
  46970. }
  46971. /*
  46972. ** This function encodes a single frame header and writes it to a buffer
  46973. ** supplied by the caller. A frame-header is made up of a series of
  46974. ** 4-byte big-endian integers, as follows:
  46975. **
  46976. ** 0: Page number.
  46977. ** 4: For commit records, the size of the database image in pages
  46978. ** after the commit. For all other records, zero.
  46979. ** 8: Salt-1 (copied from the wal-header)
  46980. ** 12: Salt-2 (copied from the wal-header)
  46981. ** 16: Checksum-1.
  46982. ** 20: Checksum-2.
  46983. */
  46984. static void walEncodeFrame(
  46985. Wal *pWal, /* The write-ahead log */
  46986. u32 iPage, /* Database page number for frame */
  46987. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  46988. u8 *aData, /* Pointer to page data */
  46989. u8 *aFrame /* OUT: Write encoded frame here */
  46990. ){
  46991. int nativeCksum; /* True for native byte-order checksums */
  46992. u32 *aCksum = pWal->hdr.aFrameCksum;
  46993. assert( WAL_FRAME_HDRSIZE==24 );
  46994. sqlite3Put4byte(&aFrame[0], iPage);
  46995. sqlite3Put4byte(&aFrame[4], nTruncate);
  46996. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  46997. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  46998. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  46999. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  47000. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  47001. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  47002. }
  47003. /*
  47004. ** Check to see if the frame with header in aFrame[] and content
  47005. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  47006. ** *pnTruncate and return true. Return if the frame is not valid.
  47007. */
  47008. static int walDecodeFrame(
  47009. Wal *pWal, /* The write-ahead log */
  47010. u32 *piPage, /* OUT: Database page number for frame */
  47011. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  47012. u8 *aData, /* Pointer to page data (for checksum) */
  47013. u8 *aFrame /* Frame data */
  47014. ){
  47015. int nativeCksum; /* True for native byte-order checksums */
  47016. u32 *aCksum = pWal->hdr.aFrameCksum;
  47017. u32 pgno; /* Page number of the frame */
  47018. assert( WAL_FRAME_HDRSIZE==24 );
  47019. /* A frame is only valid if the salt values in the frame-header
  47020. ** match the salt values in the wal-header.
  47021. */
  47022. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  47023. return 0;
  47024. }
  47025. /* A frame is only valid if the page number is creater than zero.
  47026. */
  47027. pgno = sqlite3Get4byte(&aFrame[0]);
  47028. if( pgno==0 ){
  47029. return 0;
  47030. }
  47031. /* A frame is only valid if a checksum of the WAL header,
  47032. ** all prior frams, the first 16 bytes of this frame-header,
  47033. ** and the frame-data matches the checksum in the last 8
  47034. ** bytes of this frame-header.
  47035. */
  47036. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  47037. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  47038. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  47039. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  47040. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  47041. ){
  47042. /* Checksum failed. */
  47043. return 0;
  47044. }
  47045. /* If we reach this point, the frame is valid. Return the page number
  47046. ** and the new database size.
  47047. */
  47048. *piPage = pgno;
  47049. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  47050. return 1;
  47051. }
  47052. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  47053. /*
  47054. ** Names of locks. This routine is used to provide debugging output and is not
  47055. ** a part of an ordinary build.
  47056. */
  47057. static const char *walLockName(int lockIdx){
  47058. if( lockIdx==WAL_WRITE_LOCK ){
  47059. return "WRITE-LOCK";
  47060. }else if( lockIdx==WAL_CKPT_LOCK ){
  47061. return "CKPT-LOCK";
  47062. }else if( lockIdx==WAL_RECOVER_LOCK ){
  47063. return "RECOVER-LOCK";
  47064. }else{
  47065. static char zName[15];
  47066. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  47067. lockIdx-WAL_READ_LOCK(0));
  47068. return zName;
  47069. }
  47070. }
  47071. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  47072. /*
  47073. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  47074. ** A lock cannot be moved directly between shared and exclusive - it must go
  47075. ** through the unlocked state first.
  47076. **
  47077. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  47078. */
  47079. static int walLockShared(Wal *pWal, int lockIdx){
  47080. int rc;
  47081. if( pWal->exclusiveMode ) return SQLITE_OK;
  47082. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  47083. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  47084. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  47085. walLockName(lockIdx), rc ? "failed" : "ok"));
  47086. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  47087. return rc;
  47088. }
  47089. static void walUnlockShared(Wal *pWal, int lockIdx){
  47090. if( pWal->exclusiveMode ) return;
  47091. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  47092. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  47093. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  47094. }
  47095. static int walLockExclusive(Wal *pWal, int lockIdx, int n, int fBlock){
  47096. int rc;
  47097. if( pWal->exclusiveMode ) return SQLITE_OK;
  47098. if( fBlock ) sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_WAL_BLOCK, 0);
  47099. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  47100. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  47101. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  47102. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  47103. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  47104. return rc;
  47105. }
  47106. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  47107. if( pWal->exclusiveMode ) return;
  47108. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  47109. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  47110. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  47111. walLockName(lockIdx), n));
  47112. }
  47113. /*
  47114. ** Compute a hash on a page number. The resulting hash value must land
  47115. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  47116. ** the hash to the next value in the event of a collision.
  47117. */
  47118. static int walHash(u32 iPage){
  47119. assert( iPage>0 );
  47120. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  47121. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  47122. }
  47123. static int walNextHash(int iPriorHash){
  47124. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  47125. }
  47126. /*
  47127. ** Return pointers to the hash table and page number array stored on
  47128. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  47129. ** numbered starting from 0.
  47130. **
  47131. ** Set output variable *paHash to point to the start of the hash table
  47132. ** in the wal-index file. Set *piZero to one less than the frame
  47133. ** number of the first frame indexed by this hash table. If a
  47134. ** slot in the hash table is set to N, it refers to frame number
  47135. ** (*piZero+N) in the log.
  47136. **
  47137. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  47138. ** first frame indexed by the hash table, frame (*piZero+1).
  47139. */
  47140. static int walHashGet(
  47141. Wal *pWal, /* WAL handle */
  47142. int iHash, /* Find the iHash'th table */
  47143. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  47144. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  47145. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  47146. ){
  47147. int rc; /* Return code */
  47148. volatile u32 *aPgno;
  47149. rc = walIndexPage(pWal, iHash, &aPgno);
  47150. assert( rc==SQLITE_OK || iHash>0 );
  47151. if( rc==SQLITE_OK ){
  47152. u32 iZero;
  47153. volatile ht_slot *aHash;
  47154. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  47155. if( iHash==0 ){
  47156. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  47157. iZero = 0;
  47158. }else{
  47159. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  47160. }
  47161. *paPgno = &aPgno[-1];
  47162. *paHash = aHash;
  47163. *piZero = iZero;
  47164. }
  47165. return rc;
  47166. }
  47167. /*
  47168. ** Return the number of the wal-index page that contains the hash-table
  47169. ** and page-number array that contain entries corresponding to WAL frame
  47170. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  47171. ** are numbered starting from 0.
  47172. */
  47173. static int walFramePage(u32 iFrame){
  47174. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  47175. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  47176. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  47177. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  47178. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  47179. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  47180. );
  47181. return iHash;
  47182. }
  47183. /*
  47184. ** Return the page number associated with frame iFrame in this WAL.
  47185. */
  47186. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  47187. int iHash = walFramePage(iFrame);
  47188. if( iHash==0 ){
  47189. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  47190. }
  47191. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  47192. }
  47193. /*
  47194. ** Remove entries from the hash table that point to WAL slots greater
  47195. ** than pWal->hdr.mxFrame.
  47196. **
  47197. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  47198. ** to a rollback or savepoint.
  47199. **
  47200. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  47201. ** updated. Any later hash tables will be automatically cleared when
  47202. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  47203. ** actually needed.
  47204. */
  47205. static void walCleanupHash(Wal *pWal){
  47206. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  47207. volatile u32 *aPgno = 0; /* Page number array for hash table */
  47208. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  47209. int iLimit = 0; /* Zero values greater than this */
  47210. int nByte; /* Number of bytes to zero in aPgno[] */
  47211. int i; /* Used to iterate through aHash[] */
  47212. assert( pWal->writeLock );
  47213. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  47214. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  47215. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  47216. if( pWal->hdr.mxFrame==0 ) return;
  47217. /* Obtain pointers to the hash-table and page-number array containing
  47218. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  47219. ** that the page said hash-table and array reside on is already mapped.
  47220. */
  47221. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  47222. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  47223. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  47224. /* Zero all hash-table entries that correspond to frame numbers greater
  47225. ** than pWal->hdr.mxFrame.
  47226. */
  47227. iLimit = pWal->hdr.mxFrame - iZero;
  47228. assert( iLimit>0 );
  47229. for(i=0; i<HASHTABLE_NSLOT; i++){
  47230. if( aHash[i]>iLimit ){
  47231. aHash[i] = 0;
  47232. }
  47233. }
  47234. /* Zero the entries in the aPgno array that correspond to frames with
  47235. ** frame numbers greater than pWal->hdr.mxFrame.
  47236. */
  47237. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  47238. memset((void *)&aPgno[iLimit+1], 0, nByte);
  47239. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47240. /* Verify that the every entry in the mapping region is still reachable
  47241. ** via the hash table even after the cleanup.
  47242. */
  47243. if( iLimit ){
  47244. int j; /* Loop counter */
  47245. int iKey; /* Hash key */
  47246. for(j=1; j<=iLimit; j++){
  47247. for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
  47248. if( aHash[iKey]==j ) break;
  47249. }
  47250. assert( aHash[iKey]==j );
  47251. }
  47252. }
  47253. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  47254. }
  47255. /*
  47256. ** Set an entry in the wal-index that will map database page number
  47257. ** pPage into WAL frame iFrame.
  47258. */
  47259. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  47260. int rc; /* Return code */
  47261. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  47262. volatile u32 *aPgno = 0; /* Page number array */
  47263. volatile ht_slot *aHash = 0; /* Hash table */
  47264. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  47265. /* Assuming the wal-index file was successfully mapped, populate the
  47266. ** page number array and hash table entry.
  47267. */
  47268. if( rc==SQLITE_OK ){
  47269. int iKey; /* Hash table key */
  47270. int idx; /* Value to write to hash-table slot */
  47271. int nCollide; /* Number of hash collisions */
  47272. idx = iFrame - iZero;
  47273. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  47274. /* If this is the first entry to be added to this hash-table, zero the
  47275. ** entire hash table and aPgno[] array before proceeding.
  47276. */
  47277. if( idx==1 ){
  47278. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  47279. memset((void*)&aPgno[1], 0, nByte);
  47280. }
  47281. /* If the entry in aPgno[] is already set, then the previous writer
  47282. ** must have exited unexpectedly in the middle of a transaction (after
  47283. ** writing one or more dirty pages to the WAL to free up memory).
  47284. ** Remove the remnants of that writers uncommitted transaction from
  47285. ** the hash-table before writing any new entries.
  47286. */
  47287. if( aPgno[idx] ){
  47288. walCleanupHash(pWal);
  47289. assert( !aPgno[idx] );
  47290. }
  47291. /* Write the aPgno[] array entry and the hash-table slot. */
  47292. nCollide = idx;
  47293. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  47294. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  47295. }
  47296. aPgno[idx] = iPage;
  47297. aHash[iKey] = (ht_slot)idx;
  47298. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47299. /* Verify that the number of entries in the hash table exactly equals
  47300. ** the number of entries in the mapping region.
  47301. */
  47302. {
  47303. int i; /* Loop counter */
  47304. int nEntry = 0; /* Number of entries in the hash table */
  47305. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  47306. assert( nEntry==idx );
  47307. }
  47308. /* Verify that the every entry in the mapping region is reachable
  47309. ** via the hash table. This turns out to be a really, really expensive
  47310. ** thing to check, so only do this occasionally - not on every
  47311. ** iteration.
  47312. */
  47313. if( (idx&0x3ff)==0 ){
  47314. int i; /* Loop counter */
  47315. for(i=1; i<=idx; i++){
  47316. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  47317. if( aHash[iKey]==i ) break;
  47318. }
  47319. assert( aHash[iKey]==i );
  47320. }
  47321. }
  47322. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  47323. }
  47324. return rc;
  47325. }
  47326. /*
  47327. ** Recover the wal-index by reading the write-ahead log file.
  47328. **
  47329. ** This routine first tries to establish an exclusive lock on the
  47330. ** wal-index to prevent other threads/processes from doing anything
  47331. ** with the WAL or wal-index while recovery is running. The
  47332. ** WAL_RECOVER_LOCK is also held so that other threads will know
  47333. ** that this thread is running recovery. If unable to establish
  47334. ** the necessary locks, this routine returns SQLITE_BUSY.
  47335. */
  47336. static int walIndexRecover(Wal *pWal){
  47337. int rc; /* Return Code */
  47338. i64 nSize; /* Size of log file */
  47339. u32 aFrameCksum[2] = {0, 0};
  47340. int iLock; /* Lock offset to lock for checkpoint */
  47341. int nLock; /* Number of locks to hold */
  47342. /* Obtain an exclusive lock on all byte in the locking range not already
  47343. ** locked by the caller. The caller is guaranteed to have locked the
  47344. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  47345. ** If successful, the same bytes that are locked here are unlocked before
  47346. ** this function returns.
  47347. */
  47348. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  47349. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  47350. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  47351. assert( pWal->writeLock );
  47352. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  47353. nLock = SQLITE_SHM_NLOCK - iLock;
  47354. rc = walLockExclusive(pWal, iLock, nLock, 0);
  47355. if( rc ){
  47356. return rc;
  47357. }
  47358. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  47359. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  47360. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  47361. if( rc!=SQLITE_OK ){
  47362. goto recovery_error;
  47363. }
  47364. if( nSize>WAL_HDRSIZE ){
  47365. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  47366. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  47367. int szFrame; /* Number of bytes in buffer aFrame[] */
  47368. u8 *aData; /* Pointer to data part of aFrame buffer */
  47369. int iFrame; /* Index of last frame read */
  47370. i64 iOffset; /* Next offset to read from log file */
  47371. int szPage; /* Page size according to the log */
  47372. u32 magic; /* Magic value read from WAL header */
  47373. u32 version; /* Magic value read from WAL header */
  47374. int isValid; /* True if this frame is valid */
  47375. /* Read in the WAL header. */
  47376. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  47377. if( rc!=SQLITE_OK ){
  47378. goto recovery_error;
  47379. }
  47380. /* If the database page size is not a power of two, or is greater than
  47381. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  47382. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  47383. ** WAL file.
  47384. */
  47385. magic = sqlite3Get4byte(&aBuf[0]);
  47386. szPage = sqlite3Get4byte(&aBuf[8]);
  47387. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  47388. || szPage&(szPage-1)
  47389. || szPage>SQLITE_MAX_PAGE_SIZE
  47390. || szPage<512
  47391. ){
  47392. goto finished;
  47393. }
  47394. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  47395. pWal->szPage = szPage;
  47396. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  47397. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  47398. /* Verify that the WAL header checksum is correct */
  47399. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  47400. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  47401. );
  47402. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  47403. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  47404. ){
  47405. goto finished;
  47406. }
  47407. /* Verify that the version number on the WAL format is one that
  47408. ** are able to understand */
  47409. version = sqlite3Get4byte(&aBuf[4]);
  47410. if( version!=WAL_MAX_VERSION ){
  47411. rc = SQLITE_CANTOPEN_BKPT;
  47412. goto finished;
  47413. }
  47414. /* Malloc a buffer to read frames into. */
  47415. szFrame = szPage + WAL_FRAME_HDRSIZE;
  47416. aFrame = (u8 *)sqlite3_malloc64(szFrame);
  47417. if( !aFrame ){
  47418. rc = SQLITE_NOMEM;
  47419. goto recovery_error;
  47420. }
  47421. aData = &aFrame[WAL_FRAME_HDRSIZE];
  47422. /* Read all frames from the log file. */
  47423. iFrame = 0;
  47424. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  47425. u32 pgno; /* Database page number for frame */
  47426. u32 nTruncate; /* dbsize field from frame header */
  47427. /* Read and decode the next log frame. */
  47428. iFrame++;
  47429. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  47430. if( rc!=SQLITE_OK ) break;
  47431. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  47432. if( !isValid ) break;
  47433. rc = walIndexAppend(pWal, iFrame, pgno);
  47434. if( rc!=SQLITE_OK ) break;
  47435. /* If nTruncate is non-zero, this is a commit record. */
  47436. if( nTruncate ){
  47437. pWal->hdr.mxFrame = iFrame;
  47438. pWal->hdr.nPage = nTruncate;
  47439. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  47440. testcase( szPage<=32768 );
  47441. testcase( szPage>=65536 );
  47442. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  47443. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  47444. }
  47445. }
  47446. sqlite3_free(aFrame);
  47447. }
  47448. finished:
  47449. if( rc==SQLITE_OK ){
  47450. volatile WalCkptInfo *pInfo;
  47451. int i;
  47452. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  47453. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  47454. walIndexWriteHdr(pWal);
  47455. /* Reset the checkpoint-header. This is safe because this thread is
  47456. ** currently holding locks that exclude all other readers, writers and
  47457. ** checkpointers.
  47458. */
  47459. pInfo = walCkptInfo(pWal);
  47460. pInfo->nBackfill = 0;
  47461. pInfo->aReadMark[0] = 0;
  47462. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  47463. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  47464. /* If more than one frame was recovered from the log file, report an
  47465. ** event via sqlite3_log(). This is to help with identifying performance
  47466. ** problems caused by applications routinely shutting down without
  47467. ** checkpointing the log file.
  47468. */
  47469. if( pWal->hdr.nPage ){
  47470. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  47471. "recovered %d frames from WAL file %s",
  47472. pWal->hdr.mxFrame, pWal->zWalName
  47473. );
  47474. }
  47475. }
  47476. recovery_error:
  47477. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  47478. walUnlockExclusive(pWal, iLock, nLock);
  47479. return rc;
  47480. }
  47481. /*
  47482. ** Close an open wal-index.
  47483. */
  47484. static void walIndexClose(Wal *pWal, int isDelete){
  47485. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  47486. int i;
  47487. for(i=0; i<pWal->nWiData; i++){
  47488. sqlite3_free((void *)pWal->apWiData[i]);
  47489. pWal->apWiData[i] = 0;
  47490. }
  47491. }else{
  47492. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  47493. }
  47494. }
  47495. /*
  47496. ** Open a connection to the WAL file zWalName. The database file must
  47497. ** already be opened on connection pDbFd. The buffer that zWalName points
  47498. ** to must remain valid for the lifetime of the returned Wal* handle.
  47499. **
  47500. ** A SHARED lock should be held on the database file when this function
  47501. ** is called. The purpose of this SHARED lock is to prevent any other
  47502. ** client from unlinking the WAL or wal-index file. If another process
  47503. ** were to do this just after this client opened one of these files, the
  47504. ** system would be badly broken.
  47505. **
  47506. ** If the log file is successfully opened, SQLITE_OK is returned and
  47507. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  47508. ** an SQLite error code is returned and *ppWal is left unmodified.
  47509. */
  47510. SQLITE_PRIVATE int sqlite3WalOpen(
  47511. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  47512. sqlite3_file *pDbFd, /* The open database file */
  47513. const char *zWalName, /* Name of the WAL file */
  47514. int bNoShm, /* True to run in heap-memory mode */
  47515. i64 mxWalSize, /* Truncate WAL to this size on reset */
  47516. Wal **ppWal /* OUT: Allocated Wal handle */
  47517. ){
  47518. int rc; /* Return Code */
  47519. Wal *pRet; /* Object to allocate and return */
  47520. int flags; /* Flags passed to OsOpen() */
  47521. assert( zWalName && zWalName[0] );
  47522. assert( pDbFd );
  47523. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  47524. ** this source file. Verify that the #defines of the locking byte offsets
  47525. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  47526. */
  47527. #ifdef WIN_SHM_BASE
  47528. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  47529. #endif
  47530. #ifdef UNIX_SHM_BASE
  47531. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  47532. #endif
  47533. /* Allocate an instance of struct Wal to return. */
  47534. *ppWal = 0;
  47535. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  47536. if( !pRet ){
  47537. return SQLITE_NOMEM;
  47538. }
  47539. pRet->pVfs = pVfs;
  47540. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  47541. pRet->pDbFd = pDbFd;
  47542. pRet->readLock = -1;
  47543. pRet->mxWalSize = mxWalSize;
  47544. pRet->zWalName = zWalName;
  47545. pRet->syncHeader = 1;
  47546. pRet->padToSectorBoundary = 1;
  47547. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  47548. /* Open file handle on the write-ahead log file. */
  47549. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  47550. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  47551. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  47552. pRet->readOnly = WAL_RDONLY;
  47553. }
  47554. if( rc!=SQLITE_OK ){
  47555. walIndexClose(pRet, 0);
  47556. sqlite3OsClose(pRet->pWalFd);
  47557. sqlite3_free(pRet);
  47558. }else{
  47559. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  47560. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  47561. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  47562. pRet->padToSectorBoundary = 0;
  47563. }
  47564. *ppWal = pRet;
  47565. WALTRACE(("WAL%d: opened\n", pRet));
  47566. }
  47567. return rc;
  47568. }
  47569. /*
  47570. ** Change the size to which the WAL file is trucated on each reset.
  47571. */
  47572. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  47573. if( pWal ) pWal->mxWalSize = iLimit;
  47574. }
  47575. /*
  47576. ** Find the smallest page number out of all pages held in the WAL that
  47577. ** has not been returned by any prior invocation of this method on the
  47578. ** same WalIterator object. Write into *piFrame the frame index where
  47579. ** that page was last written into the WAL. Write into *piPage the page
  47580. ** number.
  47581. **
  47582. ** Return 0 on success. If there are no pages in the WAL with a page
  47583. ** number larger than *piPage, then return 1.
  47584. */
  47585. static int walIteratorNext(
  47586. WalIterator *p, /* Iterator */
  47587. u32 *piPage, /* OUT: The page number of the next page */
  47588. u32 *piFrame /* OUT: Wal frame index of next page */
  47589. ){
  47590. u32 iMin; /* Result pgno must be greater than iMin */
  47591. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  47592. int i; /* For looping through segments */
  47593. iMin = p->iPrior;
  47594. assert( iMin<0xffffffff );
  47595. for(i=p->nSegment-1; i>=0; i--){
  47596. struct WalSegment *pSegment = &p->aSegment[i];
  47597. while( pSegment->iNext<pSegment->nEntry ){
  47598. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  47599. if( iPg>iMin ){
  47600. if( iPg<iRet ){
  47601. iRet = iPg;
  47602. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  47603. }
  47604. break;
  47605. }
  47606. pSegment->iNext++;
  47607. }
  47608. }
  47609. *piPage = p->iPrior = iRet;
  47610. return (iRet==0xFFFFFFFF);
  47611. }
  47612. /*
  47613. ** This function merges two sorted lists into a single sorted list.
  47614. **
  47615. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  47616. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  47617. ** is guaranteed for all J<K:
  47618. **
  47619. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  47620. ** aContent[aRight[J]] < aContent[aRight[K]]
  47621. **
  47622. ** This routine overwrites aRight[] with a new (probably longer) sequence
  47623. ** of indices such that the aRight[] contains every index that appears in
  47624. ** either aLeft[] or the old aRight[] and such that the second condition
  47625. ** above is still met.
  47626. **
  47627. ** The aContent[aLeft[X]] values will be unique for all X. And the
  47628. ** aContent[aRight[X]] values will be unique too. But there might be
  47629. ** one or more combinations of X and Y such that
  47630. **
  47631. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  47632. **
  47633. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  47634. */
  47635. static void walMerge(
  47636. const u32 *aContent, /* Pages in wal - keys for the sort */
  47637. ht_slot *aLeft, /* IN: Left hand input list */
  47638. int nLeft, /* IN: Elements in array *paLeft */
  47639. ht_slot **paRight, /* IN/OUT: Right hand input list */
  47640. int *pnRight, /* IN/OUT: Elements in *paRight */
  47641. ht_slot *aTmp /* Temporary buffer */
  47642. ){
  47643. int iLeft = 0; /* Current index in aLeft */
  47644. int iRight = 0; /* Current index in aRight */
  47645. int iOut = 0; /* Current index in output buffer */
  47646. int nRight = *pnRight;
  47647. ht_slot *aRight = *paRight;
  47648. assert( nLeft>0 && nRight>0 );
  47649. while( iRight<nRight || iLeft<nLeft ){
  47650. ht_slot logpage;
  47651. Pgno dbpage;
  47652. if( (iLeft<nLeft)
  47653. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  47654. ){
  47655. logpage = aLeft[iLeft++];
  47656. }else{
  47657. logpage = aRight[iRight++];
  47658. }
  47659. dbpage = aContent[logpage];
  47660. aTmp[iOut++] = logpage;
  47661. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  47662. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  47663. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  47664. }
  47665. *paRight = aLeft;
  47666. *pnRight = iOut;
  47667. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  47668. }
  47669. /*
  47670. ** Sort the elements in list aList using aContent[] as the sort key.
  47671. ** Remove elements with duplicate keys, preferring to keep the
  47672. ** larger aList[] values.
  47673. **
  47674. ** The aList[] entries are indices into aContent[]. The values in
  47675. ** aList[] are to be sorted so that for all J<K:
  47676. **
  47677. ** aContent[aList[J]] < aContent[aList[K]]
  47678. **
  47679. ** For any X and Y such that
  47680. **
  47681. ** aContent[aList[X]] == aContent[aList[Y]]
  47682. **
  47683. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  47684. ** the smaller.
  47685. */
  47686. static void walMergesort(
  47687. const u32 *aContent, /* Pages in wal */
  47688. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  47689. ht_slot *aList, /* IN/OUT: List to sort */
  47690. int *pnList /* IN/OUT: Number of elements in aList[] */
  47691. ){
  47692. struct Sublist {
  47693. int nList; /* Number of elements in aList */
  47694. ht_slot *aList; /* Pointer to sub-list content */
  47695. };
  47696. const int nList = *pnList; /* Size of input list */
  47697. int nMerge = 0; /* Number of elements in list aMerge */
  47698. ht_slot *aMerge = 0; /* List to be merged */
  47699. int iList; /* Index into input list */
  47700. u32 iSub = 0; /* Index into aSub array */
  47701. struct Sublist aSub[13]; /* Array of sub-lists */
  47702. memset(aSub, 0, sizeof(aSub));
  47703. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  47704. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  47705. for(iList=0; iList<nList; iList++){
  47706. nMerge = 1;
  47707. aMerge = &aList[iList];
  47708. for(iSub=0; iList & (1<<iSub); iSub++){
  47709. struct Sublist *p;
  47710. assert( iSub<ArraySize(aSub) );
  47711. p = &aSub[iSub];
  47712. assert( p->aList && p->nList<=(1<<iSub) );
  47713. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  47714. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47715. }
  47716. aSub[iSub].aList = aMerge;
  47717. aSub[iSub].nList = nMerge;
  47718. }
  47719. for(iSub++; iSub<ArraySize(aSub); iSub++){
  47720. if( nList & (1<<iSub) ){
  47721. struct Sublist *p;
  47722. assert( iSub<ArraySize(aSub) );
  47723. p = &aSub[iSub];
  47724. assert( p->nList<=(1<<iSub) );
  47725. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  47726. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47727. }
  47728. }
  47729. assert( aMerge==aList );
  47730. *pnList = nMerge;
  47731. #ifdef SQLITE_DEBUG
  47732. {
  47733. int i;
  47734. for(i=1; i<*pnList; i++){
  47735. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  47736. }
  47737. }
  47738. #endif
  47739. }
  47740. /*
  47741. ** Free an iterator allocated by walIteratorInit().
  47742. */
  47743. static void walIteratorFree(WalIterator *p){
  47744. sqlite3_free(p);
  47745. }
  47746. /*
  47747. ** Construct a WalInterator object that can be used to loop over all
  47748. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  47749. ** lock.
  47750. **
  47751. ** On success, make *pp point to the newly allocated WalInterator object
  47752. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  47753. ** returns an error, the value of *pp is undefined.
  47754. **
  47755. ** The calling routine should invoke walIteratorFree() to destroy the
  47756. ** WalIterator object when it has finished with it.
  47757. */
  47758. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  47759. WalIterator *p; /* Return value */
  47760. int nSegment; /* Number of segments to merge */
  47761. u32 iLast; /* Last frame in log */
  47762. int nByte; /* Number of bytes to allocate */
  47763. int i; /* Iterator variable */
  47764. ht_slot *aTmp; /* Temp space used by merge-sort */
  47765. int rc = SQLITE_OK; /* Return Code */
  47766. /* This routine only runs while holding the checkpoint lock. And
  47767. ** it only runs if there is actually content in the log (mxFrame>0).
  47768. */
  47769. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  47770. iLast = pWal->hdr.mxFrame;
  47771. /* Allocate space for the WalIterator object. */
  47772. nSegment = walFramePage(iLast) + 1;
  47773. nByte = sizeof(WalIterator)
  47774. + (nSegment-1)*sizeof(struct WalSegment)
  47775. + iLast*sizeof(ht_slot);
  47776. p = (WalIterator *)sqlite3_malloc64(nByte);
  47777. if( !p ){
  47778. return SQLITE_NOMEM;
  47779. }
  47780. memset(p, 0, nByte);
  47781. p->nSegment = nSegment;
  47782. /* Allocate temporary space used by the merge-sort routine. This block
  47783. ** of memory will be freed before this function returns.
  47784. */
  47785. aTmp = (ht_slot *)sqlite3_malloc64(
  47786. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  47787. );
  47788. if( !aTmp ){
  47789. rc = SQLITE_NOMEM;
  47790. }
  47791. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  47792. volatile ht_slot *aHash;
  47793. u32 iZero;
  47794. volatile u32 *aPgno;
  47795. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  47796. if( rc==SQLITE_OK ){
  47797. int j; /* Counter variable */
  47798. int nEntry; /* Number of entries in this segment */
  47799. ht_slot *aIndex; /* Sorted index for this segment */
  47800. aPgno++;
  47801. if( (i+1)==nSegment ){
  47802. nEntry = (int)(iLast - iZero);
  47803. }else{
  47804. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  47805. }
  47806. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  47807. iZero++;
  47808. for(j=0; j<nEntry; j++){
  47809. aIndex[j] = (ht_slot)j;
  47810. }
  47811. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  47812. p->aSegment[i].iZero = iZero;
  47813. p->aSegment[i].nEntry = nEntry;
  47814. p->aSegment[i].aIndex = aIndex;
  47815. p->aSegment[i].aPgno = (u32 *)aPgno;
  47816. }
  47817. }
  47818. sqlite3_free(aTmp);
  47819. if( rc!=SQLITE_OK ){
  47820. walIteratorFree(p);
  47821. }
  47822. *pp = p;
  47823. return rc;
  47824. }
  47825. /*
  47826. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  47827. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  47828. ** busy-handler function. Invoke it and retry the lock until either the
  47829. ** lock is successfully obtained or the busy-handler returns 0.
  47830. */
  47831. static int walBusyLock(
  47832. Wal *pWal, /* WAL connection */
  47833. int (*xBusy)(void*), /* Function to call when busy */
  47834. void *pBusyArg, /* Context argument for xBusyHandler */
  47835. int lockIdx, /* Offset of first byte to lock */
  47836. int n /* Number of bytes to lock */
  47837. ){
  47838. int rc;
  47839. do {
  47840. rc = walLockExclusive(pWal, lockIdx, n, 0);
  47841. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  47842. return rc;
  47843. }
  47844. /*
  47845. ** The cache of the wal-index header must be valid to call this function.
  47846. ** Return the page-size in bytes used by the database.
  47847. */
  47848. static int walPagesize(Wal *pWal){
  47849. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  47850. }
  47851. /*
  47852. ** The following is guaranteed when this function is called:
  47853. **
  47854. ** a) the WRITER lock is held,
  47855. ** b) the entire log file has been checkpointed, and
  47856. ** c) any existing readers are reading exclusively from the database
  47857. ** file - there are no readers that may attempt to read a frame from
  47858. ** the log file.
  47859. **
  47860. ** This function updates the shared-memory structures so that the next
  47861. ** client to write to the database (which may be this one) does so by
  47862. ** writing frames into the start of the log file.
  47863. **
  47864. ** The value of parameter salt1 is used as the aSalt[1] value in the
  47865. ** new wal-index header. It should be passed a pseudo-random value (i.e.
  47866. ** one obtained from sqlite3_randomness()).
  47867. */
  47868. static void walRestartHdr(Wal *pWal, u32 salt1){
  47869. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  47870. int i; /* Loop counter */
  47871. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  47872. pWal->nCkpt++;
  47873. pWal->hdr.mxFrame = 0;
  47874. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  47875. memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
  47876. walIndexWriteHdr(pWal);
  47877. pInfo->nBackfill = 0;
  47878. pInfo->aReadMark[1] = 0;
  47879. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  47880. assert( pInfo->aReadMark[0]==0 );
  47881. }
  47882. /*
  47883. ** Copy as much content as we can from the WAL back into the database file
  47884. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  47885. **
  47886. ** The amount of information copies from WAL to database might be limited
  47887. ** by active readers. This routine will never overwrite a database page
  47888. ** that a concurrent reader might be using.
  47889. **
  47890. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  47891. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  47892. ** checkpoints are always run by a background thread or background
  47893. ** process, foreground threads will never block on a lengthy fsync call.
  47894. **
  47895. ** Fsync is called on the WAL before writing content out of the WAL and
  47896. ** into the database. This ensures that if the new content is persistent
  47897. ** in the WAL and can be recovered following a power-loss or hard reset.
  47898. **
  47899. ** Fsync is also called on the database file if (and only if) the entire
  47900. ** WAL content is copied into the database file. This second fsync makes
  47901. ** it safe to delete the WAL since the new content will persist in the
  47902. ** database file.
  47903. **
  47904. ** This routine uses and updates the nBackfill field of the wal-index header.
  47905. ** This is the only routine that will increase the value of nBackfill.
  47906. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  47907. ** its value.)
  47908. **
  47909. ** The caller must be holding sufficient locks to ensure that no other
  47910. ** checkpoint is running (in any other thread or process) at the same
  47911. ** time.
  47912. */
  47913. static int walCheckpoint(
  47914. Wal *pWal, /* Wal connection */
  47915. int eMode, /* One of PASSIVE, FULL or RESTART */
  47916. int (*xBusy)(void*), /* Function to call when busy */
  47917. void *pBusyArg, /* Context argument for xBusyHandler */
  47918. int sync_flags, /* Flags for OsSync() (or 0) */
  47919. u8 *zBuf /* Temporary buffer to use */
  47920. ){
  47921. int rc = SQLITE_OK; /* Return code */
  47922. int szPage; /* Database page-size */
  47923. WalIterator *pIter = 0; /* Wal iterator context */
  47924. u32 iDbpage = 0; /* Next database page to write */
  47925. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  47926. u32 mxSafeFrame; /* Max frame that can be backfilled */
  47927. u32 mxPage; /* Max database page to write */
  47928. int i; /* Loop counter */
  47929. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  47930. szPage = walPagesize(pWal);
  47931. testcase( szPage<=32768 );
  47932. testcase( szPage>=65536 );
  47933. pInfo = walCkptInfo(pWal);
  47934. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  47935. /* Allocate the iterator */
  47936. rc = walIteratorInit(pWal, &pIter);
  47937. if( rc!=SQLITE_OK ){
  47938. return rc;
  47939. }
  47940. assert( pIter );
  47941. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  47942. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  47943. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  47944. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  47945. ** safe to write into the database. Frames beyond mxSafeFrame might
  47946. ** overwrite database pages that are in use by active readers and thus
  47947. ** cannot be backfilled from the WAL.
  47948. */
  47949. mxSafeFrame = pWal->hdr.mxFrame;
  47950. mxPage = pWal->hdr.nPage;
  47951. for(i=1; i<WAL_NREADER; i++){
  47952. /* Thread-sanitizer reports that the following is an unsafe read,
  47953. ** as some other thread may be in the process of updating the value
  47954. ** of the aReadMark[] slot. The assumption here is that if that is
  47955. ** happening, the other client may only be increasing the value,
  47956. ** not decreasing it. So assuming either that either the "old" or
  47957. ** "new" version of the value is read, and not some arbitrary value
  47958. ** that would never be written by a real client, things are still
  47959. ** safe. */
  47960. u32 y = pInfo->aReadMark[i];
  47961. if( mxSafeFrame>y ){
  47962. assert( y<=pWal->hdr.mxFrame );
  47963. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  47964. if( rc==SQLITE_OK ){
  47965. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  47966. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47967. }else if( rc==SQLITE_BUSY ){
  47968. mxSafeFrame = y;
  47969. xBusy = 0;
  47970. }else{
  47971. goto walcheckpoint_out;
  47972. }
  47973. }
  47974. }
  47975. if( pInfo->nBackfill<mxSafeFrame
  47976. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
  47977. ){
  47978. i64 nSize; /* Current size of database file */
  47979. u32 nBackfill = pInfo->nBackfill;
  47980. /* Sync the WAL to disk */
  47981. if( sync_flags ){
  47982. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  47983. }
  47984. /* If the database may grow as a result of this checkpoint, hint
  47985. ** about the eventual size of the db file to the VFS layer.
  47986. */
  47987. if( rc==SQLITE_OK ){
  47988. i64 nReq = ((i64)mxPage * szPage);
  47989. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  47990. if( rc==SQLITE_OK && nSize<nReq ){
  47991. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  47992. }
  47993. }
  47994. /* Iterate through the contents of the WAL, copying data to the db file */
  47995. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  47996. i64 iOffset;
  47997. assert( walFramePgno(pWal, iFrame)==iDbpage );
  47998. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
  47999. continue;
  48000. }
  48001. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  48002. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  48003. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  48004. if( rc!=SQLITE_OK ) break;
  48005. iOffset = (iDbpage-1)*(i64)szPage;
  48006. testcase( IS_BIG_INT(iOffset) );
  48007. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  48008. if( rc!=SQLITE_OK ) break;
  48009. }
  48010. /* If work was actually accomplished... */
  48011. if( rc==SQLITE_OK ){
  48012. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  48013. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  48014. testcase( IS_BIG_INT(szDb) );
  48015. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  48016. if( rc==SQLITE_OK && sync_flags ){
  48017. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  48018. }
  48019. }
  48020. if( rc==SQLITE_OK ){
  48021. pInfo->nBackfill = mxSafeFrame;
  48022. }
  48023. }
  48024. /* Release the reader lock held while backfilling */
  48025. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  48026. }
  48027. if( rc==SQLITE_BUSY ){
  48028. /* Reset the return code so as not to report a checkpoint failure
  48029. ** just because there are active readers. */
  48030. rc = SQLITE_OK;
  48031. }
  48032. }
  48033. /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
  48034. ** entire wal file has been copied into the database file, then block
  48035. ** until all readers have finished using the wal file. This ensures that
  48036. ** the next process to write to the database restarts the wal file.
  48037. */
  48038. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  48039. assert( pWal->writeLock );
  48040. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  48041. rc = SQLITE_BUSY;
  48042. }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
  48043. u32 salt1;
  48044. sqlite3_randomness(4, &salt1);
  48045. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  48046. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  48047. if( rc==SQLITE_OK ){
  48048. if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
  48049. /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
  48050. ** SQLITE_CHECKPOINT_RESTART with the addition that it also
  48051. ** truncates the log file to zero bytes just prior to a
  48052. ** successful return.
  48053. **
  48054. ** In theory, it might be safe to do this without updating the
  48055. ** wal-index header in shared memory, as all subsequent reader or
  48056. ** writer clients should see that the entire log file has been
  48057. ** checkpointed and behave accordingly. This seems unsafe though,
  48058. ** as it would leave the system in a state where the contents of
  48059. ** the wal-index header do not match the contents of the
  48060. ** file-system. To avoid this, update the wal-index header to
  48061. ** indicate that the log file contains zero valid frames. */
  48062. walRestartHdr(pWal, salt1);
  48063. rc = sqlite3OsTruncate(pWal->pWalFd, 0);
  48064. }
  48065. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48066. }
  48067. }
  48068. }
  48069. walcheckpoint_out:
  48070. walIteratorFree(pIter);
  48071. return rc;
  48072. }
  48073. /*
  48074. ** If the WAL file is currently larger than nMax bytes in size, truncate
  48075. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  48076. */
  48077. static void walLimitSize(Wal *pWal, i64 nMax){
  48078. i64 sz;
  48079. int rx;
  48080. sqlite3BeginBenignMalloc();
  48081. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  48082. if( rx==SQLITE_OK && (sz > nMax ) ){
  48083. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  48084. }
  48085. sqlite3EndBenignMalloc();
  48086. if( rx ){
  48087. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  48088. }
  48089. }
  48090. /*
  48091. ** Close a connection to a log file.
  48092. */
  48093. SQLITE_PRIVATE int sqlite3WalClose(
  48094. Wal *pWal, /* Wal to close */
  48095. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  48096. int nBuf,
  48097. u8 *zBuf /* Buffer of at least nBuf bytes */
  48098. ){
  48099. int rc = SQLITE_OK;
  48100. if( pWal ){
  48101. int isDelete = 0; /* True to unlink wal and wal-index files */
  48102. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  48103. ** ordinary, rollback-mode locking methods, this guarantees that the
  48104. ** connection associated with this log file is the only connection to
  48105. ** the database. In this case checkpoint the database and unlink both
  48106. ** the wal and wal-index files.
  48107. **
  48108. ** The EXCLUSIVE lock is not released before returning.
  48109. */
  48110. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  48111. if( rc==SQLITE_OK ){
  48112. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  48113. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  48114. }
  48115. rc = sqlite3WalCheckpoint(
  48116. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  48117. );
  48118. if( rc==SQLITE_OK ){
  48119. int bPersist = -1;
  48120. sqlite3OsFileControlHint(
  48121. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  48122. );
  48123. if( bPersist!=1 ){
  48124. /* Try to delete the WAL file if the checkpoint completed and
  48125. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  48126. ** mode (!bPersist) */
  48127. isDelete = 1;
  48128. }else if( pWal->mxWalSize>=0 ){
  48129. /* Try to truncate the WAL file to zero bytes if the checkpoint
  48130. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  48131. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  48132. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  48133. ** to zero bytes as truncating to the journal_size_limit might
  48134. ** leave a corrupt WAL file on disk. */
  48135. walLimitSize(pWal, 0);
  48136. }
  48137. }
  48138. }
  48139. walIndexClose(pWal, isDelete);
  48140. sqlite3OsClose(pWal->pWalFd);
  48141. if( isDelete ){
  48142. sqlite3BeginBenignMalloc();
  48143. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  48144. sqlite3EndBenignMalloc();
  48145. }
  48146. WALTRACE(("WAL%p: closed\n", pWal));
  48147. sqlite3_free((void *)pWal->apWiData);
  48148. sqlite3_free(pWal);
  48149. }
  48150. return rc;
  48151. }
  48152. /*
  48153. ** Try to read the wal-index header. Return 0 on success and 1 if
  48154. ** there is a problem.
  48155. **
  48156. ** The wal-index is in shared memory. Another thread or process might
  48157. ** be writing the header at the same time this procedure is trying to
  48158. ** read it, which might result in inconsistency. A dirty read is detected
  48159. ** by verifying that both copies of the header are the same and also by
  48160. ** a checksum on the header.
  48161. **
  48162. ** If and only if the read is consistent and the header is different from
  48163. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  48164. ** and *pChanged is set to 1.
  48165. **
  48166. ** If the checksum cannot be verified return non-zero. If the header
  48167. ** is read successfully and the checksum verified, return zero.
  48168. */
  48169. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  48170. u32 aCksum[2]; /* Checksum on the header content */
  48171. WalIndexHdr h1, h2; /* Two copies of the header content */
  48172. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  48173. /* The first page of the wal-index must be mapped at this point. */
  48174. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  48175. /* Read the header. This might happen concurrently with a write to the
  48176. ** same area of shared memory on a different CPU in a SMP,
  48177. ** meaning it is possible that an inconsistent snapshot is read
  48178. ** from the file. If this happens, return non-zero.
  48179. **
  48180. ** There are two copies of the header at the beginning of the wal-index.
  48181. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  48182. ** Memory barriers are used to prevent the compiler or the hardware from
  48183. ** reordering the reads and writes.
  48184. */
  48185. aHdr = walIndexHdr(pWal);
  48186. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  48187. walShmBarrier(pWal);
  48188. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  48189. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  48190. return 1; /* Dirty read */
  48191. }
  48192. if( h1.isInit==0 ){
  48193. return 1; /* Malformed header - probably all zeros */
  48194. }
  48195. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  48196. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  48197. return 1; /* Checksum does not match */
  48198. }
  48199. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  48200. *pChanged = 1;
  48201. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  48202. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  48203. testcase( pWal->szPage<=32768 );
  48204. testcase( pWal->szPage>=65536 );
  48205. }
  48206. /* The header was successfully read. Return zero. */
  48207. return 0;
  48208. }
  48209. /*
  48210. ** Read the wal-index header from the wal-index and into pWal->hdr.
  48211. ** If the wal-header appears to be corrupt, try to reconstruct the
  48212. ** wal-index from the WAL before returning.
  48213. **
  48214. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  48215. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  48216. ** to 0.
  48217. **
  48218. ** If the wal-index header is successfully read, return SQLITE_OK.
  48219. ** Otherwise an SQLite error code.
  48220. */
  48221. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  48222. int rc; /* Return code */
  48223. int badHdr; /* True if a header read failed */
  48224. volatile u32 *page0; /* Chunk of wal-index containing header */
  48225. /* Ensure that page 0 of the wal-index (the page that contains the
  48226. ** wal-index header) is mapped. Return early if an error occurs here.
  48227. */
  48228. assert( pChanged );
  48229. rc = walIndexPage(pWal, 0, &page0);
  48230. if( rc!=SQLITE_OK ){
  48231. return rc;
  48232. };
  48233. assert( page0 || pWal->writeLock==0 );
  48234. /* If the first page of the wal-index has been mapped, try to read the
  48235. ** wal-index header immediately, without holding any lock. This usually
  48236. ** works, but may fail if the wal-index header is corrupt or currently
  48237. ** being modified by another thread or process.
  48238. */
  48239. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  48240. /* If the first attempt failed, it might have been due to a race
  48241. ** with a writer. So get a WRITE lock and try again.
  48242. */
  48243. assert( badHdr==0 || pWal->writeLock==0 );
  48244. if( badHdr ){
  48245. if( pWal->readOnly & WAL_SHM_RDONLY ){
  48246. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  48247. walUnlockShared(pWal, WAL_WRITE_LOCK);
  48248. rc = SQLITE_READONLY_RECOVERY;
  48249. }
  48250. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 1)) ){
  48251. pWal->writeLock = 1;
  48252. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  48253. badHdr = walIndexTryHdr(pWal, pChanged);
  48254. if( badHdr ){
  48255. /* If the wal-index header is still malformed even while holding
  48256. ** a WRITE lock, it can only mean that the header is corrupted and
  48257. ** needs to be reconstructed. So run recovery to do exactly that.
  48258. */
  48259. rc = walIndexRecover(pWal);
  48260. *pChanged = 1;
  48261. }
  48262. }
  48263. pWal->writeLock = 0;
  48264. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48265. }
  48266. }
  48267. /* If the header is read successfully, check the version number to make
  48268. ** sure the wal-index was not constructed with some future format that
  48269. ** this version of SQLite cannot understand.
  48270. */
  48271. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  48272. rc = SQLITE_CANTOPEN_BKPT;
  48273. }
  48274. return rc;
  48275. }
  48276. /*
  48277. ** This is the value that walTryBeginRead returns when it needs to
  48278. ** be retried.
  48279. */
  48280. #define WAL_RETRY (-1)
  48281. /*
  48282. ** Attempt to start a read transaction. This might fail due to a race or
  48283. ** other transient condition. When that happens, it returns WAL_RETRY to
  48284. ** indicate to the caller that it is safe to retry immediately.
  48285. **
  48286. ** On success return SQLITE_OK. On a permanent failure (such an
  48287. ** I/O error or an SQLITE_BUSY because another process is running
  48288. ** recovery) return a positive error code.
  48289. **
  48290. ** The useWal parameter is true to force the use of the WAL and disable
  48291. ** the case where the WAL is bypassed because it has been completely
  48292. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  48293. ** to make a copy of the wal-index header into pWal->hdr. If the
  48294. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  48295. ** to the caller that the local paget cache is obsolete and needs to be
  48296. ** flushed.) When useWal==1, the wal-index header is assumed to already
  48297. ** be loaded and the pChanged parameter is unused.
  48298. **
  48299. ** The caller must set the cnt parameter to the number of prior calls to
  48300. ** this routine during the current read attempt that returned WAL_RETRY.
  48301. ** This routine will start taking more aggressive measures to clear the
  48302. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  48303. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  48304. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  48305. ** and is not honoring the locking protocol. There is a vanishingly small
  48306. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  48307. ** bad luck when there is lots of contention for the wal-index, but that
  48308. ** possibility is so small that it can be safely neglected, we believe.
  48309. **
  48310. ** On success, this routine obtains a read lock on
  48311. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  48312. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  48313. ** that means the Wal does not hold any read lock. The reader must not
  48314. ** access any database page that is modified by a WAL frame up to and
  48315. ** including frame number aReadMark[pWal->readLock]. The reader will
  48316. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  48317. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  48318. ** completely and get all content directly from the database file.
  48319. ** If the useWal parameter is 1 then the WAL will never be ignored and
  48320. ** this routine will always set pWal->readLock>0 on success.
  48321. ** When the read transaction is completed, the caller must release the
  48322. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  48323. **
  48324. ** This routine uses the nBackfill and aReadMark[] fields of the header
  48325. ** to select a particular WAL_READ_LOCK() that strives to let the
  48326. ** checkpoint process do as much work as possible. This routine might
  48327. ** update values of the aReadMark[] array in the header, but if it does
  48328. ** so it takes care to hold an exclusive lock on the corresponding
  48329. ** WAL_READ_LOCK() while changing values.
  48330. */
  48331. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  48332. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  48333. u32 mxReadMark; /* Largest aReadMark[] value */
  48334. int mxI; /* Index of largest aReadMark[] value */
  48335. int i; /* Loop counter */
  48336. int rc = SQLITE_OK; /* Return code */
  48337. assert( pWal->readLock<0 ); /* Not currently locked */
  48338. /* Take steps to avoid spinning forever if there is a protocol error.
  48339. **
  48340. ** Circumstances that cause a RETRY should only last for the briefest
  48341. ** instances of time. No I/O or other system calls are done while the
  48342. ** locks are held, so the locks should not be held for very long. But
  48343. ** if we are unlucky, another process that is holding a lock might get
  48344. ** paged out or take a page-fault that is time-consuming to resolve,
  48345. ** during the few nanoseconds that it is holding the lock. In that case,
  48346. ** it might take longer than normal for the lock to free.
  48347. **
  48348. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  48349. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  48350. ** is more of a scheduler yield than an actual delay. But on the 10th
  48351. ** an subsequent retries, the delays start becoming longer and longer,
  48352. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  48353. ** The total delay time before giving up is less than 10 seconds.
  48354. */
  48355. if( cnt>5 ){
  48356. int nDelay = 1; /* Pause time in microseconds */
  48357. if( cnt>100 ){
  48358. VVA_ONLY( pWal->lockError = 1; )
  48359. return SQLITE_PROTOCOL;
  48360. }
  48361. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  48362. sqlite3OsSleep(pWal->pVfs, nDelay);
  48363. }
  48364. if( !useWal ){
  48365. rc = walIndexReadHdr(pWal, pChanged);
  48366. if( rc==SQLITE_BUSY ){
  48367. /* If there is not a recovery running in another thread or process
  48368. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  48369. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  48370. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  48371. ** would be technically correct. But the race is benign since with
  48372. ** WAL_RETRY this routine will be called again and will probably be
  48373. ** right on the second iteration.
  48374. */
  48375. if( pWal->apWiData[0]==0 ){
  48376. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  48377. ** We assume this is a transient condition, so return WAL_RETRY. The
  48378. ** xShmMap() implementation used by the default unix and win32 VFS
  48379. ** modules may return SQLITE_BUSY due to a race condition in the
  48380. ** code that determines whether or not the shared-memory region
  48381. ** must be zeroed before the requested page is returned.
  48382. */
  48383. rc = WAL_RETRY;
  48384. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  48385. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  48386. rc = WAL_RETRY;
  48387. }else if( rc==SQLITE_BUSY ){
  48388. rc = SQLITE_BUSY_RECOVERY;
  48389. }
  48390. }
  48391. if( rc!=SQLITE_OK ){
  48392. return rc;
  48393. }
  48394. }
  48395. pInfo = walCkptInfo(pWal);
  48396. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  48397. /* The WAL has been completely backfilled (or it is empty).
  48398. ** and can be safely ignored.
  48399. */
  48400. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  48401. walShmBarrier(pWal);
  48402. if( rc==SQLITE_OK ){
  48403. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  48404. /* It is not safe to allow the reader to continue here if frames
  48405. ** may have been appended to the log before READ_LOCK(0) was obtained.
  48406. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  48407. ** which implies that the database file contains a trustworthy
  48408. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  48409. ** happening, this is usually correct.
  48410. **
  48411. ** However, if frames have been appended to the log (or if the log
  48412. ** is wrapped and written for that matter) before the READ_LOCK(0)
  48413. ** is obtained, that is not necessarily true. A checkpointer may
  48414. ** have started to backfill the appended frames but crashed before
  48415. ** it finished. Leaving a corrupt image in the database file.
  48416. */
  48417. walUnlockShared(pWal, WAL_READ_LOCK(0));
  48418. return WAL_RETRY;
  48419. }
  48420. pWal->readLock = 0;
  48421. return SQLITE_OK;
  48422. }else if( rc!=SQLITE_BUSY ){
  48423. return rc;
  48424. }
  48425. }
  48426. /* If we get this far, it means that the reader will want to use
  48427. ** the WAL to get at content from recent commits. The job now is
  48428. ** to select one of the aReadMark[] entries that is closest to
  48429. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  48430. */
  48431. mxReadMark = 0;
  48432. mxI = 0;
  48433. for(i=1; i<WAL_NREADER; i++){
  48434. u32 thisMark = pInfo->aReadMark[i];
  48435. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  48436. assert( thisMark!=READMARK_NOT_USED );
  48437. mxReadMark = thisMark;
  48438. mxI = i;
  48439. }
  48440. }
  48441. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  48442. {
  48443. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  48444. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  48445. ){
  48446. for(i=1; i<WAL_NREADER; i++){
  48447. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1, 0);
  48448. if( rc==SQLITE_OK ){
  48449. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  48450. mxI = i;
  48451. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  48452. break;
  48453. }else if( rc!=SQLITE_BUSY ){
  48454. return rc;
  48455. }
  48456. }
  48457. }
  48458. if( mxI==0 ){
  48459. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  48460. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  48461. }
  48462. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  48463. if( rc ){
  48464. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  48465. }
  48466. /* Now that the read-lock has been obtained, check that neither the
  48467. ** value in the aReadMark[] array or the contents of the wal-index
  48468. ** header have changed.
  48469. **
  48470. ** It is necessary to check that the wal-index header did not change
  48471. ** between the time it was read and when the shared-lock was obtained
  48472. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  48473. ** that the log file may have been wrapped by a writer, or that frames
  48474. ** that occur later in the log than pWal->hdr.mxFrame may have been
  48475. ** copied into the database by a checkpointer. If either of these things
  48476. ** happened, then reading the database with the current value of
  48477. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  48478. ** instead.
  48479. **
  48480. ** This does not guarantee that the copy of the wal-index header is up to
  48481. ** date before proceeding. That would not be possible without somehow
  48482. ** blocking writers. It only guarantees that a dangerous checkpoint or
  48483. ** log-wrap (either of which would require an exclusive lock on
  48484. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  48485. */
  48486. walShmBarrier(pWal);
  48487. if( pInfo->aReadMark[mxI]!=mxReadMark
  48488. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  48489. ){
  48490. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  48491. return WAL_RETRY;
  48492. }else{
  48493. assert( mxReadMark<=pWal->hdr.mxFrame );
  48494. pWal->readLock = (i16)mxI;
  48495. }
  48496. }
  48497. return rc;
  48498. }
  48499. /*
  48500. ** Begin a read transaction on the database.
  48501. **
  48502. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  48503. ** it takes a snapshot of the state of the WAL and wal-index for the current
  48504. ** instant in time. The current thread will continue to use this snapshot.
  48505. ** Other threads might append new content to the WAL and wal-index but
  48506. ** that extra content is ignored by the current thread.
  48507. **
  48508. ** If the database contents have changes since the previous read
  48509. ** transaction, then *pChanged is set to 1 before returning. The
  48510. ** Pager layer will use this to know that is cache is stale and
  48511. ** needs to be flushed.
  48512. */
  48513. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  48514. int rc; /* Return code */
  48515. int cnt = 0; /* Number of TryBeginRead attempts */
  48516. do{
  48517. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  48518. }while( rc==WAL_RETRY );
  48519. testcase( (rc&0xff)==SQLITE_BUSY );
  48520. testcase( (rc&0xff)==SQLITE_IOERR );
  48521. testcase( rc==SQLITE_PROTOCOL );
  48522. testcase( rc==SQLITE_OK );
  48523. return rc;
  48524. }
  48525. /*
  48526. ** Finish with a read transaction. All this does is release the
  48527. ** read-lock.
  48528. */
  48529. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  48530. sqlite3WalEndWriteTransaction(pWal);
  48531. if( pWal->readLock>=0 ){
  48532. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  48533. pWal->readLock = -1;
  48534. }
  48535. }
  48536. /*
  48537. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  48538. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  48539. ** to zero.
  48540. **
  48541. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  48542. ** error does occur, the final value of *piRead is undefined.
  48543. */
  48544. SQLITE_PRIVATE int sqlite3WalFindFrame(
  48545. Wal *pWal, /* WAL handle */
  48546. Pgno pgno, /* Database page number to read data for */
  48547. u32 *piRead /* OUT: Frame number (or zero) */
  48548. ){
  48549. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  48550. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  48551. int iHash; /* Used to loop through N hash tables */
  48552. /* This routine is only be called from within a read transaction. */
  48553. assert( pWal->readLock>=0 || pWal->lockError );
  48554. /* If the "last page" field of the wal-index header snapshot is 0, then
  48555. ** no data will be read from the wal under any circumstances. Return early
  48556. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  48557. ** then the WAL is ignored by the reader so return early, as if the
  48558. ** WAL were empty.
  48559. */
  48560. if( iLast==0 || pWal->readLock==0 ){
  48561. *piRead = 0;
  48562. return SQLITE_OK;
  48563. }
  48564. /* Search the hash table or tables for an entry matching page number
  48565. ** pgno. Each iteration of the following for() loop searches one
  48566. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  48567. **
  48568. ** This code might run concurrently to the code in walIndexAppend()
  48569. ** that adds entries to the wal-index (and possibly to this hash
  48570. ** table). This means the value just read from the hash
  48571. ** slot (aHash[iKey]) may have been added before or after the
  48572. ** current read transaction was opened. Values added after the
  48573. ** read transaction was opened may have been written incorrectly -
  48574. ** i.e. these slots may contain garbage data. However, we assume
  48575. ** that any slots written before the current read transaction was
  48576. ** opened remain unmodified.
  48577. **
  48578. ** For the reasons above, the if(...) condition featured in the inner
  48579. ** loop of the following block is more stringent that would be required
  48580. ** if we had exclusive access to the hash-table:
  48581. **
  48582. ** (aPgno[iFrame]==pgno):
  48583. ** This condition filters out normal hash-table collisions.
  48584. **
  48585. ** (iFrame<=iLast):
  48586. ** This condition filters out entries that were added to the hash
  48587. ** table after the current read-transaction had started.
  48588. */
  48589. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  48590. volatile ht_slot *aHash; /* Pointer to hash table */
  48591. volatile u32 *aPgno; /* Pointer to array of page numbers */
  48592. u32 iZero; /* Frame number corresponding to aPgno[0] */
  48593. int iKey; /* Hash slot index */
  48594. int nCollide; /* Number of hash collisions remaining */
  48595. int rc; /* Error code */
  48596. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  48597. if( rc!=SQLITE_OK ){
  48598. return rc;
  48599. }
  48600. nCollide = HASHTABLE_NSLOT;
  48601. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  48602. u32 iFrame = aHash[iKey] + iZero;
  48603. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  48604. assert( iFrame>iRead || CORRUPT_DB );
  48605. iRead = iFrame;
  48606. }
  48607. if( (nCollide--)==0 ){
  48608. return SQLITE_CORRUPT_BKPT;
  48609. }
  48610. }
  48611. }
  48612. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  48613. /* If expensive assert() statements are available, do a linear search
  48614. ** of the wal-index file content. Make sure the results agree with the
  48615. ** result obtained using the hash indexes above. */
  48616. {
  48617. u32 iRead2 = 0;
  48618. u32 iTest;
  48619. for(iTest=iLast; iTest>0; iTest--){
  48620. if( walFramePgno(pWal, iTest)==pgno ){
  48621. iRead2 = iTest;
  48622. break;
  48623. }
  48624. }
  48625. assert( iRead==iRead2 );
  48626. }
  48627. #endif
  48628. *piRead = iRead;
  48629. return SQLITE_OK;
  48630. }
  48631. /*
  48632. ** Read the contents of frame iRead from the wal file into buffer pOut
  48633. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  48634. ** error code otherwise.
  48635. */
  48636. SQLITE_PRIVATE int sqlite3WalReadFrame(
  48637. Wal *pWal, /* WAL handle */
  48638. u32 iRead, /* Frame to read */
  48639. int nOut, /* Size of buffer pOut in bytes */
  48640. u8 *pOut /* Buffer to write page data to */
  48641. ){
  48642. int sz;
  48643. i64 iOffset;
  48644. sz = pWal->hdr.szPage;
  48645. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  48646. testcase( sz<=32768 );
  48647. testcase( sz>=65536 );
  48648. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  48649. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  48650. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  48651. }
  48652. /*
  48653. ** Return the size of the database in pages (or zero, if unknown).
  48654. */
  48655. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  48656. if( pWal && ALWAYS(pWal->readLock>=0) ){
  48657. return pWal->hdr.nPage;
  48658. }
  48659. return 0;
  48660. }
  48661. /*
  48662. ** This function starts a write transaction on the WAL.
  48663. **
  48664. ** A read transaction must have already been started by a prior call
  48665. ** to sqlite3WalBeginReadTransaction().
  48666. **
  48667. ** If another thread or process has written into the database since
  48668. ** the read transaction was started, then it is not possible for this
  48669. ** thread to write as doing so would cause a fork. So this routine
  48670. ** returns SQLITE_BUSY in that case and no write transaction is started.
  48671. **
  48672. ** There can only be a single writer active at a time.
  48673. */
  48674. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  48675. int rc;
  48676. /* Cannot start a write transaction without first holding a read
  48677. ** transaction. */
  48678. assert( pWal->readLock>=0 );
  48679. if( pWal->readOnly ){
  48680. return SQLITE_READONLY;
  48681. }
  48682. /* Only one writer allowed at a time. Get the write lock. Return
  48683. ** SQLITE_BUSY if unable.
  48684. */
  48685. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 0);
  48686. if( rc ){
  48687. return rc;
  48688. }
  48689. pWal->writeLock = 1;
  48690. /* If another connection has written to the database file since the
  48691. ** time the read transaction on this connection was started, then
  48692. ** the write is disallowed.
  48693. */
  48694. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  48695. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48696. pWal->writeLock = 0;
  48697. rc = SQLITE_BUSY_SNAPSHOT;
  48698. }
  48699. return rc;
  48700. }
  48701. /*
  48702. ** End a write transaction. The commit has already been done. This
  48703. ** routine merely releases the lock.
  48704. */
  48705. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  48706. if( pWal->writeLock ){
  48707. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48708. pWal->writeLock = 0;
  48709. pWal->truncateOnCommit = 0;
  48710. }
  48711. return SQLITE_OK;
  48712. }
  48713. /*
  48714. ** If any data has been written (but not committed) to the log file, this
  48715. ** function moves the write-pointer back to the start of the transaction.
  48716. **
  48717. ** Additionally, the callback function is invoked for each frame written
  48718. ** to the WAL since the start of the transaction. If the callback returns
  48719. ** other than SQLITE_OK, it is not invoked again and the error code is
  48720. ** returned to the caller.
  48721. **
  48722. ** Otherwise, if the callback function does not return an error, this
  48723. ** function returns SQLITE_OK.
  48724. */
  48725. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  48726. int rc = SQLITE_OK;
  48727. if( ALWAYS(pWal->writeLock) ){
  48728. Pgno iMax = pWal->hdr.mxFrame;
  48729. Pgno iFrame;
  48730. /* Restore the clients cache of the wal-index header to the state it
  48731. ** was in before the client began writing to the database.
  48732. */
  48733. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  48734. for(iFrame=pWal->hdr.mxFrame+1;
  48735. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  48736. iFrame++
  48737. ){
  48738. /* This call cannot fail. Unless the page for which the page number
  48739. ** is passed as the second argument is (a) in the cache and
  48740. ** (b) has an outstanding reference, then xUndo is either a no-op
  48741. ** (if (a) is false) or simply expels the page from the cache (if (b)
  48742. ** is false).
  48743. **
  48744. ** If the upper layer is doing a rollback, it is guaranteed that there
  48745. ** are no outstanding references to any page other than page 1. And
  48746. ** page 1 is never written to the log until the transaction is
  48747. ** committed. As a result, the call to xUndo may not fail.
  48748. */
  48749. assert( walFramePgno(pWal, iFrame)!=1 );
  48750. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  48751. }
  48752. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  48753. }
  48754. return rc;
  48755. }
  48756. /*
  48757. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  48758. ** values. This function populates the array with values required to
  48759. ** "rollback" the write position of the WAL handle back to the current
  48760. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  48761. */
  48762. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  48763. assert( pWal->writeLock );
  48764. aWalData[0] = pWal->hdr.mxFrame;
  48765. aWalData[1] = pWal->hdr.aFrameCksum[0];
  48766. aWalData[2] = pWal->hdr.aFrameCksum[1];
  48767. aWalData[3] = pWal->nCkpt;
  48768. }
  48769. /*
  48770. ** Move the write position of the WAL back to the point identified by
  48771. ** the values in the aWalData[] array. aWalData must point to an array
  48772. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  48773. ** by a call to WalSavepoint().
  48774. */
  48775. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  48776. int rc = SQLITE_OK;
  48777. assert( pWal->writeLock );
  48778. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  48779. if( aWalData[3]!=pWal->nCkpt ){
  48780. /* This savepoint was opened immediately after the write-transaction
  48781. ** was started. Right after that, the writer decided to wrap around
  48782. ** to the start of the log. Update the savepoint values to match.
  48783. */
  48784. aWalData[0] = 0;
  48785. aWalData[3] = pWal->nCkpt;
  48786. }
  48787. if( aWalData[0]<pWal->hdr.mxFrame ){
  48788. pWal->hdr.mxFrame = aWalData[0];
  48789. pWal->hdr.aFrameCksum[0] = aWalData[1];
  48790. pWal->hdr.aFrameCksum[1] = aWalData[2];
  48791. walCleanupHash(pWal);
  48792. }
  48793. return rc;
  48794. }
  48795. /*
  48796. ** This function is called just before writing a set of frames to the log
  48797. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  48798. ** to the current log file, it is possible to overwrite the start of the
  48799. ** existing log file with the new frames (i.e. "reset" the log). If so,
  48800. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  48801. ** unchanged.
  48802. **
  48803. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  48804. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  48805. ** if an error occurs.
  48806. */
  48807. static int walRestartLog(Wal *pWal){
  48808. int rc = SQLITE_OK;
  48809. int cnt;
  48810. if( pWal->readLock==0 ){
  48811. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  48812. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  48813. if( pInfo->nBackfill>0 ){
  48814. u32 salt1;
  48815. sqlite3_randomness(4, &salt1);
  48816. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1, 0);
  48817. if( rc==SQLITE_OK ){
  48818. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  48819. ** readers are currently using the WAL), then the transactions
  48820. ** frames will overwrite the start of the existing log. Update the
  48821. ** wal-index header to reflect this.
  48822. **
  48823. ** In theory it would be Ok to update the cache of the header only
  48824. ** at this point. But updating the actual wal-index header is also
  48825. ** safe and means there is no special case for sqlite3WalUndo()
  48826. ** to handle if this transaction is rolled back. */
  48827. walRestartHdr(pWal, salt1);
  48828. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48829. }else if( rc!=SQLITE_BUSY ){
  48830. return rc;
  48831. }
  48832. }
  48833. walUnlockShared(pWal, WAL_READ_LOCK(0));
  48834. pWal->readLock = -1;
  48835. cnt = 0;
  48836. do{
  48837. int notUsed;
  48838. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  48839. }while( rc==WAL_RETRY );
  48840. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  48841. testcase( (rc&0xff)==SQLITE_IOERR );
  48842. testcase( rc==SQLITE_PROTOCOL );
  48843. testcase( rc==SQLITE_OK );
  48844. }
  48845. return rc;
  48846. }
  48847. /*
  48848. ** Information about the current state of the WAL file and where
  48849. ** the next fsync should occur - passed from sqlite3WalFrames() into
  48850. ** walWriteToLog().
  48851. */
  48852. typedef struct WalWriter {
  48853. Wal *pWal; /* The complete WAL information */
  48854. sqlite3_file *pFd; /* The WAL file to which we write */
  48855. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  48856. int syncFlags; /* Flags for the fsync */
  48857. int szPage; /* Size of one page */
  48858. } WalWriter;
  48859. /*
  48860. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  48861. ** Do a sync when crossing the p->iSyncPoint boundary.
  48862. **
  48863. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  48864. ** first write the part before iSyncPoint, then sync, then write the
  48865. ** rest.
  48866. */
  48867. static int walWriteToLog(
  48868. WalWriter *p, /* WAL to write to */
  48869. void *pContent, /* Content to be written */
  48870. int iAmt, /* Number of bytes to write */
  48871. sqlite3_int64 iOffset /* Start writing at this offset */
  48872. ){
  48873. int rc;
  48874. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  48875. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  48876. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  48877. if( rc ) return rc;
  48878. iOffset += iFirstAmt;
  48879. iAmt -= iFirstAmt;
  48880. pContent = (void*)(iFirstAmt + (char*)pContent);
  48881. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  48882. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  48883. if( iAmt==0 || rc ) return rc;
  48884. }
  48885. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  48886. return rc;
  48887. }
  48888. /*
  48889. ** Write out a single frame of the WAL
  48890. */
  48891. static int walWriteOneFrame(
  48892. WalWriter *p, /* Where to write the frame */
  48893. PgHdr *pPage, /* The page of the frame to be written */
  48894. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  48895. sqlite3_int64 iOffset /* Byte offset at which to write */
  48896. ){
  48897. int rc; /* Result code from subfunctions */
  48898. void *pData; /* Data actually written */
  48899. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  48900. #if defined(SQLITE_HAS_CODEC)
  48901. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  48902. #else
  48903. pData = pPage->pData;
  48904. #endif
  48905. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  48906. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  48907. if( rc ) return rc;
  48908. /* Write the page data */
  48909. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  48910. return rc;
  48911. }
  48912. /*
  48913. ** Write a set of frames to the log. The caller must hold the write-lock
  48914. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  48915. */
  48916. SQLITE_PRIVATE int sqlite3WalFrames(
  48917. Wal *pWal, /* Wal handle to write to */
  48918. int szPage, /* Database page-size in bytes */
  48919. PgHdr *pList, /* List of dirty pages to write */
  48920. Pgno nTruncate, /* Database size after this commit */
  48921. int isCommit, /* True if this is a commit */
  48922. int sync_flags /* Flags to pass to OsSync() (or 0) */
  48923. ){
  48924. int rc; /* Used to catch return codes */
  48925. u32 iFrame; /* Next frame address */
  48926. PgHdr *p; /* Iterator to run through pList with. */
  48927. PgHdr *pLast = 0; /* Last frame in list */
  48928. int nExtra = 0; /* Number of extra copies of last page */
  48929. int szFrame; /* The size of a single frame */
  48930. i64 iOffset; /* Next byte to write in WAL file */
  48931. WalWriter w; /* The writer */
  48932. assert( pList );
  48933. assert( pWal->writeLock );
  48934. /* If this frame set completes a transaction, then nTruncate>0. If
  48935. ** nTruncate==0 then this frame set does not complete the transaction. */
  48936. assert( (isCommit!=0)==(nTruncate!=0) );
  48937. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  48938. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  48939. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  48940. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  48941. }
  48942. #endif
  48943. /* See if it is possible to write these frames into the start of the
  48944. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  48945. */
  48946. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  48947. return rc;
  48948. }
  48949. /* If this is the first frame written into the log, write the WAL
  48950. ** header to the start of the WAL file. See comments at the top of
  48951. ** this source file for a description of the WAL header format.
  48952. */
  48953. iFrame = pWal->hdr.mxFrame;
  48954. if( iFrame==0 ){
  48955. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  48956. u32 aCksum[2]; /* Checksum for wal-header */
  48957. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  48958. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  48959. sqlite3Put4byte(&aWalHdr[8], szPage);
  48960. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  48961. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  48962. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  48963. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  48964. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  48965. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  48966. pWal->szPage = szPage;
  48967. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  48968. pWal->hdr.aFrameCksum[0] = aCksum[0];
  48969. pWal->hdr.aFrameCksum[1] = aCksum[1];
  48970. pWal->truncateOnCommit = 1;
  48971. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  48972. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  48973. if( rc!=SQLITE_OK ){
  48974. return rc;
  48975. }
  48976. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  48977. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  48978. ** an out-of-order write following a WAL restart could result in
  48979. ** database corruption. See the ticket:
  48980. **
  48981. ** http://localhost:591/sqlite/info/ff5be73dee
  48982. */
  48983. if( pWal->syncHeader && sync_flags ){
  48984. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  48985. if( rc ) return rc;
  48986. }
  48987. }
  48988. assert( (int)pWal->szPage==szPage );
  48989. /* Setup information needed to write frames into the WAL */
  48990. w.pWal = pWal;
  48991. w.pFd = pWal->pWalFd;
  48992. w.iSyncPoint = 0;
  48993. w.syncFlags = sync_flags;
  48994. w.szPage = szPage;
  48995. iOffset = walFrameOffset(iFrame+1, szPage);
  48996. szFrame = szPage + WAL_FRAME_HDRSIZE;
  48997. /* Write all frames into the log file exactly once */
  48998. for(p=pList; p; p=p->pDirty){
  48999. int nDbSize; /* 0 normally. Positive == commit flag */
  49000. iFrame++;
  49001. assert( iOffset==walFrameOffset(iFrame, szPage) );
  49002. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  49003. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  49004. if( rc ) return rc;
  49005. pLast = p;
  49006. iOffset += szFrame;
  49007. }
  49008. /* If this is the end of a transaction, then we might need to pad
  49009. ** the transaction and/or sync the WAL file.
  49010. **
  49011. ** Padding and syncing only occur if this set of frames complete a
  49012. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  49013. ** or synchronous==OFF, then no padding or syncing are needed.
  49014. **
  49015. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  49016. ** needed and only the sync is done. If padding is needed, then the
  49017. ** final frame is repeated (with its commit mark) until the next sector
  49018. ** boundary is crossed. Only the part of the WAL prior to the last
  49019. ** sector boundary is synced; the part of the last frame that extends
  49020. ** past the sector boundary is written after the sync.
  49021. */
  49022. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  49023. if( pWal->padToSectorBoundary ){
  49024. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  49025. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  49026. while( iOffset<w.iSyncPoint ){
  49027. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  49028. if( rc ) return rc;
  49029. iOffset += szFrame;
  49030. nExtra++;
  49031. }
  49032. }else{
  49033. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  49034. }
  49035. }
  49036. /* If this frame set completes the first transaction in the WAL and
  49037. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  49038. ** journal size limit, if possible.
  49039. */
  49040. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  49041. i64 sz = pWal->mxWalSize;
  49042. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  49043. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  49044. }
  49045. walLimitSize(pWal, sz);
  49046. pWal->truncateOnCommit = 0;
  49047. }
  49048. /* Append data to the wal-index. It is not necessary to lock the
  49049. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  49050. ** guarantees that there are no other writers, and no data that may
  49051. ** be in use by existing readers is being overwritten.
  49052. */
  49053. iFrame = pWal->hdr.mxFrame;
  49054. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  49055. iFrame++;
  49056. rc = walIndexAppend(pWal, iFrame, p->pgno);
  49057. }
  49058. while( rc==SQLITE_OK && nExtra>0 ){
  49059. iFrame++;
  49060. nExtra--;
  49061. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  49062. }
  49063. if( rc==SQLITE_OK ){
  49064. /* Update the private copy of the header. */
  49065. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  49066. testcase( szPage<=32768 );
  49067. testcase( szPage>=65536 );
  49068. pWal->hdr.mxFrame = iFrame;
  49069. if( isCommit ){
  49070. pWal->hdr.iChange++;
  49071. pWal->hdr.nPage = nTruncate;
  49072. }
  49073. /* If this is a commit, update the wal-index header too. */
  49074. if( isCommit ){
  49075. walIndexWriteHdr(pWal);
  49076. pWal->iCallback = iFrame;
  49077. }
  49078. }
  49079. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  49080. return rc;
  49081. }
  49082. /*
  49083. ** This routine is called to implement sqlite3_wal_checkpoint() and
  49084. ** related interfaces.
  49085. **
  49086. ** Obtain a CHECKPOINT lock and then backfill as much information as
  49087. ** we can from WAL into the database.
  49088. **
  49089. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  49090. ** callback. In this case this function runs a blocking checkpoint.
  49091. */
  49092. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  49093. Wal *pWal, /* Wal connection */
  49094. int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
  49095. int (*xBusy)(void*), /* Function to call when busy */
  49096. void *pBusyArg, /* Context argument for xBusyHandler */
  49097. int sync_flags, /* Flags to sync db file with (or 0) */
  49098. int nBuf, /* Size of temporary buffer */
  49099. u8 *zBuf, /* Temporary buffer to use */
  49100. int *pnLog, /* OUT: Number of frames in WAL */
  49101. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  49102. ){
  49103. int rc; /* Return code */
  49104. int isChanged = 0; /* True if a new wal-index header is loaded */
  49105. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  49106. int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
  49107. assert( pWal->ckptLock==0 );
  49108. assert( pWal->writeLock==0 );
  49109. /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
  49110. ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
  49111. assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
  49112. if( pWal->readOnly ) return SQLITE_READONLY;
  49113. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  49114. /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
  49115. ** "checkpoint" lock on the database file. */
  49116. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1, 0);
  49117. if( rc ){
  49118. /* EVIDENCE-OF: R-10421-19736 If any other process is running a
  49119. ** checkpoint operation at the same time, the lock cannot be obtained and
  49120. ** SQLITE_BUSY is returned.
  49121. ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
  49122. ** it will not be invoked in this case.
  49123. */
  49124. testcase( rc==SQLITE_BUSY );
  49125. testcase( xBusy!=0 );
  49126. return rc;
  49127. }
  49128. pWal->ckptLock = 1;
  49129. /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
  49130. ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
  49131. ** file.
  49132. **
  49133. ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
  49134. ** immediately, and a busy-handler is configured, it is invoked and the
  49135. ** writer lock retried until either the busy-handler returns 0 or the
  49136. ** lock is successfully obtained.
  49137. */
  49138. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  49139. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  49140. if( rc==SQLITE_OK ){
  49141. pWal->writeLock = 1;
  49142. }else if( rc==SQLITE_BUSY ){
  49143. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  49144. xBusy2 = 0;
  49145. rc = SQLITE_OK;
  49146. }
  49147. }
  49148. /* Read the wal-index header. */
  49149. if( rc==SQLITE_OK ){
  49150. rc = walIndexReadHdr(pWal, &isChanged);
  49151. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  49152. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  49153. }
  49154. }
  49155. /* Copy data from the log to the database file. */
  49156. if( rc==SQLITE_OK ){
  49157. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  49158. rc = SQLITE_CORRUPT_BKPT;
  49159. }else{
  49160. rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
  49161. }
  49162. /* If no error occurred, set the output variables. */
  49163. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  49164. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  49165. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  49166. }
  49167. }
  49168. if( isChanged ){
  49169. /* If a new wal-index header was loaded before the checkpoint was
  49170. ** performed, then the pager-cache associated with pWal is now
  49171. ** out of date. So zero the cached wal-index header to ensure that
  49172. ** next time the pager opens a snapshot on this database it knows that
  49173. ** the cache needs to be reset.
  49174. */
  49175. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  49176. }
  49177. /* Release the locks. */
  49178. sqlite3WalEndWriteTransaction(pWal);
  49179. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  49180. pWal->ckptLock = 0;
  49181. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  49182. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  49183. }
  49184. /* Return the value to pass to a sqlite3_wal_hook callback, the
  49185. ** number of frames in the WAL at the point of the last commit since
  49186. ** sqlite3WalCallback() was called. If no commits have occurred since
  49187. ** the last call, then return 0.
  49188. */
  49189. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  49190. u32 ret = 0;
  49191. if( pWal ){
  49192. ret = pWal->iCallback;
  49193. pWal->iCallback = 0;
  49194. }
  49195. return (int)ret;
  49196. }
  49197. /*
  49198. ** This function is called to change the WAL subsystem into or out
  49199. ** of locking_mode=EXCLUSIVE.
  49200. **
  49201. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  49202. ** into locking_mode=NORMAL. This means that we must acquire a lock
  49203. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  49204. ** or if the acquisition of the lock fails, then return 0. If the
  49205. ** transition out of exclusive-mode is successful, return 1. This
  49206. ** operation must occur while the pager is still holding the exclusive
  49207. ** lock on the main database file.
  49208. **
  49209. ** If op is one, then change from locking_mode=NORMAL into
  49210. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  49211. ** be released. Return 1 if the transition is made and 0 if the
  49212. ** WAL is already in exclusive-locking mode - meaning that this
  49213. ** routine is a no-op. The pager must already hold the exclusive lock
  49214. ** on the main database file before invoking this operation.
  49215. **
  49216. ** If op is negative, then do a dry-run of the op==1 case but do
  49217. ** not actually change anything. The pager uses this to see if it
  49218. ** should acquire the database exclusive lock prior to invoking
  49219. ** the op==1 case.
  49220. */
  49221. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  49222. int rc;
  49223. assert( pWal->writeLock==0 );
  49224. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  49225. /* pWal->readLock is usually set, but might be -1 if there was a
  49226. ** prior error while attempting to acquire are read-lock. This cannot
  49227. ** happen if the connection is actually in exclusive mode (as no xShmLock
  49228. ** locks are taken in this case). Nor should the pager attempt to
  49229. ** upgrade to exclusive-mode following such an error.
  49230. */
  49231. assert( pWal->readLock>=0 || pWal->lockError );
  49232. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  49233. if( op==0 ){
  49234. if( pWal->exclusiveMode ){
  49235. pWal->exclusiveMode = 0;
  49236. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  49237. pWal->exclusiveMode = 1;
  49238. }
  49239. rc = pWal->exclusiveMode==0;
  49240. }else{
  49241. /* Already in locking_mode=NORMAL */
  49242. rc = 0;
  49243. }
  49244. }else if( op>0 ){
  49245. assert( pWal->exclusiveMode==0 );
  49246. assert( pWal->readLock>=0 );
  49247. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  49248. pWal->exclusiveMode = 1;
  49249. rc = 1;
  49250. }else{
  49251. rc = pWal->exclusiveMode==0;
  49252. }
  49253. return rc;
  49254. }
  49255. /*
  49256. ** Return true if the argument is non-NULL and the WAL module is using
  49257. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  49258. ** WAL module is using shared-memory, return false.
  49259. */
  49260. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  49261. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  49262. }
  49263. #ifdef SQLITE_ENABLE_ZIPVFS
  49264. /*
  49265. ** If the argument is not NULL, it points to a Wal object that holds a
  49266. ** read-lock. This function returns the database page-size if it is known,
  49267. ** or zero if it is not (or if pWal is NULL).
  49268. */
  49269. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  49270. assert( pWal==0 || pWal->readLock>=0 );
  49271. return (pWal ? pWal->szPage : 0);
  49272. }
  49273. #endif
  49274. #endif /* #ifndef SQLITE_OMIT_WAL */
  49275. /************** End of wal.c *************************************************/
  49276. /************** Begin file btmutex.c *****************************************/
  49277. /*
  49278. ** 2007 August 27
  49279. **
  49280. ** The author disclaims copyright to this source code. In place of
  49281. ** a legal notice, here is a blessing:
  49282. **
  49283. ** May you do good and not evil.
  49284. ** May you find forgiveness for yourself and forgive others.
  49285. ** May you share freely, never taking more than you give.
  49286. **
  49287. *************************************************************************
  49288. **
  49289. ** This file contains code used to implement mutexes on Btree objects.
  49290. ** This code really belongs in btree.c. But btree.c is getting too
  49291. ** big and we want to break it down some. This packaged seemed like
  49292. ** a good breakout.
  49293. */
  49294. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  49295. /************** Begin file btreeInt.h ****************************************/
  49296. /*
  49297. ** 2004 April 6
  49298. **
  49299. ** The author disclaims copyright to this source code. In place of
  49300. ** a legal notice, here is a blessing:
  49301. **
  49302. ** May you do good and not evil.
  49303. ** May you find forgiveness for yourself and forgive others.
  49304. ** May you share freely, never taking more than you give.
  49305. **
  49306. *************************************************************************
  49307. ** This file implements an external (disk-based) database using BTrees.
  49308. ** For a detailed discussion of BTrees, refer to
  49309. **
  49310. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  49311. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  49312. ** Publishing Company, Reading, Massachusetts.
  49313. **
  49314. ** The basic idea is that each page of the file contains N database
  49315. ** entries and N+1 pointers to subpages.
  49316. **
  49317. ** ----------------------------------------------------------------
  49318. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  49319. ** ----------------------------------------------------------------
  49320. **
  49321. ** All of the keys on the page that Ptr(0) points to have values less
  49322. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  49323. ** values greater than Key(0) and less than Key(1). All of the keys
  49324. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  49325. ** so forth.
  49326. **
  49327. ** Finding a particular key requires reading O(log(M)) pages from the
  49328. ** disk where M is the number of entries in the tree.
  49329. **
  49330. ** In this implementation, a single file can hold one or more separate
  49331. ** BTrees. Each BTree is identified by the index of its root page. The
  49332. ** key and data for any entry are combined to form the "payload". A
  49333. ** fixed amount of payload can be carried directly on the database
  49334. ** page. If the payload is larger than the preset amount then surplus
  49335. ** bytes are stored on overflow pages. The payload for an entry
  49336. ** and the preceding pointer are combined to form a "Cell". Each
  49337. ** page has a small header which contains the Ptr(N) pointer and other
  49338. ** information such as the size of key and data.
  49339. **
  49340. ** FORMAT DETAILS
  49341. **
  49342. ** The file is divided into pages. The first page is called page 1,
  49343. ** the second is page 2, and so forth. A page number of zero indicates
  49344. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  49345. ** Each page can be either a btree page, a freelist page, an overflow
  49346. ** page, or a pointer-map page.
  49347. **
  49348. ** The first page is always a btree page. The first 100 bytes of the first
  49349. ** page contain a special header (the "file header") that describes the file.
  49350. ** The format of the file header is as follows:
  49351. **
  49352. ** OFFSET SIZE DESCRIPTION
  49353. ** 0 16 Header string: "SQLite format 3\000"
  49354. ** 16 2 Page size in bytes. (1 means 65536)
  49355. ** 18 1 File format write version
  49356. ** 19 1 File format read version
  49357. ** 20 1 Bytes of unused space at the end of each page
  49358. ** 21 1 Max embedded payload fraction (must be 64)
  49359. ** 22 1 Min embedded payload fraction (must be 32)
  49360. ** 23 1 Min leaf payload fraction (must be 32)
  49361. ** 24 4 File change counter
  49362. ** 28 4 Reserved for future use
  49363. ** 32 4 First freelist page
  49364. ** 36 4 Number of freelist pages in the file
  49365. ** 40 60 15 4-byte meta values passed to higher layers
  49366. **
  49367. ** 40 4 Schema cookie
  49368. ** 44 4 File format of schema layer
  49369. ** 48 4 Size of page cache
  49370. ** 52 4 Largest root-page (auto/incr_vacuum)
  49371. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  49372. ** 60 4 User version
  49373. ** 64 4 Incremental vacuum mode
  49374. ** 68 4 Application-ID
  49375. ** 72 20 unused
  49376. ** 92 4 The version-valid-for number
  49377. ** 96 4 SQLITE_VERSION_NUMBER
  49378. **
  49379. ** All of the integer values are big-endian (most significant byte first).
  49380. **
  49381. ** The file change counter is incremented when the database is changed
  49382. ** This counter allows other processes to know when the file has changed
  49383. ** and thus when they need to flush their cache.
  49384. **
  49385. ** The max embedded payload fraction is the amount of the total usable
  49386. ** space in a page that can be consumed by a single cell for standard
  49387. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  49388. ** is to limit the maximum cell size so that at least 4 cells will fit
  49389. ** on one page. Thus the default max embedded payload fraction is 64.
  49390. **
  49391. ** If the payload for a cell is larger than the max payload, then extra
  49392. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  49393. ** as many bytes as possible are moved into the overflow pages without letting
  49394. ** the cell size drop below the min embedded payload fraction.
  49395. **
  49396. ** The min leaf payload fraction is like the min embedded payload fraction
  49397. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  49398. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  49399. ** not specified in the header.
  49400. **
  49401. ** Each btree pages is divided into three sections: The header, the
  49402. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  49403. ** file header that occurs before the page header.
  49404. **
  49405. ** |----------------|
  49406. ** | file header | 100 bytes. Page 1 only.
  49407. ** |----------------|
  49408. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  49409. ** |----------------|
  49410. ** | cell pointer | | 2 bytes per cell. Sorted order.
  49411. ** | array | | Grows downward
  49412. ** | | v
  49413. ** |----------------|
  49414. ** | unallocated |
  49415. ** | space |
  49416. ** |----------------| ^ Grows upwards
  49417. ** | cell content | | Arbitrary order interspersed with freeblocks.
  49418. ** | area | | and free space fragments.
  49419. ** |----------------|
  49420. **
  49421. ** The page headers looks like this:
  49422. **
  49423. ** OFFSET SIZE DESCRIPTION
  49424. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  49425. ** 1 2 byte offset to the first freeblock
  49426. ** 3 2 number of cells on this page
  49427. ** 5 2 first byte of the cell content area
  49428. ** 7 1 number of fragmented free bytes
  49429. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  49430. **
  49431. ** The flags define the format of this btree page. The leaf flag means that
  49432. ** this page has no children. The zerodata flag means that this page carries
  49433. ** only keys and no data. The intkey flag means that the key is an integer
  49434. ** which is stored in the key size entry of the cell header rather than in
  49435. ** the payload area.
  49436. **
  49437. ** The cell pointer array begins on the first byte after the page header.
  49438. ** The cell pointer array contains zero or more 2-byte numbers which are
  49439. ** offsets from the beginning of the page to the cell content in the cell
  49440. ** content area. The cell pointers occur in sorted order. The system strives
  49441. ** to keep free space after the last cell pointer so that new cells can
  49442. ** be easily added without having to defragment the page.
  49443. **
  49444. ** Cell content is stored at the very end of the page and grows toward the
  49445. ** beginning of the page.
  49446. **
  49447. ** Unused space within the cell content area is collected into a linked list of
  49448. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  49449. ** to the first freeblock is given in the header. Freeblocks occur in
  49450. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  49451. ** any group of 3 or fewer unused bytes in the cell content area cannot
  49452. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  49453. ** a fragment. The total number of bytes in all fragments is recorded.
  49454. ** in the page header at offset 7.
  49455. **
  49456. ** SIZE DESCRIPTION
  49457. ** 2 Byte offset of the next freeblock
  49458. ** 2 Bytes in this freeblock
  49459. **
  49460. ** Cells are of variable length. Cells are stored in the cell content area at
  49461. ** the end of the page. Pointers to the cells are in the cell pointer array
  49462. ** that immediately follows the page header. Cells is not necessarily
  49463. ** contiguous or in order, but cell pointers are contiguous and in order.
  49464. **
  49465. ** Cell content makes use of variable length integers. A variable
  49466. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  49467. ** byte are used. The integer consists of all bytes that have bit 8 set and
  49468. ** the first byte with bit 8 clear. The most significant byte of the integer
  49469. ** appears first. A variable-length integer may not be more than 9 bytes long.
  49470. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  49471. ** allows a 64-bit integer to be encoded in 9 bytes.
  49472. **
  49473. ** 0x00 becomes 0x00000000
  49474. ** 0x7f becomes 0x0000007f
  49475. ** 0x81 0x00 becomes 0x00000080
  49476. ** 0x82 0x00 becomes 0x00000100
  49477. ** 0x80 0x7f becomes 0x0000007f
  49478. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  49479. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  49480. **
  49481. ** Variable length integers are used for rowids and to hold the number of
  49482. ** bytes of key and data in a btree cell.
  49483. **
  49484. ** The content of a cell looks like this:
  49485. **
  49486. ** SIZE DESCRIPTION
  49487. ** 4 Page number of the left child. Omitted if leaf flag is set.
  49488. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  49489. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  49490. ** * Payload
  49491. ** 4 First page of the overflow chain. Omitted if no overflow
  49492. **
  49493. ** Overflow pages form a linked list. Each page except the last is completely
  49494. ** filled with data (pagesize - 4 bytes). The last page can have as little
  49495. ** as 1 byte of data.
  49496. **
  49497. ** SIZE DESCRIPTION
  49498. ** 4 Page number of next overflow page
  49499. ** * Data
  49500. **
  49501. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  49502. ** file header points to the first in a linked list of trunk page. Each trunk
  49503. ** page points to multiple leaf pages. The content of a leaf page is
  49504. ** unspecified. A trunk page looks like this:
  49505. **
  49506. ** SIZE DESCRIPTION
  49507. ** 4 Page number of next trunk page
  49508. ** 4 Number of leaf pointers on this page
  49509. ** * zero or more pages numbers of leaves
  49510. */
  49511. /* #include "sqliteInt.h" */
  49512. /* The following value is the maximum cell size assuming a maximum page
  49513. ** size give above.
  49514. */
  49515. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  49516. /* The maximum number of cells on a single page of the database. This
  49517. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  49518. ** plus 2 bytes for the index to the cell in the page header). Such
  49519. ** small cells will be rare, but they are possible.
  49520. */
  49521. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  49522. /* Forward declarations */
  49523. typedef struct MemPage MemPage;
  49524. typedef struct BtLock BtLock;
  49525. typedef struct CellInfo CellInfo;
  49526. /*
  49527. ** This is a magic string that appears at the beginning of every
  49528. ** SQLite database in order to identify the file as a real database.
  49529. **
  49530. ** You can change this value at compile-time by specifying a
  49531. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  49532. ** header must be exactly 16 bytes including the zero-terminator so
  49533. ** the string itself should be 15 characters long. If you change
  49534. ** the header, then your custom library will not be able to read
  49535. ** databases generated by the standard tools and the standard tools
  49536. ** will not be able to read databases created by your custom library.
  49537. */
  49538. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  49539. # define SQLITE_FILE_HEADER "SQLite format 3"
  49540. #endif
  49541. /*
  49542. ** Page type flags. An ORed combination of these flags appear as the
  49543. ** first byte of on-disk image of every BTree page.
  49544. */
  49545. #define PTF_INTKEY 0x01
  49546. #define PTF_ZERODATA 0x02
  49547. #define PTF_LEAFDATA 0x04
  49548. #define PTF_LEAF 0x08
  49549. /*
  49550. ** As each page of the file is loaded into memory, an instance of the following
  49551. ** structure is appended and initialized to zero. This structure stores
  49552. ** information about the page that is decoded from the raw file page.
  49553. **
  49554. ** The pParent field points back to the parent page. This allows us to
  49555. ** walk up the BTree from any leaf to the root. Care must be taken to
  49556. ** unref() the parent page pointer when this page is no longer referenced.
  49557. ** The pageDestructor() routine handles that chore.
  49558. **
  49559. ** Access to all fields of this structure is controlled by the mutex
  49560. ** stored in MemPage.pBt->mutex.
  49561. */
  49562. struct MemPage {
  49563. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  49564. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  49565. u8 intKey; /* True if table b-trees. False for index b-trees */
  49566. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  49567. u8 noPayload; /* True if internal intKey page (thus w/o data) */
  49568. u8 leaf; /* True if a leaf page */
  49569. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  49570. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  49571. u8 max1bytePayload; /* min(maxLocal,127) */
  49572. u8 bBusy; /* Prevent endless loops on corrupt database files */
  49573. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  49574. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  49575. u16 cellOffset; /* Index in aData of first cell pointer */
  49576. u16 nFree; /* Number of free bytes on the page */
  49577. u16 nCell; /* Number of cells on this page, local and ovfl */
  49578. u16 maskPage; /* Mask for page offset */
  49579. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  49580. ** non-overflow cell */
  49581. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  49582. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  49583. u8 *aData; /* Pointer to disk image of the page data */
  49584. u8 *aDataEnd; /* One byte past the end of usable data */
  49585. u8 *aCellIdx; /* The cell index area */
  49586. u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
  49587. DbPage *pDbPage; /* Pager page handle */
  49588. u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
  49589. void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
  49590. Pgno pgno; /* Page number for this page */
  49591. };
  49592. /*
  49593. ** The in-memory image of a disk page has the auxiliary information appended
  49594. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  49595. ** that extra information.
  49596. */
  49597. #define EXTRA_SIZE sizeof(MemPage)
  49598. /*
  49599. ** A linked list of the following structures is stored at BtShared.pLock.
  49600. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  49601. ** is opened on the table with root page BtShared.iTable. Locks are removed
  49602. ** from this list when a transaction is committed or rolled back, or when
  49603. ** a btree handle is closed.
  49604. */
  49605. struct BtLock {
  49606. Btree *pBtree; /* Btree handle holding this lock */
  49607. Pgno iTable; /* Root page of table */
  49608. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  49609. BtLock *pNext; /* Next in BtShared.pLock list */
  49610. };
  49611. /* Candidate values for BtLock.eLock */
  49612. #define READ_LOCK 1
  49613. #define WRITE_LOCK 2
  49614. /* A Btree handle
  49615. **
  49616. ** A database connection contains a pointer to an instance of
  49617. ** this object for every database file that it has open. This structure
  49618. ** is opaque to the database connection. The database connection cannot
  49619. ** see the internals of this structure and only deals with pointers to
  49620. ** this structure.
  49621. **
  49622. ** For some database files, the same underlying database cache might be
  49623. ** shared between multiple connections. In that case, each connection
  49624. ** has it own instance of this object. But each instance of this object
  49625. ** points to the same BtShared object. The database cache and the
  49626. ** schema associated with the database file are all contained within
  49627. ** the BtShared object.
  49628. **
  49629. ** All fields in this structure are accessed under sqlite3.mutex.
  49630. ** The pBt pointer itself may not be changed while there exists cursors
  49631. ** in the referenced BtShared that point back to this Btree since those
  49632. ** cursors have to go through this Btree to find their BtShared and
  49633. ** they often do so without holding sqlite3.mutex.
  49634. */
  49635. struct Btree {
  49636. sqlite3 *db; /* The database connection holding this btree */
  49637. BtShared *pBt; /* Sharable content of this btree */
  49638. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  49639. u8 sharable; /* True if we can share pBt with another db */
  49640. u8 locked; /* True if db currently has pBt locked */
  49641. u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
  49642. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  49643. int nBackup; /* Number of backup operations reading this btree */
  49644. u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
  49645. Btree *pNext; /* List of other sharable Btrees from the same db */
  49646. Btree *pPrev; /* Back pointer of the same list */
  49647. #ifndef SQLITE_OMIT_SHARED_CACHE
  49648. BtLock lock; /* Object used to lock page 1 */
  49649. #endif
  49650. };
  49651. /*
  49652. ** Btree.inTrans may take one of the following values.
  49653. **
  49654. ** If the shared-data extension is enabled, there may be multiple users
  49655. ** of the Btree structure. At most one of these may open a write transaction,
  49656. ** but any number may have active read transactions.
  49657. */
  49658. #define TRANS_NONE 0
  49659. #define TRANS_READ 1
  49660. #define TRANS_WRITE 2
  49661. /*
  49662. ** An instance of this object represents a single database file.
  49663. **
  49664. ** A single database file can be in use at the same time by two
  49665. ** or more database connections. When two or more connections are
  49666. ** sharing the same database file, each connection has it own
  49667. ** private Btree object for the file and each of those Btrees points
  49668. ** to this one BtShared object. BtShared.nRef is the number of
  49669. ** connections currently sharing this database file.
  49670. **
  49671. ** Fields in this structure are accessed under the BtShared.mutex
  49672. ** mutex, except for nRef and pNext which are accessed under the
  49673. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  49674. ** may not be modified once it is initially set as long as nRef>0.
  49675. ** The pSchema field may be set once under BtShared.mutex and
  49676. ** thereafter is unchanged as long as nRef>0.
  49677. **
  49678. ** isPending:
  49679. **
  49680. ** If a BtShared client fails to obtain a write-lock on a database
  49681. ** table (because there exists one or more read-locks on the table),
  49682. ** the shared-cache enters 'pending-lock' state and isPending is
  49683. ** set to true.
  49684. **
  49685. ** The shared-cache leaves the 'pending lock' state when either of
  49686. ** the following occur:
  49687. **
  49688. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  49689. ** 2) The number of locks held by other connections drops to zero.
  49690. **
  49691. ** while in the 'pending-lock' state, no connection may start a new
  49692. ** transaction.
  49693. **
  49694. ** This feature is included to help prevent writer-starvation.
  49695. */
  49696. struct BtShared {
  49697. Pager *pPager; /* The page cache */
  49698. sqlite3 *db; /* Database connection currently using this Btree */
  49699. BtCursor *pCursor; /* A list of all open cursors */
  49700. MemPage *pPage1; /* First page of the database */
  49701. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  49702. #ifndef SQLITE_OMIT_AUTOVACUUM
  49703. u8 autoVacuum; /* True if auto-vacuum is enabled */
  49704. u8 incrVacuum; /* True if incr-vacuum is enabled */
  49705. u8 bDoTruncate; /* True to truncate db on commit */
  49706. #endif
  49707. u8 inTransaction; /* Transaction state */
  49708. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  49709. #ifdef SQLITE_HAS_CODEC
  49710. u8 optimalReserve; /* Desired amount of reserved space per page */
  49711. #endif
  49712. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  49713. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  49714. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  49715. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  49716. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  49717. u32 pageSize; /* Total number of bytes on a page */
  49718. u32 usableSize; /* Number of usable bytes on each page */
  49719. int nTransaction; /* Number of open transactions (read + write) */
  49720. u32 nPage; /* Number of pages in the database */
  49721. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  49722. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  49723. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  49724. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  49725. #ifndef SQLITE_OMIT_SHARED_CACHE
  49726. int nRef; /* Number of references to this structure */
  49727. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  49728. BtLock *pLock; /* List of locks held on this shared-btree struct */
  49729. Btree *pWriter; /* Btree with currently open write transaction */
  49730. #endif
  49731. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  49732. };
  49733. /*
  49734. ** Allowed values for BtShared.btsFlags
  49735. */
  49736. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  49737. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  49738. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  49739. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  49740. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  49741. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  49742. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  49743. /*
  49744. ** An instance of the following structure is used to hold information
  49745. ** about a cell. The parseCellPtr() function fills in this structure
  49746. ** based on information extract from the raw disk page.
  49747. */
  49748. struct CellInfo {
  49749. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  49750. u8 *pPayload; /* Pointer to the start of payload */
  49751. u32 nPayload; /* Bytes of payload */
  49752. u16 nLocal; /* Amount of payload held locally, not on overflow */
  49753. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  49754. u16 nSize; /* Size of the cell content on the main b-tree page */
  49755. };
  49756. /*
  49757. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  49758. ** this will be declared corrupt. This value is calculated based on a
  49759. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  49760. ** root-node and 3 for all other internal nodes.
  49761. **
  49762. ** If a tree that appears to be taller than this is encountered, it is
  49763. ** assumed that the database is corrupt.
  49764. */
  49765. #define BTCURSOR_MAX_DEPTH 20
  49766. /*
  49767. ** A cursor is a pointer to a particular entry within a particular
  49768. ** b-tree within a database file.
  49769. **
  49770. ** The entry is identified by its MemPage and the index in
  49771. ** MemPage.aCell[] of the entry.
  49772. **
  49773. ** A single database file can be shared by two more database connections,
  49774. ** but cursors cannot be shared. Each cursor is associated with a
  49775. ** particular database connection identified BtCursor.pBtree.db.
  49776. **
  49777. ** Fields in this structure are accessed under the BtShared.mutex
  49778. ** found at self->pBt->mutex.
  49779. **
  49780. ** skipNext meaning:
  49781. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  49782. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  49783. ** eState==FAULT: Cursor fault with skipNext as error code.
  49784. */
  49785. struct BtCursor {
  49786. Btree *pBtree; /* The Btree to which this cursor belongs */
  49787. BtShared *pBt; /* The BtShared this cursor points to */
  49788. BtCursor *pNext; /* Forms a linked list of all cursors */
  49789. Pgno *aOverflow; /* Cache of overflow page locations */
  49790. CellInfo info; /* A parse of the cell we are pointing at */
  49791. i64 nKey; /* Size of pKey, or last integer key */
  49792. void *pKey; /* Saved key that was cursor last known position */
  49793. Pgno pgnoRoot; /* The root page of this tree */
  49794. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  49795. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  49796. ** Error code if eState==CURSOR_FAULT */
  49797. u8 curFlags; /* zero or more BTCF_* flags defined below */
  49798. u8 curPagerFlags; /* Flags to send to sqlite3PagerAcquire() */
  49799. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  49800. u8 hints; /* As configured by CursorSetHints() */
  49801. /* All fields above are zeroed when the cursor is allocated. See
  49802. ** sqlite3BtreeCursorZero(). Fields that follow must be manually
  49803. ** initialized. */
  49804. i8 iPage; /* Index of current page in apPage */
  49805. u8 curIntKey; /* Value of apPage[0]->intKey */
  49806. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  49807. void *padding1; /* Make object size a multiple of 16 */
  49808. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  49809. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  49810. };
  49811. /*
  49812. ** Legal values for BtCursor.curFlags
  49813. */
  49814. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  49815. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  49816. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  49817. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  49818. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  49819. #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
  49820. /*
  49821. ** Potential values for BtCursor.eState.
  49822. **
  49823. ** CURSOR_INVALID:
  49824. ** Cursor does not point to a valid entry. This can happen (for example)
  49825. ** because the table is empty or because BtreeCursorFirst() has not been
  49826. ** called.
  49827. **
  49828. ** CURSOR_VALID:
  49829. ** Cursor points to a valid entry. getPayload() etc. may be called.
  49830. **
  49831. ** CURSOR_SKIPNEXT:
  49832. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  49833. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  49834. ** operation should be a no-op.
  49835. **
  49836. ** CURSOR_REQUIRESEEK:
  49837. ** The table that this cursor was opened on still exists, but has been
  49838. ** modified since the cursor was last used. The cursor position is saved
  49839. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  49840. ** this state, restoreCursorPosition() can be called to attempt to
  49841. ** seek the cursor to the saved position.
  49842. **
  49843. ** CURSOR_FAULT:
  49844. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  49845. ** on a different connection that shares the BtShared cache with this
  49846. ** cursor. The error has left the cache in an inconsistent state.
  49847. ** Do nothing else with this cursor. Any attempt to use the cursor
  49848. ** should return the error code stored in BtCursor.skipNext
  49849. */
  49850. #define CURSOR_INVALID 0
  49851. #define CURSOR_VALID 1
  49852. #define CURSOR_SKIPNEXT 2
  49853. #define CURSOR_REQUIRESEEK 3
  49854. #define CURSOR_FAULT 4
  49855. /*
  49856. ** The database page the PENDING_BYTE occupies. This page is never used.
  49857. */
  49858. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  49859. /*
  49860. ** These macros define the location of the pointer-map entry for a
  49861. ** database page. The first argument to each is the number of usable
  49862. ** bytes on each page of the database (often 1024). The second is the
  49863. ** page number to look up in the pointer map.
  49864. **
  49865. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  49866. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  49867. ** the offset of the requested map entry.
  49868. **
  49869. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  49870. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  49871. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  49872. ** this test.
  49873. */
  49874. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  49875. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  49876. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  49877. /*
  49878. ** The pointer map is a lookup table that identifies the parent page for
  49879. ** each child page in the database file. The parent page is the page that
  49880. ** contains a pointer to the child. Every page in the database contains
  49881. ** 0 or 1 parent pages. (In this context 'database page' refers
  49882. ** to any page that is not part of the pointer map itself.) Each pointer map
  49883. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  49884. ** The PTRMAP_XXX identifiers below are the valid types.
  49885. **
  49886. ** The purpose of the pointer map is to facility moving pages from one
  49887. ** position in the file to another as part of autovacuum. When a page
  49888. ** is moved, the pointer in its parent must be updated to point to the
  49889. ** new location. The pointer map is used to locate the parent page quickly.
  49890. **
  49891. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  49892. ** used in this case.
  49893. **
  49894. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  49895. ** is not used in this case.
  49896. **
  49897. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  49898. ** overflow pages. The page number identifies the page that
  49899. ** contains the cell with a pointer to this overflow page.
  49900. **
  49901. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  49902. ** overflow pages. The page-number identifies the previous
  49903. ** page in the overflow page list.
  49904. **
  49905. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  49906. ** identifies the parent page in the btree.
  49907. */
  49908. #define PTRMAP_ROOTPAGE 1
  49909. #define PTRMAP_FREEPAGE 2
  49910. #define PTRMAP_OVERFLOW1 3
  49911. #define PTRMAP_OVERFLOW2 4
  49912. #define PTRMAP_BTREE 5
  49913. /* A bunch of assert() statements to check the transaction state variables
  49914. ** of handle p (type Btree*) are internally consistent.
  49915. */
  49916. #define btreeIntegrity(p) \
  49917. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  49918. assert( p->pBt->inTransaction>=p->inTrans );
  49919. /*
  49920. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  49921. ** if the database supports auto-vacuum or not. Because it is used
  49922. ** within an expression that is an argument to another macro
  49923. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  49924. ** So, this macro is defined instead.
  49925. */
  49926. #ifndef SQLITE_OMIT_AUTOVACUUM
  49927. #define ISAUTOVACUUM (pBt->autoVacuum)
  49928. #else
  49929. #define ISAUTOVACUUM 0
  49930. #endif
  49931. /*
  49932. ** This structure is passed around through all the sanity checking routines
  49933. ** in order to keep track of some global state information.
  49934. **
  49935. ** The aRef[] array is allocated so that there is 1 bit for each page in
  49936. ** the database. As the integrity-check proceeds, for each page used in
  49937. ** the database the corresponding bit is set. This allows integrity-check to
  49938. ** detect pages that are used twice and orphaned pages (both of which
  49939. ** indicate corruption).
  49940. */
  49941. typedef struct IntegrityCk IntegrityCk;
  49942. struct IntegrityCk {
  49943. BtShared *pBt; /* The tree being checked out */
  49944. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  49945. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  49946. Pgno nPage; /* Number of pages in the database */
  49947. int mxErr; /* Stop accumulating errors when this reaches zero */
  49948. int nErr; /* Number of messages written to zErrMsg so far */
  49949. int mallocFailed; /* A memory allocation error has occurred */
  49950. const char *zPfx; /* Error message prefix */
  49951. int v1, v2; /* Values for up to two %d fields in zPfx */
  49952. StrAccum errMsg; /* Accumulate the error message text here */
  49953. u32 *heap; /* Min-heap used for analyzing cell coverage */
  49954. };
  49955. /*
  49956. ** Routines to read or write a two- and four-byte big-endian integer values.
  49957. */
  49958. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  49959. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  49960. #define get4byte sqlite3Get4byte
  49961. #define put4byte sqlite3Put4byte
  49962. /*
  49963. ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
  49964. ** two-byte aligned address. get2bytea() is only used for accessing the
  49965. ** cell addresses in a btree header.
  49966. */
  49967. #if SQLITE_BYTEORDER==4321
  49968. # define get2byteAligned(x) (*(u16*)(x))
  49969. #elif SQLITE_BYTEORDER==1234 && GCC_VERSION>=4008000
  49970. # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
  49971. #elif SQLITE_BYTEORDER==1234 && defined(_MSC_VER) && _MSC_VER>=1300
  49972. # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
  49973. #else
  49974. # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
  49975. #endif
  49976. /************** End of btreeInt.h ********************************************/
  49977. /************** Continuing where we left off in btmutex.c ********************/
  49978. #ifndef SQLITE_OMIT_SHARED_CACHE
  49979. #if SQLITE_THREADSAFE
  49980. /*
  49981. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  49982. ** set BtShared.db to the database handle associated with p and the
  49983. ** p->locked boolean to true.
  49984. */
  49985. static void lockBtreeMutex(Btree *p){
  49986. assert( p->locked==0 );
  49987. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  49988. assert( sqlite3_mutex_held(p->db->mutex) );
  49989. sqlite3_mutex_enter(p->pBt->mutex);
  49990. p->pBt->db = p->db;
  49991. p->locked = 1;
  49992. }
  49993. /*
  49994. ** Release the BtShared mutex associated with B-Tree handle p and
  49995. ** clear the p->locked boolean.
  49996. */
  49997. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  49998. BtShared *pBt = p->pBt;
  49999. assert( p->locked==1 );
  50000. assert( sqlite3_mutex_held(pBt->mutex) );
  50001. assert( sqlite3_mutex_held(p->db->mutex) );
  50002. assert( p->db==pBt->db );
  50003. sqlite3_mutex_leave(pBt->mutex);
  50004. p->locked = 0;
  50005. }
  50006. /* Forward reference */
  50007. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  50008. /*
  50009. ** Enter a mutex on the given BTree object.
  50010. **
  50011. ** If the object is not sharable, then no mutex is ever required
  50012. ** and this routine is a no-op. The underlying mutex is non-recursive.
  50013. ** But we keep a reference count in Btree.wantToLock so the behavior
  50014. ** of this interface is recursive.
  50015. **
  50016. ** To avoid deadlocks, multiple Btrees are locked in the same order
  50017. ** by all database connections. The p->pNext is a list of other
  50018. ** Btrees belonging to the same database connection as the p Btree
  50019. ** which need to be locked after p. If we cannot get a lock on
  50020. ** p, then first unlock all of the others on p->pNext, then wait
  50021. ** for the lock to become available on p, then relock all of the
  50022. ** subsequent Btrees that desire a lock.
  50023. */
  50024. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  50025. /* Some basic sanity checking on the Btree. The list of Btrees
  50026. ** connected by pNext and pPrev should be in sorted order by
  50027. ** Btree.pBt value. All elements of the list should belong to
  50028. ** the same connection. Only shared Btrees are on the list. */
  50029. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  50030. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  50031. assert( p->pNext==0 || p->pNext->db==p->db );
  50032. assert( p->pPrev==0 || p->pPrev->db==p->db );
  50033. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  50034. /* Check for locking consistency */
  50035. assert( !p->locked || p->wantToLock>0 );
  50036. assert( p->sharable || p->wantToLock==0 );
  50037. /* We should already hold a lock on the database connection */
  50038. assert( sqlite3_mutex_held(p->db->mutex) );
  50039. /* Unless the database is sharable and unlocked, then BtShared.db
  50040. ** should already be set correctly. */
  50041. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  50042. if( !p->sharable ) return;
  50043. p->wantToLock++;
  50044. if( p->locked ) return;
  50045. btreeLockCarefully(p);
  50046. }
  50047. /* This is a helper function for sqlite3BtreeLock(). By moving
  50048. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  50049. ** into this routine, we avoid unnecessary stack pointer changes
  50050. ** and thus help the sqlite3BtreeLock() routine to run much faster
  50051. ** in the common case.
  50052. */
  50053. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  50054. Btree *pLater;
  50055. /* In most cases, we should be able to acquire the lock we
  50056. ** want without having to go through the ascending lock
  50057. ** procedure that follows. Just be sure not to block.
  50058. */
  50059. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  50060. p->pBt->db = p->db;
  50061. p->locked = 1;
  50062. return;
  50063. }
  50064. /* To avoid deadlock, first release all locks with a larger
  50065. ** BtShared address. Then acquire our lock. Then reacquire
  50066. ** the other BtShared locks that we used to hold in ascending
  50067. ** order.
  50068. */
  50069. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  50070. assert( pLater->sharable );
  50071. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  50072. assert( !pLater->locked || pLater->wantToLock>0 );
  50073. if( pLater->locked ){
  50074. unlockBtreeMutex(pLater);
  50075. }
  50076. }
  50077. lockBtreeMutex(p);
  50078. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  50079. if( pLater->wantToLock ){
  50080. lockBtreeMutex(pLater);
  50081. }
  50082. }
  50083. }
  50084. /*
  50085. ** Exit the recursive mutex on a Btree.
  50086. */
  50087. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  50088. assert( sqlite3_mutex_held(p->db->mutex) );
  50089. if( p->sharable ){
  50090. assert( p->wantToLock>0 );
  50091. p->wantToLock--;
  50092. if( p->wantToLock==0 ){
  50093. unlockBtreeMutex(p);
  50094. }
  50095. }
  50096. }
  50097. #ifndef NDEBUG
  50098. /*
  50099. ** Return true if the BtShared mutex is held on the btree, or if the
  50100. ** B-Tree is not marked as sharable.
  50101. **
  50102. ** This routine is used only from within assert() statements.
  50103. */
  50104. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  50105. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  50106. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  50107. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  50108. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  50109. return (p->sharable==0 || p->locked);
  50110. }
  50111. #endif
  50112. #ifndef SQLITE_OMIT_INCRBLOB
  50113. /*
  50114. ** Enter and leave a mutex on a Btree given a cursor owned by that
  50115. ** Btree. These entry points are used by incremental I/O and can be
  50116. ** omitted if that module is not used.
  50117. */
  50118. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  50119. sqlite3BtreeEnter(pCur->pBtree);
  50120. }
  50121. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  50122. sqlite3BtreeLeave(pCur->pBtree);
  50123. }
  50124. #endif /* SQLITE_OMIT_INCRBLOB */
  50125. /*
  50126. ** Enter the mutex on every Btree associated with a database
  50127. ** connection. This is needed (for example) prior to parsing
  50128. ** a statement since we will be comparing table and column names
  50129. ** against all schemas and we do not want those schemas being
  50130. ** reset out from under us.
  50131. **
  50132. ** There is a corresponding leave-all procedures.
  50133. **
  50134. ** Enter the mutexes in accending order by BtShared pointer address
  50135. ** to avoid the possibility of deadlock when two threads with
  50136. ** two or more btrees in common both try to lock all their btrees
  50137. ** at the same instant.
  50138. */
  50139. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  50140. int i;
  50141. Btree *p;
  50142. assert( sqlite3_mutex_held(db->mutex) );
  50143. for(i=0; i<db->nDb; i++){
  50144. p = db->aDb[i].pBt;
  50145. if( p ) sqlite3BtreeEnter(p);
  50146. }
  50147. }
  50148. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  50149. int i;
  50150. Btree *p;
  50151. assert( sqlite3_mutex_held(db->mutex) );
  50152. for(i=0; i<db->nDb; i++){
  50153. p = db->aDb[i].pBt;
  50154. if( p ) sqlite3BtreeLeave(p);
  50155. }
  50156. }
  50157. /*
  50158. ** Return true if a particular Btree requires a lock. Return FALSE if
  50159. ** no lock is ever required since it is not sharable.
  50160. */
  50161. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  50162. return p->sharable;
  50163. }
  50164. #ifndef NDEBUG
  50165. /*
  50166. ** Return true if the current thread holds the database connection
  50167. ** mutex and all required BtShared mutexes.
  50168. **
  50169. ** This routine is used inside assert() statements only.
  50170. */
  50171. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  50172. int i;
  50173. if( !sqlite3_mutex_held(db->mutex) ){
  50174. return 0;
  50175. }
  50176. for(i=0; i<db->nDb; i++){
  50177. Btree *p;
  50178. p = db->aDb[i].pBt;
  50179. if( p && p->sharable &&
  50180. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  50181. return 0;
  50182. }
  50183. }
  50184. return 1;
  50185. }
  50186. #endif /* NDEBUG */
  50187. #ifndef NDEBUG
  50188. /*
  50189. ** Return true if the correct mutexes are held for accessing the
  50190. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  50191. ** access are:
  50192. **
  50193. ** (1) The mutex on db
  50194. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  50195. **
  50196. ** If pSchema is not NULL, then iDb is computed from pSchema and
  50197. ** db using sqlite3SchemaToIndex().
  50198. */
  50199. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  50200. Btree *p;
  50201. assert( db!=0 );
  50202. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  50203. assert( iDb>=0 && iDb<db->nDb );
  50204. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  50205. if( iDb==1 ) return 1;
  50206. p = db->aDb[iDb].pBt;
  50207. assert( p!=0 );
  50208. return p->sharable==0 || p->locked==1;
  50209. }
  50210. #endif /* NDEBUG */
  50211. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  50212. /*
  50213. ** The following are special cases for mutex enter routines for use
  50214. ** in single threaded applications that use shared cache. Except for
  50215. ** these two routines, all mutex operations are no-ops in that case and
  50216. ** are null #defines in btree.h.
  50217. **
  50218. ** If shared cache is disabled, then all btree mutex routines, including
  50219. ** the ones below, are no-ops and are null #defines in btree.h.
  50220. */
  50221. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  50222. p->pBt->db = p->db;
  50223. }
  50224. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  50225. int i;
  50226. for(i=0; i<db->nDb; i++){
  50227. Btree *p = db->aDb[i].pBt;
  50228. if( p ){
  50229. p->pBt->db = p->db;
  50230. }
  50231. }
  50232. }
  50233. #endif /* if SQLITE_THREADSAFE */
  50234. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  50235. /************** End of btmutex.c *********************************************/
  50236. /************** Begin file btree.c *******************************************/
  50237. /*
  50238. ** 2004 April 6
  50239. **
  50240. ** The author disclaims copyright to this source code. In place of
  50241. ** a legal notice, here is a blessing:
  50242. **
  50243. ** May you do good and not evil.
  50244. ** May you find forgiveness for yourself and forgive others.
  50245. ** May you share freely, never taking more than you give.
  50246. **
  50247. *************************************************************************
  50248. ** This file implements an external (disk-based) database using BTrees.
  50249. ** See the header comment on "btreeInt.h" for additional information.
  50250. ** Including a description of file format and an overview of operation.
  50251. */
  50252. /* #include "btreeInt.h" */
  50253. /*
  50254. ** The header string that appears at the beginning of every
  50255. ** SQLite database.
  50256. */
  50257. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  50258. /*
  50259. ** Set this global variable to 1 to enable tracing using the TRACE
  50260. ** macro.
  50261. */
  50262. #if 0
  50263. int sqlite3BtreeTrace=1; /* True to enable tracing */
  50264. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  50265. #else
  50266. # define TRACE(X)
  50267. #endif
  50268. /*
  50269. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  50270. ** But if the value is zero, make it 65536.
  50271. **
  50272. ** This routine is used to extract the "offset to cell content area" value
  50273. ** from the header of a btree page. If the page size is 65536 and the page
  50274. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  50275. ** This routine makes the necessary adjustment to 65536.
  50276. */
  50277. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  50278. /*
  50279. ** Values passed as the 5th argument to allocateBtreePage()
  50280. */
  50281. #define BTALLOC_ANY 0 /* Allocate any page */
  50282. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  50283. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  50284. /*
  50285. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  50286. ** defined, or 0 if it is. For example:
  50287. **
  50288. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  50289. */
  50290. #ifndef SQLITE_OMIT_AUTOVACUUM
  50291. #define IfNotOmitAV(expr) (expr)
  50292. #else
  50293. #define IfNotOmitAV(expr) 0
  50294. #endif
  50295. #ifndef SQLITE_OMIT_SHARED_CACHE
  50296. /*
  50297. ** A list of BtShared objects that are eligible for participation
  50298. ** in shared cache. This variable has file scope during normal builds,
  50299. ** but the test harness needs to access it so we make it global for
  50300. ** test builds.
  50301. **
  50302. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  50303. */
  50304. #ifdef SQLITE_TEST
  50305. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  50306. #else
  50307. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  50308. #endif
  50309. #endif /* SQLITE_OMIT_SHARED_CACHE */
  50310. #ifndef SQLITE_OMIT_SHARED_CACHE
  50311. /*
  50312. ** Enable or disable the shared pager and schema features.
  50313. **
  50314. ** This routine has no effect on existing database connections.
  50315. ** The shared cache setting effects only future calls to
  50316. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  50317. */
  50318. SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
  50319. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  50320. return SQLITE_OK;
  50321. }
  50322. #endif
  50323. #ifdef SQLITE_OMIT_SHARED_CACHE
  50324. /*
  50325. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  50326. ** and clearAllSharedCacheTableLocks()
  50327. ** manipulate entries in the BtShared.pLock linked list used to store
  50328. ** shared-cache table level locks. If the library is compiled with the
  50329. ** shared-cache feature disabled, then there is only ever one user
  50330. ** of each BtShared structure and so this locking is not necessary.
  50331. ** So define the lock related functions as no-ops.
  50332. */
  50333. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  50334. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  50335. #define clearAllSharedCacheTableLocks(a)
  50336. #define downgradeAllSharedCacheTableLocks(a)
  50337. #define hasSharedCacheTableLock(a,b,c,d) 1
  50338. #define hasReadConflicts(a, b) 0
  50339. #endif
  50340. #ifndef SQLITE_OMIT_SHARED_CACHE
  50341. #ifdef SQLITE_DEBUG
  50342. /*
  50343. **** This function is only used as part of an assert() statement. ***
  50344. **
  50345. ** Check to see if pBtree holds the required locks to read or write to the
  50346. ** table with root page iRoot. Return 1 if it does and 0 if not.
  50347. **
  50348. ** For example, when writing to a table with root-page iRoot via
  50349. ** Btree connection pBtree:
  50350. **
  50351. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  50352. **
  50353. ** When writing to an index that resides in a sharable database, the
  50354. ** caller should have first obtained a lock specifying the root page of
  50355. ** the corresponding table. This makes things a bit more complicated,
  50356. ** as this module treats each table as a separate structure. To determine
  50357. ** the table corresponding to the index being written, this
  50358. ** function has to search through the database schema.
  50359. **
  50360. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  50361. ** hold a write-lock on the schema table (root page 1). This is also
  50362. ** acceptable.
  50363. */
  50364. static int hasSharedCacheTableLock(
  50365. Btree *pBtree, /* Handle that must hold lock */
  50366. Pgno iRoot, /* Root page of b-tree */
  50367. int isIndex, /* True if iRoot is the root of an index b-tree */
  50368. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  50369. ){
  50370. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  50371. Pgno iTab = 0;
  50372. BtLock *pLock;
  50373. /* If this database is not shareable, or if the client is reading
  50374. ** and has the read-uncommitted flag set, then no lock is required.
  50375. ** Return true immediately.
  50376. */
  50377. if( (pBtree->sharable==0)
  50378. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  50379. ){
  50380. return 1;
  50381. }
  50382. /* If the client is reading or writing an index and the schema is
  50383. ** not loaded, then it is too difficult to actually check to see if
  50384. ** the correct locks are held. So do not bother - just return true.
  50385. ** This case does not come up very often anyhow.
  50386. */
  50387. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  50388. return 1;
  50389. }
  50390. /* Figure out the root-page that the lock should be held on. For table
  50391. ** b-trees, this is just the root page of the b-tree being read or
  50392. ** written. For index b-trees, it is the root page of the associated
  50393. ** table. */
  50394. if( isIndex ){
  50395. HashElem *p;
  50396. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  50397. Index *pIdx = (Index *)sqliteHashData(p);
  50398. if( pIdx->tnum==(int)iRoot ){
  50399. if( iTab ){
  50400. /* Two or more indexes share the same root page. There must
  50401. ** be imposter tables. So just return true. The assert is not
  50402. ** useful in that case. */
  50403. return 1;
  50404. }
  50405. iTab = pIdx->pTable->tnum;
  50406. }
  50407. }
  50408. }else{
  50409. iTab = iRoot;
  50410. }
  50411. /* Search for the required lock. Either a write-lock on root-page iTab, a
  50412. ** write-lock on the schema table, or (if the client is reading) a
  50413. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  50414. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  50415. if( pLock->pBtree==pBtree
  50416. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  50417. && pLock->eLock>=eLockType
  50418. ){
  50419. return 1;
  50420. }
  50421. }
  50422. /* Failed to find the required lock. */
  50423. return 0;
  50424. }
  50425. #endif /* SQLITE_DEBUG */
  50426. #ifdef SQLITE_DEBUG
  50427. /*
  50428. **** This function may be used as part of assert() statements only. ****
  50429. **
  50430. ** Return true if it would be illegal for pBtree to write into the
  50431. ** table or index rooted at iRoot because other shared connections are
  50432. ** simultaneously reading that same table or index.
  50433. **
  50434. ** It is illegal for pBtree to write if some other Btree object that
  50435. ** shares the same BtShared object is currently reading or writing
  50436. ** the iRoot table. Except, if the other Btree object has the
  50437. ** read-uncommitted flag set, then it is OK for the other object to
  50438. ** have a read cursor.
  50439. **
  50440. ** For example, before writing to any part of the table or index
  50441. ** rooted at page iRoot, one should call:
  50442. **
  50443. ** assert( !hasReadConflicts(pBtree, iRoot) );
  50444. */
  50445. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  50446. BtCursor *p;
  50447. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  50448. if( p->pgnoRoot==iRoot
  50449. && p->pBtree!=pBtree
  50450. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  50451. ){
  50452. return 1;
  50453. }
  50454. }
  50455. return 0;
  50456. }
  50457. #endif /* #ifdef SQLITE_DEBUG */
  50458. /*
  50459. ** Query to see if Btree handle p may obtain a lock of type eLock
  50460. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  50461. ** SQLITE_OK if the lock may be obtained (by calling
  50462. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  50463. */
  50464. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  50465. BtShared *pBt = p->pBt;
  50466. BtLock *pIter;
  50467. assert( sqlite3BtreeHoldsMutex(p) );
  50468. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  50469. assert( p->db!=0 );
  50470. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  50471. /* If requesting a write-lock, then the Btree must have an open write
  50472. ** transaction on this file. And, obviously, for this to be so there
  50473. ** must be an open write transaction on the file itself.
  50474. */
  50475. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  50476. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  50477. /* This routine is a no-op if the shared-cache is not enabled */
  50478. if( !p->sharable ){
  50479. return SQLITE_OK;
  50480. }
  50481. /* If some other connection is holding an exclusive lock, the
  50482. ** requested lock may not be obtained.
  50483. */
  50484. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  50485. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  50486. return SQLITE_LOCKED_SHAREDCACHE;
  50487. }
  50488. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  50489. /* The condition (pIter->eLock!=eLock) in the following if(...)
  50490. ** statement is a simplification of:
  50491. **
  50492. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  50493. **
  50494. ** since we know that if eLock==WRITE_LOCK, then no other connection
  50495. ** may hold a WRITE_LOCK on any table in this file (since there can
  50496. ** only be a single writer).
  50497. */
  50498. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  50499. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  50500. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  50501. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  50502. if( eLock==WRITE_LOCK ){
  50503. assert( p==pBt->pWriter );
  50504. pBt->btsFlags |= BTS_PENDING;
  50505. }
  50506. return SQLITE_LOCKED_SHAREDCACHE;
  50507. }
  50508. }
  50509. return SQLITE_OK;
  50510. }
  50511. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  50512. #ifndef SQLITE_OMIT_SHARED_CACHE
  50513. /*
  50514. ** Add a lock on the table with root-page iTable to the shared-btree used
  50515. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  50516. ** WRITE_LOCK.
  50517. **
  50518. ** This function assumes the following:
  50519. **
  50520. ** (a) The specified Btree object p is connected to a sharable
  50521. ** database (one with the BtShared.sharable flag set), and
  50522. **
  50523. ** (b) No other Btree objects hold a lock that conflicts
  50524. ** with the requested lock (i.e. querySharedCacheTableLock() has
  50525. ** already been called and returned SQLITE_OK).
  50526. **
  50527. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  50528. ** is returned if a malloc attempt fails.
  50529. */
  50530. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  50531. BtShared *pBt = p->pBt;
  50532. BtLock *pLock = 0;
  50533. BtLock *pIter;
  50534. assert( sqlite3BtreeHoldsMutex(p) );
  50535. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  50536. assert( p->db!=0 );
  50537. /* A connection with the read-uncommitted flag set will never try to
  50538. ** obtain a read-lock using this function. The only read-lock obtained
  50539. ** by a connection in read-uncommitted mode is on the sqlite_master
  50540. ** table, and that lock is obtained in BtreeBeginTrans(). */
  50541. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  50542. /* This function should only be called on a sharable b-tree after it
  50543. ** has been determined that no other b-tree holds a conflicting lock. */
  50544. assert( p->sharable );
  50545. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  50546. /* First search the list for an existing lock on this table. */
  50547. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  50548. if( pIter->iTable==iTable && pIter->pBtree==p ){
  50549. pLock = pIter;
  50550. break;
  50551. }
  50552. }
  50553. /* If the above search did not find a BtLock struct associating Btree p
  50554. ** with table iTable, allocate one and link it into the list.
  50555. */
  50556. if( !pLock ){
  50557. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  50558. if( !pLock ){
  50559. return SQLITE_NOMEM;
  50560. }
  50561. pLock->iTable = iTable;
  50562. pLock->pBtree = p;
  50563. pLock->pNext = pBt->pLock;
  50564. pBt->pLock = pLock;
  50565. }
  50566. /* Set the BtLock.eLock variable to the maximum of the current lock
  50567. ** and the requested lock. This means if a write-lock was already held
  50568. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  50569. */
  50570. assert( WRITE_LOCK>READ_LOCK );
  50571. if( eLock>pLock->eLock ){
  50572. pLock->eLock = eLock;
  50573. }
  50574. return SQLITE_OK;
  50575. }
  50576. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  50577. #ifndef SQLITE_OMIT_SHARED_CACHE
  50578. /*
  50579. ** Release all the table locks (locks obtained via calls to
  50580. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  50581. **
  50582. ** This function assumes that Btree p has an open read or write
  50583. ** transaction. If it does not, then the BTS_PENDING flag
  50584. ** may be incorrectly cleared.
  50585. */
  50586. static void clearAllSharedCacheTableLocks(Btree *p){
  50587. BtShared *pBt = p->pBt;
  50588. BtLock **ppIter = &pBt->pLock;
  50589. assert( sqlite3BtreeHoldsMutex(p) );
  50590. assert( p->sharable || 0==*ppIter );
  50591. assert( p->inTrans>0 );
  50592. while( *ppIter ){
  50593. BtLock *pLock = *ppIter;
  50594. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  50595. assert( pLock->pBtree->inTrans>=pLock->eLock );
  50596. if( pLock->pBtree==p ){
  50597. *ppIter = pLock->pNext;
  50598. assert( pLock->iTable!=1 || pLock==&p->lock );
  50599. if( pLock->iTable!=1 ){
  50600. sqlite3_free(pLock);
  50601. }
  50602. }else{
  50603. ppIter = &pLock->pNext;
  50604. }
  50605. }
  50606. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  50607. if( pBt->pWriter==p ){
  50608. pBt->pWriter = 0;
  50609. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  50610. }else if( pBt->nTransaction==2 ){
  50611. /* This function is called when Btree p is concluding its
  50612. ** transaction. If there currently exists a writer, and p is not
  50613. ** that writer, then the number of locks held by connections other
  50614. ** than the writer must be about to drop to zero. In this case
  50615. ** set the BTS_PENDING flag to 0.
  50616. **
  50617. ** If there is not currently a writer, then BTS_PENDING must
  50618. ** be zero already. So this next line is harmless in that case.
  50619. */
  50620. pBt->btsFlags &= ~BTS_PENDING;
  50621. }
  50622. }
  50623. /*
  50624. ** This function changes all write-locks held by Btree p into read-locks.
  50625. */
  50626. static void downgradeAllSharedCacheTableLocks(Btree *p){
  50627. BtShared *pBt = p->pBt;
  50628. if( pBt->pWriter==p ){
  50629. BtLock *pLock;
  50630. pBt->pWriter = 0;
  50631. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  50632. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  50633. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  50634. pLock->eLock = READ_LOCK;
  50635. }
  50636. }
  50637. }
  50638. #endif /* SQLITE_OMIT_SHARED_CACHE */
  50639. static void releasePage(MemPage *pPage); /* Forward reference */
  50640. /*
  50641. ***** This routine is used inside of assert() only ****
  50642. **
  50643. ** Verify that the cursor holds the mutex on its BtShared
  50644. */
  50645. #ifdef SQLITE_DEBUG
  50646. static int cursorHoldsMutex(BtCursor *p){
  50647. return sqlite3_mutex_held(p->pBt->mutex);
  50648. }
  50649. #endif
  50650. /*
  50651. ** Invalidate the overflow cache of the cursor passed as the first argument.
  50652. ** on the shared btree structure pBt.
  50653. */
  50654. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  50655. /*
  50656. ** Invalidate the overflow page-list cache for all cursors opened
  50657. ** on the shared btree structure pBt.
  50658. */
  50659. static void invalidateAllOverflowCache(BtShared *pBt){
  50660. BtCursor *p;
  50661. assert( sqlite3_mutex_held(pBt->mutex) );
  50662. for(p=pBt->pCursor; p; p=p->pNext){
  50663. invalidateOverflowCache(p);
  50664. }
  50665. }
  50666. #ifndef SQLITE_OMIT_INCRBLOB
  50667. /*
  50668. ** This function is called before modifying the contents of a table
  50669. ** to invalidate any incrblob cursors that are open on the
  50670. ** row or one of the rows being modified.
  50671. **
  50672. ** If argument isClearTable is true, then the entire contents of the
  50673. ** table is about to be deleted. In this case invalidate all incrblob
  50674. ** cursors open on any row within the table with root-page pgnoRoot.
  50675. **
  50676. ** Otherwise, if argument isClearTable is false, then the row with
  50677. ** rowid iRow is being replaced or deleted. In this case invalidate
  50678. ** only those incrblob cursors open on that specific row.
  50679. */
  50680. static void invalidateIncrblobCursors(
  50681. Btree *pBtree, /* The database file to check */
  50682. i64 iRow, /* The rowid that might be changing */
  50683. int isClearTable /* True if all rows are being deleted */
  50684. ){
  50685. BtCursor *p;
  50686. if( pBtree->hasIncrblobCur==0 ) return;
  50687. assert( sqlite3BtreeHoldsMutex(pBtree) );
  50688. pBtree->hasIncrblobCur = 0;
  50689. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  50690. if( (p->curFlags & BTCF_Incrblob)!=0 ){
  50691. pBtree->hasIncrblobCur = 1;
  50692. if( isClearTable || p->info.nKey==iRow ){
  50693. p->eState = CURSOR_INVALID;
  50694. }
  50695. }
  50696. }
  50697. }
  50698. #else
  50699. /* Stub function when INCRBLOB is omitted */
  50700. #define invalidateIncrblobCursors(x,y,z)
  50701. #endif /* SQLITE_OMIT_INCRBLOB */
  50702. /*
  50703. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  50704. ** when a page that previously contained data becomes a free-list leaf
  50705. ** page.
  50706. **
  50707. ** The BtShared.pHasContent bitvec exists to work around an obscure
  50708. ** bug caused by the interaction of two useful IO optimizations surrounding
  50709. ** free-list leaf pages:
  50710. **
  50711. ** 1) When all data is deleted from a page and the page becomes
  50712. ** a free-list leaf page, the page is not written to the database
  50713. ** (as free-list leaf pages contain no meaningful data). Sometimes
  50714. ** such a page is not even journalled (as it will not be modified,
  50715. ** why bother journalling it?).
  50716. **
  50717. ** 2) When a free-list leaf page is reused, its content is not read
  50718. ** from the database or written to the journal file (why should it
  50719. ** be, if it is not at all meaningful?).
  50720. **
  50721. ** By themselves, these optimizations work fine and provide a handy
  50722. ** performance boost to bulk delete or insert operations. However, if
  50723. ** a page is moved to the free-list and then reused within the same
  50724. ** transaction, a problem comes up. If the page is not journalled when
  50725. ** it is moved to the free-list and it is also not journalled when it
  50726. ** is extracted from the free-list and reused, then the original data
  50727. ** may be lost. In the event of a rollback, it may not be possible
  50728. ** to restore the database to its original configuration.
  50729. **
  50730. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  50731. ** moved to become a free-list leaf page, the corresponding bit is
  50732. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  50733. ** optimization 2 above is omitted if the corresponding bit is already
  50734. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  50735. ** at the end of every transaction.
  50736. */
  50737. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  50738. int rc = SQLITE_OK;
  50739. if( !pBt->pHasContent ){
  50740. assert( pgno<=pBt->nPage );
  50741. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  50742. if( !pBt->pHasContent ){
  50743. rc = SQLITE_NOMEM;
  50744. }
  50745. }
  50746. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  50747. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  50748. }
  50749. return rc;
  50750. }
  50751. /*
  50752. ** Query the BtShared.pHasContent vector.
  50753. **
  50754. ** This function is called when a free-list leaf page is removed from the
  50755. ** free-list for reuse. It returns false if it is safe to retrieve the
  50756. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  50757. */
  50758. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  50759. Bitvec *p = pBt->pHasContent;
  50760. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  50761. }
  50762. /*
  50763. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  50764. ** invoked at the conclusion of each write-transaction.
  50765. */
  50766. static void btreeClearHasContent(BtShared *pBt){
  50767. sqlite3BitvecDestroy(pBt->pHasContent);
  50768. pBt->pHasContent = 0;
  50769. }
  50770. /*
  50771. ** Release all of the apPage[] pages for a cursor.
  50772. */
  50773. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  50774. int i;
  50775. for(i=0; i<=pCur->iPage; i++){
  50776. releasePage(pCur->apPage[i]);
  50777. pCur->apPage[i] = 0;
  50778. }
  50779. pCur->iPage = -1;
  50780. }
  50781. /*
  50782. ** Save the current cursor position in the variables BtCursor.nKey
  50783. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  50784. **
  50785. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  50786. ** prior to calling this routine.
  50787. */
  50788. static int saveCursorPosition(BtCursor *pCur){
  50789. int rc;
  50790. assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
  50791. assert( 0==pCur->pKey );
  50792. assert( cursorHoldsMutex(pCur) );
  50793. if( pCur->eState==CURSOR_SKIPNEXT ){
  50794. pCur->eState = CURSOR_VALID;
  50795. }else{
  50796. pCur->skipNext = 0;
  50797. }
  50798. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  50799. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  50800. /* If this is an intKey table, then the above call to BtreeKeySize()
  50801. ** stores the integer key in pCur->nKey. In this case this value is
  50802. ** all that is required. Otherwise, if pCur is not open on an intKey
  50803. ** table, then malloc space for and store the pCur->nKey bytes of key
  50804. ** data.
  50805. */
  50806. if( 0==pCur->curIntKey ){
  50807. void *pKey = sqlite3Malloc( pCur->nKey );
  50808. if( pKey ){
  50809. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  50810. if( rc==SQLITE_OK ){
  50811. pCur->pKey = pKey;
  50812. }else{
  50813. sqlite3_free(pKey);
  50814. }
  50815. }else{
  50816. rc = SQLITE_NOMEM;
  50817. }
  50818. }
  50819. assert( !pCur->curIntKey || !pCur->pKey );
  50820. if( rc==SQLITE_OK ){
  50821. btreeReleaseAllCursorPages(pCur);
  50822. pCur->eState = CURSOR_REQUIRESEEK;
  50823. }
  50824. invalidateOverflowCache(pCur);
  50825. return rc;
  50826. }
  50827. /* Forward reference */
  50828. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  50829. /*
  50830. ** Save the positions of all cursors (except pExcept) that are open on
  50831. ** the table with root-page iRoot. "Saving the cursor position" means that
  50832. ** the location in the btree is remembered in such a way that it can be
  50833. ** moved back to the same spot after the btree has been modified. This
  50834. ** routine is called just before cursor pExcept is used to modify the
  50835. ** table, for example in BtreeDelete() or BtreeInsert().
  50836. **
  50837. ** If there are two or more cursors on the same btree, then all such
  50838. ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
  50839. ** routine enforces that rule. This routine only needs to be called in
  50840. ** the uncommon case when pExpect has the BTCF_Multiple flag set.
  50841. **
  50842. ** If pExpect!=NULL and if no other cursors are found on the same root-page,
  50843. ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
  50844. ** pointless call to this routine.
  50845. **
  50846. ** Implementation note: This routine merely checks to see if any cursors
  50847. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  50848. ** event that cursors are in need to being saved.
  50849. */
  50850. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  50851. BtCursor *p;
  50852. assert( sqlite3_mutex_held(pBt->mutex) );
  50853. assert( pExcept==0 || pExcept->pBt==pBt );
  50854. for(p=pBt->pCursor; p; p=p->pNext){
  50855. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  50856. }
  50857. if( p ) return saveCursorsOnList(p, iRoot, pExcept);
  50858. if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
  50859. return SQLITE_OK;
  50860. }
  50861. /* This helper routine to saveAllCursors does the actual work of saving
  50862. ** the cursors if and when a cursor is found that actually requires saving.
  50863. ** The common case is that no cursors need to be saved, so this routine is
  50864. ** broken out from its caller to avoid unnecessary stack pointer movement.
  50865. */
  50866. static int SQLITE_NOINLINE saveCursorsOnList(
  50867. BtCursor *p, /* The first cursor that needs saving */
  50868. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  50869. BtCursor *pExcept /* Do not save this cursor */
  50870. ){
  50871. do{
  50872. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  50873. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  50874. int rc = saveCursorPosition(p);
  50875. if( SQLITE_OK!=rc ){
  50876. return rc;
  50877. }
  50878. }else{
  50879. testcase( p->iPage>0 );
  50880. btreeReleaseAllCursorPages(p);
  50881. }
  50882. }
  50883. p = p->pNext;
  50884. }while( p );
  50885. return SQLITE_OK;
  50886. }
  50887. /*
  50888. ** Clear the current cursor position.
  50889. */
  50890. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  50891. assert( cursorHoldsMutex(pCur) );
  50892. sqlite3_free(pCur->pKey);
  50893. pCur->pKey = 0;
  50894. pCur->eState = CURSOR_INVALID;
  50895. }
  50896. /*
  50897. ** In this version of BtreeMoveto, pKey is a packed index record
  50898. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  50899. ** record and then call BtreeMovetoUnpacked() to do the work.
  50900. */
  50901. static int btreeMoveto(
  50902. BtCursor *pCur, /* Cursor open on the btree to be searched */
  50903. const void *pKey, /* Packed key if the btree is an index */
  50904. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  50905. int bias, /* Bias search to the high end */
  50906. int *pRes /* Write search results here */
  50907. ){
  50908. int rc; /* Status code */
  50909. UnpackedRecord *pIdxKey; /* Unpacked index key */
  50910. char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
  50911. char *pFree = 0;
  50912. if( pKey ){
  50913. assert( nKey==(i64)(int)nKey );
  50914. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  50915. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  50916. );
  50917. if( pIdxKey==0 ) return SQLITE_NOMEM;
  50918. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  50919. if( pIdxKey->nField==0 ){
  50920. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  50921. return SQLITE_CORRUPT_BKPT;
  50922. }
  50923. }else{
  50924. pIdxKey = 0;
  50925. }
  50926. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  50927. if( pFree ){
  50928. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  50929. }
  50930. return rc;
  50931. }
  50932. /*
  50933. ** Restore the cursor to the position it was in (or as close to as possible)
  50934. ** when saveCursorPosition() was called. Note that this call deletes the
  50935. ** saved position info stored by saveCursorPosition(), so there can be
  50936. ** at most one effective restoreCursorPosition() call after each
  50937. ** saveCursorPosition().
  50938. */
  50939. static int btreeRestoreCursorPosition(BtCursor *pCur){
  50940. int rc;
  50941. int skipNext;
  50942. assert( cursorHoldsMutex(pCur) );
  50943. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  50944. if( pCur->eState==CURSOR_FAULT ){
  50945. return pCur->skipNext;
  50946. }
  50947. pCur->eState = CURSOR_INVALID;
  50948. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
  50949. if( rc==SQLITE_OK ){
  50950. sqlite3_free(pCur->pKey);
  50951. pCur->pKey = 0;
  50952. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  50953. pCur->skipNext |= skipNext;
  50954. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  50955. pCur->eState = CURSOR_SKIPNEXT;
  50956. }
  50957. }
  50958. return rc;
  50959. }
  50960. #define restoreCursorPosition(p) \
  50961. (p->eState>=CURSOR_REQUIRESEEK ? \
  50962. btreeRestoreCursorPosition(p) : \
  50963. SQLITE_OK)
  50964. /*
  50965. ** Determine whether or not a cursor has moved from the position where
  50966. ** it was last placed, or has been invalidated for any other reason.
  50967. ** Cursors can move when the row they are pointing at is deleted out
  50968. ** from under them, for example. Cursor might also move if a btree
  50969. ** is rebalanced.
  50970. **
  50971. ** Calling this routine with a NULL cursor pointer returns false.
  50972. **
  50973. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  50974. ** back to where it ought to be if this routine returns true.
  50975. */
  50976. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  50977. return pCur->eState!=CURSOR_VALID;
  50978. }
  50979. /*
  50980. ** This routine restores a cursor back to its original position after it
  50981. ** has been moved by some outside activity (such as a btree rebalance or
  50982. ** a row having been deleted out from under the cursor).
  50983. **
  50984. ** On success, the *pDifferentRow parameter is false if the cursor is left
  50985. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  50986. ** was pointing to has been deleted, forcing the cursor to point to some
  50987. ** nearby row.
  50988. **
  50989. ** This routine should only be called for a cursor that just returned
  50990. ** TRUE from sqlite3BtreeCursorHasMoved().
  50991. */
  50992. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  50993. int rc;
  50994. assert( pCur!=0 );
  50995. assert( pCur->eState!=CURSOR_VALID );
  50996. rc = restoreCursorPosition(pCur);
  50997. if( rc ){
  50998. *pDifferentRow = 1;
  50999. return rc;
  51000. }
  51001. if( pCur->eState!=CURSOR_VALID ){
  51002. *pDifferentRow = 1;
  51003. }else{
  51004. assert( pCur->skipNext==0 );
  51005. *pDifferentRow = 0;
  51006. }
  51007. return SQLITE_OK;
  51008. }
  51009. #ifndef SQLITE_OMIT_AUTOVACUUM
  51010. /*
  51011. ** Given a page number of a regular database page, return the page
  51012. ** number for the pointer-map page that contains the entry for the
  51013. ** input page number.
  51014. **
  51015. ** Return 0 (not a valid page) for pgno==1 since there is
  51016. ** no pointer map associated with page 1. The integrity_check logic
  51017. ** requires that ptrmapPageno(*,1)!=1.
  51018. */
  51019. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  51020. int nPagesPerMapPage;
  51021. Pgno iPtrMap, ret;
  51022. assert( sqlite3_mutex_held(pBt->mutex) );
  51023. if( pgno<2 ) return 0;
  51024. nPagesPerMapPage = (pBt->usableSize/5)+1;
  51025. iPtrMap = (pgno-2)/nPagesPerMapPage;
  51026. ret = (iPtrMap*nPagesPerMapPage) + 2;
  51027. if( ret==PENDING_BYTE_PAGE(pBt) ){
  51028. ret++;
  51029. }
  51030. return ret;
  51031. }
  51032. /*
  51033. ** Write an entry into the pointer map.
  51034. **
  51035. ** This routine updates the pointer map entry for page number 'key'
  51036. ** so that it maps to type 'eType' and parent page number 'pgno'.
  51037. **
  51038. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  51039. ** a no-op. If an error occurs, the appropriate error code is written
  51040. ** into *pRC.
  51041. */
  51042. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  51043. DbPage *pDbPage; /* The pointer map page */
  51044. u8 *pPtrmap; /* The pointer map data */
  51045. Pgno iPtrmap; /* The pointer map page number */
  51046. int offset; /* Offset in pointer map page */
  51047. int rc; /* Return code from subfunctions */
  51048. if( *pRC ) return;
  51049. assert( sqlite3_mutex_held(pBt->mutex) );
  51050. /* The master-journal page number must never be used as a pointer map page */
  51051. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  51052. assert( pBt->autoVacuum );
  51053. if( key==0 ){
  51054. *pRC = SQLITE_CORRUPT_BKPT;
  51055. return;
  51056. }
  51057. iPtrmap = PTRMAP_PAGENO(pBt, key);
  51058. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  51059. if( rc!=SQLITE_OK ){
  51060. *pRC = rc;
  51061. return;
  51062. }
  51063. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  51064. if( offset<0 ){
  51065. *pRC = SQLITE_CORRUPT_BKPT;
  51066. goto ptrmap_exit;
  51067. }
  51068. assert( offset <= (int)pBt->usableSize-5 );
  51069. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  51070. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  51071. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  51072. *pRC= rc = sqlite3PagerWrite(pDbPage);
  51073. if( rc==SQLITE_OK ){
  51074. pPtrmap[offset] = eType;
  51075. put4byte(&pPtrmap[offset+1], parent);
  51076. }
  51077. }
  51078. ptrmap_exit:
  51079. sqlite3PagerUnref(pDbPage);
  51080. }
  51081. /*
  51082. ** Read an entry from the pointer map.
  51083. **
  51084. ** This routine retrieves the pointer map entry for page 'key', writing
  51085. ** the type and parent page number to *pEType and *pPgno respectively.
  51086. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  51087. */
  51088. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  51089. DbPage *pDbPage; /* The pointer map page */
  51090. int iPtrmap; /* Pointer map page index */
  51091. u8 *pPtrmap; /* Pointer map page data */
  51092. int offset; /* Offset of entry in pointer map */
  51093. int rc;
  51094. assert( sqlite3_mutex_held(pBt->mutex) );
  51095. iPtrmap = PTRMAP_PAGENO(pBt, key);
  51096. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  51097. if( rc!=0 ){
  51098. return rc;
  51099. }
  51100. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  51101. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  51102. if( offset<0 ){
  51103. sqlite3PagerUnref(pDbPage);
  51104. return SQLITE_CORRUPT_BKPT;
  51105. }
  51106. assert( offset <= (int)pBt->usableSize-5 );
  51107. assert( pEType!=0 );
  51108. *pEType = pPtrmap[offset];
  51109. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  51110. sqlite3PagerUnref(pDbPage);
  51111. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  51112. return SQLITE_OK;
  51113. }
  51114. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  51115. #define ptrmapPut(w,x,y,z,rc)
  51116. #define ptrmapGet(w,x,y,z) SQLITE_OK
  51117. #define ptrmapPutOvflPtr(x, y, rc)
  51118. #endif
  51119. /*
  51120. ** Given a btree page and a cell index (0 means the first cell on
  51121. ** the page, 1 means the second cell, and so forth) return a pointer
  51122. ** to the cell content.
  51123. **
  51124. ** findCellPastPtr() does the same except it skips past the initial
  51125. ** 4-byte child pointer found on interior pages, if there is one.
  51126. **
  51127. ** This routine works only for pages that do not contain overflow cells.
  51128. */
  51129. #define findCell(P,I) \
  51130. ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  51131. #define findCellPastPtr(P,I) \
  51132. ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
  51133. /*
  51134. ** This is common tail processing for btreeParseCellPtr() and
  51135. ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
  51136. ** on a single B-tree page. Make necessary adjustments to the CellInfo
  51137. ** structure.
  51138. */
  51139. static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(
  51140. MemPage *pPage, /* Page containing the cell */
  51141. u8 *pCell, /* Pointer to the cell text. */
  51142. CellInfo *pInfo /* Fill in this structure */
  51143. ){
  51144. /* If the payload will not fit completely on the local page, we have
  51145. ** to decide how much to store locally and how much to spill onto
  51146. ** overflow pages. The strategy is to minimize the amount of unused
  51147. ** space on overflow pages while keeping the amount of local storage
  51148. ** in between minLocal and maxLocal.
  51149. **
  51150. ** Warning: changing the way overflow payload is distributed in any
  51151. ** way will result in an incompatible file format.
  51152. */
  51153. int minLocal; /* Minimum amount of payload held locally */
  51154. int maxLocal; /* Maximum amount of payload held locally */
  51155. int surplus; /* Overflow payload available for local storage */
  51156. minLocal = pPage->minLocal;
  51157. maxLocal = pPage->maxLocal;
  51158. surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
  51159. testcase( surplus==maxLocal );
  51160. testcase( surplus==maxLocal+1 );
  51161. if( surplus <= maxLocal ){
  51162. pInfo->nLocal = (u16)surplus;
  51163. }else{
  51164. pInfo->nLocal = (u16)minLocal;
  51165. }
  51166. pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
  51167. pInfo->nSize = pInfo->iOverflow + 4;
  51168. }
  51169. /*
  51170. ** The following routines are implementations of the MemPage.xParseCell()
  51171. ** method.
  51172. **
  51173. ** Parse a cell content block and fill in the CellInfo structure.
  51174. **
  51175. ** btreeParseCellPtr() => table btree leaf nodes
  51176. ** btreeParseCellNoPayload() => table btree internal nodes
  51177. ** btreeParseCellPtrIndex() => index btree nodes
  51178. **
  51179. ** There is also a wrapper function btreeParseCell() that works for
  51180. ** all MemPage types and that references the cell by index rather than
  51181. ** by pointer.
  51182. */
  51183. static void btreeParseCellPtrNoPayload(
  51184. MemPage *pPage, /* Page containing the cell */
  51185. u8 *pCell, /* Pointer to the cell text. */
  51186. CellInfo *pInfo /* Fill in this structure */
  51187. ){
  51188. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51189. assert( pPage->leaf==0 );
  51190. assert( pPage->noPayload );
  51191. assert( pPage->childPtrSize==4 );
  51192. #ifndef SQLITE_DEBUG
  51193. UNUSED_PARAMETER(pPage);
  51194. #endif
  51195. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  51196. pInfo->nPayload = 0;
  51197. pInfo->nLocal = 0;
  51198. pInfo->iOverflow = 0;
  51199. pInfo->pPayload = 0;
  51200. return;
  51201. }
  51202. static void btreeParseCellPtr(
  51203. MemPage *pPage, /* Page containing the cell */
  51204. u8 *pCell, /* Pointer to the cell text. */
  51205. CellInfo *pInfo /* Fill in this structure */
  51206. ){
  51207. u8 *pIter; /* For scanning through pCell */
  51208. u32 nPayload; /* Number of bytes of cell payload */
  51209. u64 iKey; /* Extracted Key value */
  51210. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51211. assert( pPage->leaf==0 || pPage->leaf==1 );
  51212. assert( pPage->intKeyLeaf || pPage->noPayload );
  51213. assert( pPage->noPayload==0 );
  51214. assert( pPage->intKeyLeaf );
  51215. assert( pPage->childPtrSize==0 );
  51216. pIter = pCell;
  51217. /* The next block of code is equivalent to:
  51218. **
  51219. ** pIter += getVarint32(pIter, nPayload);
  51220. **
  51221. ** The code is inlined to avoid a function call.
  51222. */
  51223. nPayload = *pIter;
  51224. if( nPayload>=0x80 ){
  51225. u8 *pEnd = &pIter[8];
  51226. nPayload &= 0x7f;
  51227. do{
  51228. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  51229. }while( (*pIter)>=0x80 && pIter<pEnd );
  51230. }
  51231. pIter++;
  51232. /* The next block of code is equivalent to:
  51233. **
  51234. ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  51235. **
  51236. ** The code is inlined to avoid a function call.
  51237. */
  51238. iKey = *pIter;
  51239. if( iKey>=0x80 ){
  51240. u8 *pEnd = &pIter[7];
  51241. iKey &= 0x7f;
  51242. while(1){
  51243. iKey = (iKey<<7) | (*++pIter & 0x7f);
  51244. if( (*pIter)<0x80 ) break;
  51245. if( pIter>=pEnd ){
  51246. iKey = (iKey<<8) | *++pIter;
  51247. break;
  51248. }
  51249. }
  51250. }
  51251. pIter++;
  51252. pInfo->nKey = *(i64*)&iKey;
  51253. pInfo->nPayload = nPayload;
  51254. pInfo->pPayload = pIter;
  51255. testcase( nPayload==pPage->maxLocal );
  51256. testcase( nPayload==pPage->maxLocal+1 );
  51257. if( nPayload<=pPage->maxLocal ){
  51258. /* This is the (easy) common case where the entire payload fits
  51259. ** on the local page. No overflow is required.
  51260. */
  51261. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  51262. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  51263. pInfo->nLocal = (u16)nPayload;
  51264. pInfo->iOverflow = 0;
  51265. }else{
  51266. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  51267. }
  51268. }
  51269. static void btreeParseCellPtrIndex(
  51270. MemPage *pPage, /* Page containing the cell */
  51271. u8 *pCell, /* Pointer to the cell text. */
  51272. CellInfo *pInfo /* Fill in this structure */
  51273. ){
  51274. u8 *pIter; /* For scanning through pCell */
  51275. u32 nPayload; /* Number of bytes of cell payload */
  51276. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51277. assert( pPage->leaf==0 || pPage->leaf==1 );
  51278. assert( pPage->intKeyLeaf==0 );
  51279. assert( pPage->noPayload==0 );
  51280. pIter = pCell + pPage->childPtrSize;
  51281. nPayload = *pIter;
  51282. if( nPayload>=0x80 ){
  51283. u8 *pEnd = &pIter[8];
  51284. nPayload &= 0x7f;
  51285. do{
  51286. nPayload = (nPayload<<7) | (*++pIter & 0x7f);
  51287. }while( *(pIter)>=0x80 && pIter<pEnd );
  51288. }
  51289. pIter++;
  51290. pInfo->nKey = nPayload;
  51291. pInfo->nPayload = nPayload;
  51292. pInfo->pPayload = pIter;
  51293. testcase( nPayload==pPage->maxLocal );
  51294. testcase( nPayload==pPage->maxLocal+1 );
  51295. if( nPayload<=pPage->maxLocal ){
  51296. /* This is the (easy) common case where the entire payload fits
  51297. ** on the local page. No overflow is required.
  51298. */
  51299. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  51300. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  51301. pInfo->nLocal = (u16)nPayload;
  51302. pInfo->iOverflow = 0;
  51303. }else{
  51304. btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
  51305. }
  51306. }
  51307. static void btreeParseCell(
  51308. MemPage *pPage, /* Page containing the cell */
  51309. int iCell, /* The cell index. First cell is 0 */
  51310. CellInfo *pInfo /* Fill in this structure */
  51311. ){
  51312. pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
  51313. }
  51314. /*
  51315. ** The following routines are implementations of the MemPage.xCellSize
  51316. ** method.
  51317. **
  51318. ** Compute the total number of bytes that a Cell needs in the cell
  51319. ** data area of the btree-page. The return number includes the cell
  51320. ** data header and the local payload, but not any overflow page or
  51321. ** the space used by the cell pointer.
  51322. **
  51323. ** cellSizePtrNoPayload() => table internal nodes
  51324. ** cellSizePtr() => all index nodes & table leaf nodes
  51325. */
  51326. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  51327. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  51328. u8 *pEnd; /* End mark for a varint */
  51329. u32 nSize; /* Size value to return */
  51330. #ifdef SQLITE_DEBUG
  51331. /* The value returned by this function should always be the same as
  51332. ** the (CellInfo.nSize) value found by doing a full parse of the
  51333. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  51334. ** this function verifies that this invariant is not violated. */
  51335. CellInfo debuginfo;
  51336. pPage->xParseCell(pPage, pCell, &debuginfo);
  51337. #endif
  51338. assert( pPage->noPayload==0 );
  51339. nSize = *pIter;
  51340. if( nSize>=0x80 ){
  51341. pEnd = &pIter[8];
  51342. nSize &= 0x7f;
  51343. do{
  51344. nSize = (nSize<<7) | (*++pIter & 0x7f);
  51345. }while( *(pIter)>=0x80 && pIter<pEnd );
  51346. }
  51347. pIter++;
  51348. if( pPage->intKey ){
  51349. /* pIter now points at the 64-bit integer key value, a variable length
  51350. ** integer. The following block moves pIter to point at the first byte
  51351. ** past the end of the key value. */
  51352. pEnd = &pIter[9];
  51353. while( (*pIter++)&0x80 && pIter<pEnd );
  51354. }
  51355. testcase( nSize==pPage->maxLocal );
  51356. testcase( nSize==pPage->maxLocal+1 );
  51357. if( nSize<=pPage->maxLocal ){
  51358. nSize += (u32)(pIter - pCell);
  51359. if( nSize<4 ) nSize = 4;
  51360. }else{
  51361. int minLocal = pPage->minLocal;
  51362. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  51363. testcase( nSize==pPage->maxLocal );
  51364. testcase( nSize==pPage->maxLocal+1 );
  51365. if( nSize>pPage->maxLocal ){
  51366. nSize = minLocal;
  51367. }
  51368. nSize += 4 + (u16)(pIter - pCell);
  51369. }
  51370. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  51371. return (u16)nSize;
  51372. }
  51373. static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
  51374. u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
  51375. u8 *pEnd; /* End mark for a varint */
  51376. #ifdef SQLITE_DEBUG
  51377. /* The value returned by this function should always be the same as
  51378. ** the (CellInfo.nSize) value found by doing a full parse of the
  51379. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  51380. ** this function verifies that this invariant is not violated. */
  51381. CellInfo debuginfo;
  51382. pPage->xParseCell(pPage, pCell, &debuginfo);
  51383. #else
  51384. UNUSED_PARAMETER(pPage);
  51385. #endif
  51386. assert( pPage->childPtrSize==4 );
  51387. pEnd = pIter + 9;
  51388. while( (*pIter++)&0x80 && pIter<pEnd );
  51389. assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
  51390. return (u16)(pIter - pCell);
  51391. }
  51392. #ifdef SQLITE_DEBUG
  51393. /* This variation on cellSizePtr() is used inside of assert() statements
  51394. ** only. */
  51395. static u16 cellSize(MemPage *pPage, int iCell){
  51396. return pPage->xCellSize(pPage, findCell(pPage, iCell));
  51397. }
  51398. #endif
  51399. #ifndef SQLITE_OMIT_AUTOVACUUM
  51400. /*
  51401. ** If the cell pCell, part of page pPage contains a pointer
  51402. ** to an overflow page, insert an entry into the pointer-map
  51403. ** for the overflow page.
  51404. */
  51405. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  51406. CellInfo info;
  51407. if( *pRC ) return;
  51408. assert( pCell!=0 );
  51409. pPage->xParseCell(pPage, pCell, &info);
  51410. if( info.iOverflow ){
  51411. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  51412. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  51413. }
  51414. }
  51415. #endif
  51416. /*
  51417. ** Defragment the page given. All Cells are moved to the
  51418. ** end of the page and all free space is collected into one
  51419. ** big FreeBlk that occurs in between the header and cell
  51420. ** pointer array and the cell content area.
  51421. **
  51422. ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
  51423. ** b-tree page so that there are no freeblocks or fragment bytes, all
  51424. ** unused bytes are contained in the unallocated space region, and all
  51425. ** cells are packed tightly at the end of the page.
  51426. */
  51427. static int defragmentPage(MemPage *pPage){
  51428. int i; /* Loop counter */
  51429. int pc; /* Address of the i-th cell */
  51430. int hdr; /* Offset to the page header */
  51431. int size; /* Size of a cell */
  51432. int usableSize; /* Number of usable bytes on a page */
  51433. int cellOffset; /* Offset to the cell pointer array */
  51434. int cbrk; /* Offset to the cell content area */
  51435. int nCell; /* Number of cells on the page */
  51436. unsigned char *data; /* The page data */
  51437. unsigned char *temp; /* Temp area for cell content */
  51438. unsigned char *src; /* Source of content */
  51439. int iCellFirst; /* First allowable cell index */
  51440. int iCellLast; /* Last possible cell index */
  51441. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51442. assert( pPage->pBt!=0 );
  51443. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  51444. assert( pPage->nOverflow==0 );
  51445. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51446. temp = 0;
  51447. src = data = pPage->aData;
  51448. hdr = pPage->hdrOffset;
  51449. cellOffset = pPage->cellOffset;
  51450. nCell = pPage->nCell;
  51451. assert( nCell==get2byte(&data[hdr+3]) );
  51452. usableSize = pPage->pBt->usableSize;
  51453. cbrk = usableSize;
  51454. iCellFirst = cellOffset + 2*nCell;
  51455. iCellLast = usableSize - 4;
  51456. for(i=0; i<nCell; i++){
  51457. u8 *pAddr; /* The i-th cell pointer */
  51458. pAddr = &data[cellOffset + i*2];
  51459. pc = get2byte(pAddr);
  51460. testcase( pc==iCellFirst );
  51461. testcase( pc==iCellLast );
  51462. /* These conditions have already been verified in btreeInitPage()
  51463. ** if PRAGMA cell_size_check=ON.
  51464. */
  51465. if( pc<iCellFirst || pc>iCellLast ){
  51466. return SQLITE_CORRUPT_BKPT;
  51467. }
  51468. assert( pc>=iCellFirst && pc<=iCellLast );
  51469. size = pPage->xCellSize(pPage, &src[pc]);
  51470. cbrk -= size;
  51471. if( cbrk<iCellFirst || pc+size>usableSize ){
  51472. return SQLITE_CORRUPT_BKPT;
  51473. }
  51474. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  51475. testcase( cbrk+size==usableSize );
  51476. testcase( pc+size==usableSize );
  51477. put2byte(pAddr, cbrk);
  51478. if( temp==0 ){
  51479. int x;
  51480. if( cbrk==pc ) continue;
  51481. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  51482. x = get2byte(&data[hdr+5]);
  51483. memcpy(&temp[x], &data[x], (cbrk+size) - x);
  51484. src = temp;
  51485. }
  51486. memcpy(&data[cbrk], &src[pc], size);
  51487. }
  51488. assert( cbrk>=iCellFirst );
  51489. put2byte(&data[hdr+5], cbrk);
  51490. data[hdr+1] = 0;
  51491. data[hdr+2] = 0;
  51492. data[hdr+7] = 0;
  51493. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  51494. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51495. if( cbrk-iCellFirst!=pPage->nFree ){
  51496. return SQLITE_CORRUPT_BKPT;
  51497. }
  51498. return SQLITE_OK;
  51499. }
  51500. /*
  51501. ** Search the free-list on page pPg for space to store a cell nByte bytes in
  51502. ** size. If one can be found, return a pointer to the space and remove it
  51503. ** from the free-list.
  51504. **
  51505. ** If no suitable space can be found on the free-list, return NULL.
  51506. **
  51507. ** This function may detect corruption within pPg. If corruption is
  51508. ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
  51509. **
  51510. ** Slots on the free list that are between 1 and 3 bytes larger than nByte
  51511. ** will be ignored if adding the extra space to the fragmentation count
  51512. ** causes the fragmentation count to exceed 60.
  51513. */
  51514. static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
  51515. const int hdr = pPg->hdrOffset;
  51516. u8 * const aData = pPg->aData;
  51517. int iAddr = hdr + 1;
  51518. int pc = get2byte(&aData[iAddr]);
  51519. int x;
  51520. int usableSize = pPg->pBt->usableSize;
  51521. assert( pc>0 );
  51522. do{
  51523. int size; /* Size of the free slot */
  51524. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  51525. ** increasing offset. */
  51526. if( pc>usableSize-4 || pc<iAddr+4 ){
  51527. *pRc = SQLITE_CORRUPT_BKPT;
  51528. return 0;
  51529. }
  51530. /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
  51531. ** freeblock form a big-endian integer which is the size of the freeblock
  51532. ** in bytes, including the 4-byte header. */
  51533. size = get2byte(&aData[pc+2]);
  51534. if( (x = size - nByte)>=0 ){
  51535. testcase( x==4 );
  51536. testcase( x==3 );
  51537. if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
  51538. *pRc = SQLITE_CORRUPT_BKPT;
  51539. return 0;
  51540. }else if( x<4 ){
  51541. /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
  51542. ** number of bytes in fragments may not exceed 60. */
  51543. if( aData[hdr+7]>57 ) return 0;
  51544. /* Remove the slot from the free-list. Update the number of
  51545. ** fragmented bytes within the page. */
  51546. memcpy(&aData[iAddr], &aData[pc], 2);
  51547. aData[hdr+7] += (u8)x;
  51548. }else{
  51549. /* The slot remains on the free-list. Reduce its size to account
  51550. ** for the portion used by the new allocation. */
  51551. put2byte(&aData[pc+2], x);
  51552. }
  51553. return &aData[pc + x];
  51554. }
  51555. iAddr = pc;
  51556. pc = get2byte(&aData[pc]);
  51557. }while( pc );
  51558. return 0;
  51559. }
  51560. /*
  51561. ** Allocate nByte bytes of space from within the B-Tree page passed
  51562. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  51563. ** of the first byte of allocated space. Return either SQLITE_OK or
  51564. ** an error code (usually SQLITE_CORRUPT).
  51565. **
  51566. ** The caller guarantees that there is sufficient space to make the
  51567. ** allocation. This routine might need to defragment in order to bring
  51568. ** all the space together, however. This routine will avoid using
  51569. ** the first two bytes past the cell pointer area since presumably this
  51570. ** allocation is being made in order to insert a new cell, so we will
  51571. ** also end up needing a new cell pointer.
  51572. */
  51573. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  51574. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  51575. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  51576. int top; /* First byte of cell content area */
  51577. int rc = SQLITE_OK; /* Integer return code */
  51578. int gap; /* First byte of gap between cell pointers and cell content */
  51579. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51580. assert( pPage->pBt );
  51581. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51582. assert( nByte>=0 ); /* Minimum cell size is 4 */
  51583. assert( pPage->nFree>=nByte );
  51584. assert( pPage->nOverflow==0 );
  51585. assert( nByte < (int)(pPage->pBt->usableSize-8) );
  51586. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  51587. gap = pPage->cellOffset + 2*pPage->nCell;
  51588. assert( gap<=65536 );
  51589. /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
  51590. ** and the reserved space is zero (the usual value for reserved space)
  51591. ** then the cell content offset of an empty page wants to be 65536.
  51592. ** However, that integer is too large to be stored in a 2-byte unsigned
  51593. ** integer, so a value of 0 is used in its place. */
  51594. top = get2byte(&data[hdr+5]);
  51595. assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
  51596. if( gap>top ){
  51597. if( top==0 && pPage->pBt->usableSize==65536 ){
  51598. top = 65536;
  51599. }else{
  51600. return SQLITE_CORRUPT_BKPT;
  51601. }
  51602. }
  51603. /* If there is enough space between gap and top for one more cell pointer
  51604. ** array entry offset, and if the freelist is not empty, then search the
  51605. ** freelist looking for a free slot big enough to satisfy the request.
  51606. */
  51607. testcase( gap+2==top );
  51608. testcase( gap+1==top );
  51609. testcase( gap==top );
  51610. if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
  51611. u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
  51612. if( pSpace ){
  51613. assert( pSpace>=data && (pSpace - data)<65536 );
  51614. *pIdx = (int)(pSpace - data);
  51615. return SQLITE_OK;
  51616. }else if( rc ){
  51617. return rc;
  51618. }
  51619. }
  51620. /* The request could not be fulfilled using a freelist slot. Check
  51621. ** to see if defragmentation is necessary.
  51622. */
  51623. testcase( gap+2+nByte==top );
  51624. if( gap+2+nByte>top ){
  51625. assert( pPage->nCell>0 || CORRUPT_DB );
  51626. rc = defragmentPage(pPage);
  51627. if( rc ) return rc;
  51628. top = get2byteNotZero(&data[hdr+5]);
  51629. assert( gap+nByte<=top );
  51630. }
  51631. /* Allocate memory from the gap in between the cell pointer array
  51632. ** and the cell content area. The btreeInitPage() call has already
  51633. ** validated the freelist. Given that the freelist is valid, there
  51634. ** is no way that the allocation can extend off the end of the page.
  51635. ** The assert() below verifies the previous sentence.
  51636. */
  51637. top -= nByte;
  51638. put2byte(&data[hdr+5], top);
  51639. assert( top+nByte <= (int)pPage->pBt->usableSize );
  51640. *pIdx = top;
  51641. return SQLITE_OK;
  51642. }
  51643. /*
  51644. ** Return a section of the pPage->aData to the freelist.
  51645. ** The first byte of the new free block is pPage->aData[iStart]
  51646. ** and the size of the block is iSize bytes.
  51647. **
  51648. ** Adjacent freeblocks are coalesced.
  51649. **
  51650. ** Note that even though the freeblock list was checked by btreeInitPage(),
  51651. ** that routine will not detect overlap between cells or freeblocks. Nor
  51652. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  51653. ** at the end of the page. So do additional corruption checks inside this
  51654. ** routine and return SQLITE_CORRUPT if any problems are found.
  51655. */
  51656. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  51657. u16 iPtr; /* Address of ptr to next freeblock */
  51658. u16 iFreeBlk; /* Address of the next freeblock */
  51659. u8 hdr; /* Page header size. 0 or 100 */
  51660. u8 nFrag = 0; /* Reduction in fragmentation */
  51661. u16 iOrigSize = iSize; /* Original value of iSize */
  51662. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  51663. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  51664. unsigned char *data = pPage->aData; /* Page content */
  51665. assert( pPage->pBt!=0 );
  51666. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51667. assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  51668. assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
  51669. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51670. assert( iSize>=4 ); /* Minimum cell size is 4 */
  51671. assert( iStart<=iLast );
  51672. /* Overwrite deleted information with zeros when the secure_delete
  51673. ** option is enabled */
  51674. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  51675. memset(&data[iStart], 0, iSize);
  51676. }
  51677. /* The list of freeblocks must be in ascending order. Find the
  51678. ** spot on the list where iStart should be inserted.
  51679. */
  51680. hdr = pPage->hdrOffset;
  51681. iPtr = hdr + 1;
  51682. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  51683. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  51684. }else{
  51685. while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
  51686. if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
  51687. iPtr = iFreeBlk;
  51688. }
  51689. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  51690. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  51691. /* At this point:
  51692. ** iFreeBlk: First freeblock after iStart, or zero if none
  51693. ** iPtr: The address of a pointer to iFreeBlk
  51694. **
  51695. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  51696. */
  51697. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  51698. nFrag = iFreeBlk - iEnd;
  51699. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  51700. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  51701. if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
  51702. iSize = iEnd - iStart;
  51703. iFreeBlk = get2byte(&data[iFreeBlk]);
  51704. }
  51705. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  51706. ** pointer in the page header) then check to see if iStart should be
  51707. ** coalesced onto the end of iPtr.
  51708. */
  51709. if( iPtr>hdr+1 ){
  51710. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  51711. if( iPtrEnd+3>=iStart ){
  51712. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  51713. nFrag += iStart - iPtrEnd;
  51714. iSize = iEnd - iPtr;
  51715. iStart = iPtr;
  51716. }
  51717. }
  51718. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  51719. data[hdr+7] -= nFrag;
  51720. }
  51721. if( iStart==get2byte(&data[hdr+5]) ){
  51722. /* The new freeblock is at the beginning of the cell content area,
  51723. ** so just extend the cell content area rather than create another
  51724. ** freelist entry */
  51725. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  51726. put2byte(&data[hdr+1], iFreeBlk);
  51727. put2byte(&data[hdr+5], iEnd);
  51728. }else{
  51729. /* Insert the new freeblock into the freelist */
  51730. put2byte(&data[iPtr], iStart);
  51731. put2byte(&data[iStart], iFreeBlk);
  51732. put2byte(&data[iStart+2], iSize);
  51733. }
  51734. pPage->nFree += iOrigSize;
  51735. return SQLITE_OK;
  51736. }
  51737. /*
  51738. ** Decode the flags byte (the first byte of the header) for a page
  51739. ** and initialize fields of the MemPage structure accordingly.
  51740. **
  51741. ** Only the following combinations are supported. Anything different
  51742. ** indicates a corrupt database files:
  51743. **
  51744. ** PTF_ZERODATA
  51745. ** PTF_ZERODATA | PTF_LEAF
  51746. ** PTF_LEAFDATA | PTF_INTKEY
  51747. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  51748. */
  51749. static int decodeFlags(MemPage *pPage, int flagByte){
  51750. BtShared *pBt; /* A copy of pPage->pBt */
  51751. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  51752. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51753. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  51754. flagByte &= ~PTF_LEAF;
  51755. pPage->childPtrSize = 4-4*pPage->leaf;
  51756. pPage->xCellSize = cellSizePtr;
  51757. pBt = pPage->pBt;
  51758. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  51759. /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
  51760. ** table b-tree page. */
  51761. assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
  51762. /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
  51763. ** table b-tree page. */
  51764. assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
  51765. pPage->intKey = 1;
  51766. if( pPage->leaf ){
  51767. pPage->intKeyLeaf = 1;
  51768. pPage->noPayload = 0;
  51769. pPage->xParseCell = btreeParseCellPtr;
  51770. }else{
  51771. pPage->intKeyLeaf = 0;
  51772. pPage->noPayload = 1;
  51773. pPage->xCellSize = cellSizePtrNoPayload;
  51774. pPage->xParseCell = btreeParseCellPtrNoPayload;
  51775. }
  51776. pPage->maxLocal = pBt->maxLeaf;
  51777. pPage->minLocal = pBt->minLeaf;
  51778. }else if( flagByte==PTF_ZERODATA ){
  51779. /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
  51780. ** index b-tree page. */
  51781. assert( (PTF_ZERODATA)==2 );
  51782. /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
  51783. ** index b-tree page. */
  51784. assert( (PTF_ZERODATA|PTF_LEAF)==10 );
  51785. pPage->intKey = 0;
  51786. pPage->intKeyLeaf = 0;
  51787. pPage->noPayload = 0;
  51788. pPage->xParseCell = btreeParseCellPtrIndex;
  51789. pPage->maxLocal = pBt->maxLocal;
  51790. pPage->minLocal = pBt->minLocal;
  51791. }else{
  51792. /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
  51793. ** an error. */
  51794. return SQLITE_CORRUPT_BKPT;
  51795. }
  51796. pPage->max1bytePayload = pBt->max1bytePayload;
  51797. return SQLITE_OK;
  51798. }
  51799. /*
  51800. ** Initialize the auxiliary information for a disk block.
  51801. **
  51802. ** Return SQLITE_OK on success. If we see that the page does
  51803. ** not contain a well-formed database page, then return
  51804. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  51805. ** guarantee that the page is well-formed. It only shows that
  51806. ** we failed to detect any corruption.
  51807. */
  51808. static int btreeInitPage(MemPage *pPage){
  51809. assert( pPage->pBt!=0 );
  51810. assert( pPage->pBt->db!=0 );
  51811. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51812. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  51813. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  51814. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  51815. if( !pPage->isInit ){
  51816. u16 pc; /* Address of a freeblock within pPage->aData[] */
  51817. u8 hdr; /* Offset to beginning of page header */
  51818. u8 *data; /* Equal to pPage->aData */
  51819. BtShared *pBt; /* The main btree structure */
  51820. int usableSize; /* Amount of usable space on each page */
  51821. u16 cellOffset; /* Offset from start of page to first cell pointer */
  51822. int nFree; /* Number of unused bytes on the page */
  51823. int top; /* First byte of the cell content area */
  51824. int iCellFirst; /* First allowable cell or freeblock offset */
  51825. int iCellLast; /* Last possible cell or freeblock offset */
  51826. pBt = pPage->pBt;
  51827. hdr = pPage->hdrOffset;
  51828. data = pPage->aData;
  51829. /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
  51830. ** the b-tree page type. */
  51831. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  51832. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  51833. pPage->maskPage = (u16)(pBt->pageSize - 1);
  51834. pPage->nOverflow = 0;
  51835. usableSize = pBt->usableSize;
  51836. pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
  51837. pPage->aDataEnd = &data[usableSize];
  51838. pPage->aCellIdx = &data[cellOffset];
  51839. pPage->aDataOfst = &data[pPage->childPtrSize];
  51840. /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
  51841. ** the start of the cell content area. A zero value for this integer is
  51842. ** interpreted as 65536. */
  51843. top = get2byteNotZero(&data[hdr+5]);
  51844. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  51845. ** number of cells on the page. */
  51846. pPage->nCell = get2byte(&data[hdr+3]);
  51847. if( pPage->nCell>MX_CELL(pBt) ){
  51848. /* To many cells for a single page. The page must be corrupt */
  51849. return SQLITE_CORRUPT_BKPT;
  51850. }
  51851. testcase( pPage->nCell==MX_CELL(pBt) );
  51852. /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
  51853. ** possible for a root page of a table that contains no rows) then the
  51854. ** offset to the cell content area will equal the page size minus the
  51855. ** bytes of reserved space. */
  51856. assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
  51857. /* A malformed database page might cause us to read past the end
  51858. ** of page when parsing a cell.
  51859. **
  51860. ** The following block of code checks early to see if a cell extends
  51861. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  51862. ** returned if it does.
  51863. */
  51864. iCellFirst = cellOffset + 2*pPage->nCell;
  51865. iCellLast = usableSize - 4;
  51866. if( pBt->db->flags & SQLITE_CellSizeCk ){
  51867. int i; /* Index into the cell pointer array */
  51868. int sz; /* Size of a cell */
  51869. if( !pPage->leaf ) iCellLast--;
  51870. for(i=0; i<pPage->nCell; i++){
  51871. pc = get2byteAligned(&data[cellOffset+i*2]);
  51872. testcase( pc==iCellFirst );
  51873. testcase( pc==iCellLast );
  51874. if( pc<iCellFirst || pc>iCellLast ){
  51875. return SQLITE_CORRUPT_BKPT;
  51876. }
  51877. sz = pPage->xCellSize(pPage, &data[pc]);
  51878. testcase( pc+sz==usableSize );
  51879. if( pc+sz>usableSize ){
  51880. return SQLITE_CORRUPT_BKPT;
  51881. }
  51882. }
  51883. if( !pPage->leaf ) iCellLast++;
  51884. }
  51885. /* Compute the total free space on the page
  51886. ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
  51887. ** start of the first freeblock on the page, or is zero if there are no
  51888. ** freeblocks. */
  51889. pc = get2byte(&data[hdr+1]);
  51890. nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
  51891. while( pc>0 ){
  51892. u16 next, size;
  51893. if( pc<iCellFirst || pc>iCellLast ){
  51894. /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
  51895. ** always be at least one cell before the first freeblock.
  51896. **
  51897. ** Or, the freeblock is off the end of the page
  51898. */
  51899. return SQLITE_CORRUPT_BKPT;
  51900. }
  51901. next = get2byte(&data[pc]);
  51902. size = get2byte(&data[pc+2]);
  51903. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  51904. /* Free blocks must be in ascending order. And the last byte of
  51905. ** the free-block must lie on the database page. */
  51906. return SQLITE_CORRUPT_BKPT;
  51907. }
  51908. nFree = nFree + size;
  51909. pc = next;
  51910. }
  51911. /* At this point, nFree contains the sum of the offset to the start
  51912. ** of the cell-content area plus the number of free bytes within
  51913. ** the cell-content area. If this is greater than the usable-size
  51914. ** of the page, then the page must be corrupted. This check also
  51915. ** serves to verify that the offset to the start of the cell-content
  51916. ** area, according to the page header, lies within the page.
  51917. */
  51918. if( nFree>usableSize ){
  51919. return SQLITE_CORRUPT_BKPT;
  51920. }
  51921. pPage->nFree = (u16)(nFree - iCellFirst);
  51922. pPage->isInit = 1;
  51923. }
  51924. return SQLITE_OK;
  51925. }
  51926. /*
  51927. ** Set up a raw page so that it looks like a database page holding
  51928. ** no entries.
  51929. */
  51930. static void zeroPage(MemPage *pPage, int flags){
  51931. unsigned char *data = pPage->aData;
  51932. BtShared *pBt = pPage->pBt;
  51933. u8 hdr = pPage->hdrOffset;
  51934. u16 first;
  51935. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  51936. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  51937. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  51938. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51939. assert( sqlite3_mutex_held(pBt->mutex) );
  51940. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  51941. memset(&data[hdr], 0, pBt->usableSize - hdr);
  51942. }
  51943. data[hdr] = (char)flags;
  51944. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  51945. memset(&data[hdr+1], 0, 4);
  51946. data[hdr+7] = 0;
  51947. put2byte(&data[hdr+5], pBt->usableSize);
  51948. pPage->nFree = (u16)(pBt->usableSize - first);
  51949. decodeFlags(pPage, flags);
  51950. pPage->cellOffset = first;
  51951. pPage->aDataEnd = &data[pBt->usableSize];
  51952. pPage->aCellIdx = &data[first];
  51953. pPage->aDataOfst = &data[pPage->childPtrSize];
  51954. pPage->nOverflow = 0;
  51955. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  51956. pPage->maskPage = (u16)(pBt->pageSize - 1);
  51957. pPage->nCell = 0;
  51958. pPage->isInit = 1;
  51959. }
  51960. /*
  51961. ** Convert a DbPage obtained from the pager into a MemPage used by
  51962. ** the btree layer.
  51963. */
  51964. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  51965. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  51966. pPage->aData = sqlite3PagerGetData(pDbPage);
  51967. pPage->pDbPage = pDbPage;
  51968. pPage->pBt = pBt;
  51969. pPage->pgno = pgno;
  51970. pPage->hdrOffset = pgno==1 ? 100 : 0;
  51971. return pPage;
  51972. }
  51973. /*
  51974. ** Get a page from the pager. Initialize the MemPage.pBt and
  51975. ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
  51976. **
  51977. ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
  51978. ** about the content of the page at this time. So do not go to the disk
  51979. ** to fetch the content. Just fill in the content with zeros for now.
  51980. ** If in the future we call sqlite3PagerWrite() on this page, that
  51981. ** means we have started to be concerned about content and the disk
  51982. ** read should occur at that point.
  51983. */
  51984. static int btreeGetPage(
  51985. BtShared *pBt, /* The btree */
  51986. Pgno pgno, /* Number of the page to fetch */
  51987. MemPage **ppPage, /* Return the page in this parameter */
  51988. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  51989. ){
  51990. int rc;
  51991. DbPage *pDbPage;
  51992. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  51993. assert( sqlite3_mutex_held(pBt->mutex) );
  51994. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  51995. if( rc ) return rc;
  51996. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  51997. return SQLITE_OK;
  51998. }
  51999. /*
  52000. ** Retrieve a page from the pager cache. If the requested page is not
  52001. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  52002. ** MemPage.aData elements if needed.
  52003. */
  52004. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  52005. DbPage *pDbPage;
  52006. assert( sqlite3_mutex_held(pBt->mutex) );
  52007. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  52008. if( pDbPage ){
  52009. return btreePageFromDbPage(pDbPage, pgno, pBt);
  52010. }
  52011. return 0;
  52012. }
  52013. /*
  52014. ** Return the size of the database file in pages. If there is any kind of
  52015. ** error, return ((unsigned int)-1).
  52016. */
  52017. static Pgno btreePagecount(BtShared *pBt){
  52018. return pBt->nPage;
  52019. }
  52020. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  52021. assert( sqlite3BtreeHoldsMutex(p) );
  52022. assert( ((p->pBt->nPage)&0x8000000)==0 );
  52023. return btreePagecount(p->pBt);
  52024. }
  52025. /*
  52026. ** Get a page from the pager and initialize it.
  52027. **
  52028. ** If pCur!=0 then the page is being fetched as part of a moveToChild()
  52029. ** call. Do additional sanity checking on the page in this case.
  52030. ** And if the fetch fails, this routine must decrement pCur->iPage.
  52031. **
  52032. ** The page is fetched as read-write unless pCur is not NULL and is
  52033. ** a read-only cursor.
  52034. **
  52035. ** If an error occurs, then *ppPage is undefined. It
  52036. ** may remain unchanged, or it may be set to an invalid value.
  52037. */
  52038. static int getAndInitPage(
  52039. BtShared *pBt, /* The database file */
  52040. Pgno pgno, /* Number of the page to get */
  52041. MemPage **ppPage, /* Write the page pointer here */
  52042. BtCursor *pCur, /* Cursor to receive the page, or NULL */
  52043. int bReadOnly /* True for a read-only page */
  52044. ){
  52045. int rc;
  52046. DbPage *pDbPage;
  52047. assert( sqlite3_mutex_held(pBt->mutex) );
  52048. assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
  52049. assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
  52050. assert( pCur==0 || pCur->iPage>0 );
  52051. if( pgno>btreePagecount(pBt) ){
  52052. rc = SQLITE_CORRUPT_BKPT;
  52053. goto getAndInitPage_error;
  52054. }
  52055. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
  52056. if( rc ){
  52057. goto getAndInitPage_error;
  52058. }
  52059. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  52060. if( (*ppPage)->isInit==0 ){
  52061. rc = btreeInitPage(*ppPage);
  52062. if( rc!=SQLITE_OK ){
  52063. releasePage(*ppPage);
  52064. goto getAndInitPage_error;
  52065. }
  52066. }
  52067. /* If obtaining a child page for a cursor, we must verify that the page is
  52068. ** compatible with the root page. */
  52069. if( pCur
  52070. && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey)
  52071. ){
  52072. rc = SQLITE_CORRUPT_BKPT;
  52073. releasePage(*ppPage);
  52074. goto getAndInitPage_error;
  52075. }
  52076. return SQLITE_OK;
  52077. getAndInitPage_error:
  52078. if( pCur ) pCur->iPage--;
  52079. testcase( pgno==0 );
  52080. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  52081. return rc;
  52082. }
  52083. /*
  52084. ** Release a MemPage. This should be called once for each prior
  52085. ** call to btreeGetPage.
  52086. */
  52087. static void releasePageNotNull(MemPage *pPage){
  52088. assert( pPage->aData );
  52089. assert( pPage->pBt );
  52090. assert( pPage->pDbPage!=0 );
  52091. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  52092. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  52093. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52094. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  52095. }
  52096. static void releasePage(MemPage *pPage){
  52097. if( pPage ) releasePageNotNull(pPage);
  52098. }
  52099. /*
  52100. ** Get an unused page.
  52101. **
  52102. ** This works just like btreeGetPage() with the addition:
  52103. **
  52104. ** * If the page is already in use for some other purpose, immediately
  52105. ** release it and return an SQLITE_CURRUPT error.
  52106. ** * Make sure the isInit flag is clear
  52107. */
  52108. static int btreeGetUnusedPage(
  52109. BtShared *pBt, /* The btree */
  52110. Pgno pgno, /* Number of the page to fetch */
  52111. MemPage **ppPage, /* Return the page in this parameter */
  52112. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  52113. ){
  52114. int rc = btreeGetPage(pBt, pgno, ppPage, flags);
  52115. if( rc==SQLITE_OK ){
  52116. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  52117. releasePage(*ppPage);
  52118. *ppPage = 0;
  52119. return SQLITE_CORRUPT_BKPT;
  52120. }
  52121. (*ppPage)->isInit = 0;
  52122. }else{
  52123. *ppPage = 0;
  52124. }
  52125. return rc;
  52126. }
  52127. /*
  52128. ** During a rollback, when the pager reloads information into the cache
  52129. ** so that the cache is restored to its original state at the start of
  52130. ** the transaction, for each page restored this routine is called.
  52131. **
  52132. ** This routine needs to reset the extra data section at the end of the
  52133. ** page to agree with the restored data.
  52134. */
  52135. static void pageReinit(DbPage *pData){
  52136. MemPage *pPage;
  52137. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  52138. assert( sqlite3PagerPageRefcount(pData)>0 );
  52139. if( pPage->isInit ){
  52140. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52141. pPage->isInit = 0;
  52142. if( sqlite3PagerPageRefcount(pData)>1 ){
  52143. /* pPage might not be a btree page; it might be an overflow page
  52144. ** or ptrmap page or a free page. In those cases, the following
  52145. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  52146. ** But no harm is done by this. And it is very important that
  52147. ** btreeInitPage() be called on every btree page so we make
  52148. ** the call for every page that comes in for re-initing. */
  52149. btreeInitPage(pPage);
  52150. }
  52151. }
  52152. }
  52153. /*
  52154. ** Invoke the busy handler for a btree.
  52155. */
  52156. static int btreeInvokeBusyHandler(void *pArg){
  52157. BtShared *pBt = (BtShared*)pArg;
  52158. assert( pBt->db );
  52159. assert( sqlite3_mutex_held(pBt->db->mutex) );
  52160. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  52161. }
  52162. /*
  52163. ** Open a database file.
  52164. **
  52165. ** zFilename is the name of the database file. If zFilename is NULL
  52166. ** then an ephemeral database is created. The ephemeral database might
  52167. ** be exclusively in memory, or it might use a disk-based memory cache.
  52168. ** Either way, the ephemeral database will be automatically deleted
  52169. ** when sqlite3BtreeClose() is called.
  52170. **
  52171. ** If zFilename is ":memory:" then an in-memory database is created
  52172. ** that is automatically destroyed when it is closed.
  52173. **
  52174. ** The "flags" parameter is a bitmask that might contain bits like
  52175. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  52176. **
  52177. ** If the database is already opened in the same database connection
  52178. ** and we are in shared cache mode, then the open will fail with an
  52179. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  52180. ** objects in the same database connection since doing so will lead
  52181. ** to problems with locking.
  52182. */
  52183. SQLITE_PRIVATE int sqlite3BtreeOpen(
  52184. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  52185. const char *zFilename, /* Name of the file containing the BTree database */
  52186. sqlite3 *db, /* Associated database handle */
  52187. Btree **ppBtree, /* Pointer to new Btree object written here */
  52188. int flags, /* Options */
  52189. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  52190. ){
  52191. BtShared *pBt = 0; /* Shared part of btree structure */
  52192. Btree *p; /* Handle to return */
  52193. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  52194. int rc = SQLITE_OK; /* Result code from this function */
  52195. u8 nReserve; /* Byte of unused space on each page */
  52196. unsigned char zDbHeader[100]; /* Database header content */
  52197. /* True if opening an ephemeral, temporary database */
  52198. const int isTempDb = zFilename==0 || zFilename[0]==0;
  52199. /* Set the variable isMemdb to true for an in-memory database, or
  52200. ** false for a file-based database.
  52201. */
  52202. #ifdef SQLITE_OMIT_MEMORYDB
  52203. const int isMemdb = 0;
  52204. #else
  52205. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  52206. || (isTempDb && sqlite3TempInMemory(db))
  52207. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  52208. #endif
  52209. assert( db!=0 );
  52210. assert( pVfs!=0 );
  52211. assert( sqlite3_mutex_held(db->mutex) );
  52212. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  52213. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  52214. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  52215. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  52216. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  52217. if( isMemdb ){
  52218. flags |= BTREE_MEMORY;
  52219. }
  52220. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  52221. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  52222. }
  52223. p = sqlite3MallocZero(sizeof(Btree));
  52224. if( !p ){
  52225. return SQLITE_NOMEM;
  52226. }
  52227. p->inTrans = TRANS_NONE;
  52228. p->db = db;
  52229. #ifndef SQLITE_OMIT_SHARED_CACHE
  52230. p->lock.pBtree = p;
  52231. p->lock.iTable = 1;
  52232. #endif
  52233. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  52234. /*
  52235. ** If this Btree is a candidate for shared cache, try to find an
  52236. ** existing BtShared object that we can share with
  52237. */
  52238. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  52239. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  52240. int nFilename = sqlite3Strlen30(zFilename)+1;
  52241. int nFullPathname = pVfs->mxPathname+1;
  52242. char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
  52243. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  52244. p->sharable = 1;
  52245. if( !zFullPathname ){
  52246. sqlite3_free(p);
  52247. return SQLITE_NOMEM;
  52248. }
  52249. if( isMemdb ){
  52250. memcpy(zFullPathname, zFilename, nFilename);
  52251. }else{
  52252. rc = sqlite3OsFullPathname(pVfs, zFilename,
  52253. nFullPathname, zFullPathname);
  52254. if( rc ){
  52255. sqlite3_free(zFullPathname);
  52256. sqlite3_free(p);
  52257. return rc;
  52258. }
  52259. }
  52260. #if SQLITE_THREADSAFE
  52261. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  52262. sqlite3_mutex_enter(mutexOpen);
  52263. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  52264. sqlite3_mutex_enter(mutexShared);
  52265. #endif
  52266. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  52267. assert( pBt->nRef>0 );
  52268. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  52269. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  52270. int iDb;
  52271. for(iDb=db->nDb-1; iDb>=0; iDb--){
  52272. Btree *pExisting = db->aDb[iDb].pBt;
  52273. if( pExisting && pExisting->pBt==pBt ){
  52274. sqlite3_mutex_leave(mutexShared);
  52275. sqlite3_mutex_leave(mutexOpen);
  52276. sqlite3_free(zFullPathname);
  52277. sqlite3_free(p);
  52278. return SQLITE_CONSTRAINT;
  52279. }
  52280. }
  52281. p->pBt = pBt;
  52282. pBt->nRef++;
  52283. break;
  52284. }
  52285. }
  52286. sqlite3_mutex_leave(mutexShared);
  52287. sqlite3_free(zFullPathname);
  52288. }
  52289. #ifdef SQLITE_DEBUG
  52290. else{
  52291. /* In debug mode, we mark all persistent databases as sharable
  52292. ** even when they are not. This exercises the locking code and
  52293. ** gives more opportunity for asserts(sqlite3_mutex_held())
  52294. ** statements to find locking problems.
  52295. */
  52296. p->sharable = 1;
  52297. }
  52298. #endif
  52299. }
  52300. #endif
  52301. if( pBt==0 ){
  52302. /*
  52303. ** The following asserts make sure that structures used by the btree are
  52304. ** the right size. This is to guard against size changes that result
  52305. ** when compiling on a different architecture.
  52306. */
  52307. assert( sizeof(i64)==8 );
  52308. assert( sizeof(u64)==8 );
  52309. assert( sizeof(u32)==4 );
  52310. assert( sizeof(u16)==2 );
  52311. assert( sizeof(Pgno)==4 );
  52312. pBt = sqlite3MallocZero( sizeof(*pBt) );
  52313. if( pBt==0 ){
  52314. rc = SQLITE_NOMEM;
  52315. goto btree_open_out;
  52316. }
  52317. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  52318. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  52319. if( rc==SQLITE_OK ){
  52320. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  52321. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  52322. }
  52323. if( rc!=SQLITE_OK ){
  52324. goto btree_open_out;
  52325. }
  52326. pBt->openFlags = (u8)flags;
  52327. pBt->db = db;
  52328. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  52329. p->pBt = pBt;
  52330. pBt->pCursor = 0;
  52331. pBt->pPage1 = 0;
  52332. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  52333. #ifdef SQLITE_SECURE_DELETE
  52334. pBt->btsFlags |= BTS_SECURE_DELETE;
  52335. #endif
  52336. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  52337. ** determined by the 2-byte integer located at an offset of 16 bytes from
  52338. ** the beginning of the database file. */
  52339. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  52340. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  52341. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  52342. pBt->pageSize = 0;
  52343. #ifndef SQLITE_OMIT_AUTOVACUUM
  52344. /* If the magic name ":memory:" will create an in-memory database, then
  52345. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  52346. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  52347. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  52348. ** regular file-name. In this case the auto-vacuum applies as per normal.
  52349. */
  52350. if( zFilename && !isMemdb ){
  52351. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  52352. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  52353. }
  52354. #endif
  52355. nReserve = 0;
  52356. }else{
  52357. /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  52358. ** determined by the one-byte unsigned integer found at an offset of 20
  52359. ** into the database file header. */
  52360. nReserve = zDbHeader[20];
  52361. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  52362. #ifndef SQLITE_OMIT_AUTOVACUUM
  52363. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  52364. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  52365. #endif
  52366. }
  52367. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  52368. if( rc ) goto btree_open_out;
  52369. pBt->usableSize = pBt->pageSize - nReserve;
  52370. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  52371. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  52372. /* Add the new BtShared object to the linked list sharable BtShareds.
  52373. */
  52374. if( p->sharable ){
  52375. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  52376. pBt->nRef = 1;
  52377. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  52378. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  52379. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  52380. if( pBt->mutex==0 ){
  52381. rc = SQLITE_NOMEM;
  52382. db->mallocFailed = 0;
  52383. goto btree_open_out;
  52384. }
  52385. }
  52386. sqlite3_mutex_enter(mutexShared);
  52387. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  52388. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  52389. sqlite3_mutex_leave(mutexShared);
  52390. }
  52391. #endif
  52392. }
  52393. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  52394. /* If the new Btree uses a sharable pBtShared, then link the new
  52395. ** Btree into the list of all sharable Btrees for the same connection.
  52396. ** The list is kept in ascending order by pBt address.
  52397. */
  52398. if( p->sharable ){
  52399. int i;
  52400. Btree *pSib;
  52401. for(i=0; i<db->nDb; i++){
  52402. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  52403. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  52404. if( p->pBt<pSib->pBt ){
  52405. p->pNext = pSib;
  52406. p->pPrev = 0;
  52407. pSib->pPrev = p;
  52408. }else{
  52409. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  52410. pSib = pSib->pNext;
  52411. }
  52412. p->pNext = pSib->pNext;
  52413. p->pPrev = pSib;
  52414. if( p->pNext ){
  52415. p->pNext->pPrev = p;
  52416. }
  52417. pSib->pNext = p;
  52418. }
  52419. break;
  52420. }
  52421. }
  52422. }
  52423. #endif
  52424. *ppBtree = p;
  52425. btree_open_out:
  52426. if( rc!=SQLITE_OK ){
  52427. if( pBt && pBt->pPager ){
  52428. sqlite3PagerClose(pBt->pPager);
  52429. }
  52430. sqlite3_free(pBt);
  52431. sqlite3_free(p);
  52432. *ppBtree = 0;
  52433. }else{
  52434. /* If the B-Tree was successfully opened, set the pager-cache size to the
  52435. ** default value. Except, when opening on an existing shared pager-cache,
  52436. ** do not change the pager-cache size.
  52437. */
  52438. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  52439. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  52440. }
  52441. }
  52442. if( mutexOpen ){
  52443. assert( sqlite3_mutex_held(mutexOpen) );
  52444. sqlite3_mutex_leave(mutexOpen);
  52445. }
  52446. return rc;
  52447. }
  52448. /*
  52449. ** Decrement the BtShared.nRef counter. When it reaches zero,
  52450. ** remove the BtShared structure from the sharing list. Return
  52451. ** true if the BtShared.nRef counter reaches zero and return
  52452. ** false if it is still positive.
  52453. */
  52454. static int removeFromSharingList(BtShared *pBt){
  52455. #ifndef SQLITE_OMIT_SHARED_CACHE
  52456. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  52457. BtShared *pList;
  52458. int removed = 0;
  52459. assert( sqlite3_mutex_notheld(pBt->mutex) );
  52460. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  52461. sqlite3_mutex_enter(pMaster);
  52462. pBt->nRef--;
  52463. if( pBt->nRef<=0 ){
  52464. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  52465. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  52466. }else{
  52467. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  52468. while( ALWAYS(pList) && pList->pNext!=pBt ){
  52469. pList=pList->pNext;
  52470. }
  52471. if( ALWAYS(pList) ){
  52472. pList->pNext = pBt->pNext;
  52473. }
  52474. }
  52475. if( SQLITE_THREADSAFE ){
  52476. sqlite3_mutex_free(pBt->mutex);
  52477. }
  52478. removed = 1;
  52479. }
  52480. sqlite3_mutex_leave(pMaster);
  52481. return removed;
  52482. #else
  52483. return 1;
  52484. #endif
  52485. }
  52486. /*
  52487. ** Make sure pBt->pTmpSpace points to an allocation of
  52488. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  52489. ** pointer.
  52490. */
  52491. static void allocateTempSpace(BtShared *pBt){
  52492. if( !pBt->pTmpSpace ){
  52493. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  52494. /* One of the uses of pBt->pTmpSpace is to format cells before
  52495. ** inserting them into a leaf page (function fillInCell()). If
  52496. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  52497. ** by the various routines that manipulate binary cells. Which
  52498. ** can mean that fillInCell() only initializes the first 2 or 3
  52499. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  52500. ** it into a database page. This is not actually a problem, but it
  52501. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  52502. ** data is passed to system call write(). So to avoid this error,
  52503. ** zero the first 4 bytes of temp space here.
  52504. **
  52505. ** Also: Provide four bytes of initialized space before the
  52506. ** beginning of pTmpSpace as an area available to prepend the
  52507. ** left-child pointer to the beginning of a cell.
  52508. */
  52509. if( pBt->pTmpSpace ){
  52510. memset(pBt->pTmpSpace, 0, 8);
  52511. pBt->pTmpSpace += 4;
  52512. }
  52513. }
  52514. }
  52515. /*
  52516. ** Free the pBt->pTmpSpace allocation
  52517. */
  52518. static void freeTempSpace(BtShared *pBt){
  52519. if( pBt->pTmpSpace ){
  52520. pBt->pTmpSpace -= 4;
  52521. sqlite3PageFree(pBt->pTmpSpace);
  52522. pBt->pTmpSpace = 0;
  52523. }
  52524. }
  52525. /*
  52526. ** Close an open database and invalidate all cursors.
  52527. */
  52528. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  52529. BtShared *pBt = p->pBt;
  52530. BtCursor *pCur;
  52531. /* Close all cursors opened via this handle. */
  52532. assert( sqlite3_mutex_held(p->db->mutex) );
  52533. sqlite3BtreeEnter(p);
  52534. pCur = pBt->pCursor;
  52535. while( pCur ){
  52536. BtCursor *pTmp = pCur;
  52537. pCur = pCur->pNext;
  52538. if( pTmp->pBtree==p ){
  52539. sqlite3BtreeCloseCursor(pTmp);
  52540. }
  52541. }
  52542. /* Rollback any active transaction and free the handle structure.
  52543. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  52544. ** this handle.
  52545. */
  52546. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  52547. sqlite3BtreeLeave(p);
  52548. /* If there are still other outstanding references to the shared-btree
  52549. ** structure, return now. The remainder of this procedure cleans
  52550. ** up the shared-btree.
  52551. */
  52552. assert( p->wantToLock==0 && p->locked==0 );
  52553. if( !p->sharable || removeFromSharingList(pBt) ){
  52554. /* The pBt is no longer on the sharing list, so we can access
  52555. ** it without having to hold the mutex.
  52556. **
  52557. ** Clean out and delete the BtShared object.
  52558. */
  52559. assert( !pBt->pCursor );
  52560. sqlite3PagerClose(pBt->pPager);
  52561. if( pBt->xFreeSchema && pBt->pSchema ){
  52562. pBt->xFreeSchema(pBt->pSchema);
  52563. }
  52564. sqlite3DbFree(0, pBt->pSchema);
  52565. freeTempSpace(pBt);
  52566. sqlite3_free(pBt);
  52567. }
  52568. #ifndef SQLITE_OMIT_SHARED_CACHE
  52569. assert( p->wantToLock==0 );
  52570. assert( p->locked==0 );
  52571. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  52572. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  52573. #endif
  52574. sqlite3_free(p);
  52575. return SQLITE_OK;
  52576. }
  52577. /*
  52578. ** Change the limit on the number of pages allowed in the cache.
  52579. **
  52580. ** The maximum number of cache pages is set to the absolute
  52581. ** value of mxPage. If mxPage is negative, the pager will
  52582. ** operate asynchronously - it will not stop to do fsync()s
  52583. ** to insure data is written to the disk surface before
  52584. ** continuing. Transactions still work if synchronous is off,
  52585. ** and the database cannot be corrupted if this program
  52586. ** crashes. But if the operating system crashes or there is
  52587. ** an abrupt power failure when synchronous is off, the database
  52588. ** could be left in an inconsistent and unrecoverable state.
  52589. ** Synchronous is on by default so database corruption is not
  52590. ** normally a worry.
  52591. */
  52592. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  52593. BtShared *pBt = p->pBt;
  52594. assert( sqlite3_mutex_held(p->db->mutex) );
  52595. sqlite3BtreeEnter(p);
  52596. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  52597. sqlite3BtreeLeave(p);
  52598. return SQLITE_OK;
  52599. }
  52600. #if SQLITE_MAX_MMAP_SIZE>0
  52601. /*
  52602. ** Change the limit on the amount of the database file that may be
  52603. ** memory mapped.
  52604. */
  52605. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  52606. BtShared *pBt = p->pBt;
  52607. assert( sqlite3_mutex_held(p->db->mutex) );
  52608. sqlite3BtreeEnter(p);
  52609. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  52610. sqlite3BtreeLeave(p);
  52611. return SQLITE_OK;
  52612. }
  52613. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  52614. /*
  52615. ** Change the way data is synced to disk in order to increase or decrease
  52616. ** how well the database resists damage due to OS crashes and power
  52617. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  52618. ** there is a high probability of damage) Level 2 is the default. There
  52619. ** is a very low but non-zero probability of damage. Level 3 reduces the
  52620. ** probability of damage to near zero but with a write performance reduction.
  52621. */
  52622. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  52623. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  52624. Btree *p, /* The btree to set the safety level on */
  52625. unsigned pgFlags /* Various PAGER_* flags */
  52626. ){
  52627. BtShared *pBt = p->pBt;
  52628. assert( sqlite3_mutex_held(p->db->mutex) );
  52629. sqlite3BtreeEnter(p);
  52630. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  52631. sqlite3BtreeLeave(p);
  52632. return SQLITE_OK;
  52633. }
  52634. #endif
  52635. /*
  52636. ** Return TRUE if the given btree is set to safety level 1. In other
  52637. ** words, return TRUE if no sync() occurs on the disk files.
  52638. */
  52639. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  52640. BtShared *pBt = p->pBt;
  52641. int rc;
  52642. assert( sqlite3_mutex_held(p->db->mutex) );
  52643. sqlite3BtreeEnter(p);
  52644. assert( pBt && pBt->pPager );
  52645. rc = sqlite3PagerNosync(pBt->pPager);
  52646. sqlite3BtreeLeave(p);
  52647. return rc;
  52648. }
  52649. /*
  52650. ** Change the default pages size and the number of reserved bytes per page.
  52651. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  52652. ** without changing anything.
  52653. **
  52654. ** The page size must be a power of 2 between 512 and 65536. If the page
  52655. ** size supplied does not meet this constraint then the page size is not
  52656. ** changed.
  52657. **
  52658. ** Page sizes are constrained to be a power of two so that the region
  52659. ** of the database file used for locking (beginning at PENDING_BYTE,
  52660. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  52661. ** at the beginning of a page.
  52662. **
  52663. ** If parameter nReserve is less than zero, then the number of reserved
  52664. ** bytes per page is left unchanged.
  52665. **
  52666. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  52667. ** and autovacuum mode can no longer be changed.
  52668. */
  52669. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  52670. int rc = SQLITE_OK;
  52671. BtShared *pBt = p->pBt;
  52672. assert( nReserve>=-1 && nReserve<=255 );
  52673. sqlite3BtreeEnter(p);
  52674. #if SQLITE_HAS_CODEC
  52675. if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
  52676. #endif
  52677. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  52678. sqlite3BtreeLeave(p);
  52679. return SQLITE_READONLY;
  52680. }
  52681. if( nReserve<0 ){
  52682. nReserve = pBt->pageSize - pBt->usableSize;
  52683. }
  52684. assert( nReserve>=0 && nReserve<=255 );
  52685. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  52686. ((pageSize-1)&pageSize)==0 ){
  52687. assert( (pageSize & 7)==0 );
  52688. assert( !pBt->pCursor );
  52689. pBt->pageSize = (u32)pageSize;
  52690. freeTempSpace(pBt);
  52691. }
  52692. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  52693. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  52694. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  52695. sqlite3BtreeLeave(p);
  52696. return rc;
  52697. }
  52698. /*
  52699. ** Return the currently defined page size
  52700. */
  52701. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  52702. return p->pBt->pageSize;
  52703. }
  52704. /*
  52705. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  52706. ** may only be called if it is guaranteed that the b-tree mutex is already
  52707. ** held.
  52708. **
  52709. ** This is useful in one special case in the backup API code where it is
  52710. ** known that the shared b-tree mutex is held, but the mutex on the
  52711. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  52712. ** were to be called, it might collide with some other operation on the
  52713. ** database handle that owns *p, causing undefined behavior.
  52714. */
  52715. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  52716. int n;
  52717. assert( sqlite3_mutex_held(p->pBt->mutex) );
  52718. n = p->pBt->pageSize - p->pBt->usableSize;
  52719. return n;
  52720. }
  52721. /*
  52722. ** Return the number of bytes of space at the end of every page that
  52723. ** are intentually left unused. This is the "reserved" space that is
  52724. ** sometimes used by extensions.
  52725. **
  52726. ** If SQLITE_HAS_MUTEX is defined then the number returned is the
  52727. ** greater of the current reserved space and the maximum requested
  52728. ** reserve space.
  52729. */
  52730. SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
  52731. int n;
  52732. sqlite3BtreeEnter(p);
  52733. n = sqlite3BtreeGetReserveNoMutex(p);
  52734. #ifdef SQLITE_HAS_CODEC
  52735. if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
  52736. #endif
  52737. sqlite3BtreeLeave(p);
  52738. return n;
  52739. }
  52740. /*
  52741. ** Set the maximum page count for a database if mxPage is positive.
  52742. ** No changes are made if mxPage is 0 or negative.
  52743. ** Regardless of the value of mxPage, return the maximum page count.
  52744. */
  52745. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  52746. int n;
  52747. sqlite3BtreeEnter(p);
  52748. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  52749. sqlite3BtreeLeave(p);
  52750. return n;
  52751. }
  52752. /*
  52753. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  52754. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  52755. ** setting after the change.
  52756. */
  52757. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  52758. int b;
  52759. if( p==0 ) return 0;
  52760. sqlite3BtreeEnter(p);
  52761. if( newFlag>=0 ){
  52762. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  52763. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  52764. }
  52765. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  52766. sqlite3BtreeLeave(p);
  52767. return b;
  52768. }
  52769. /*
  52770. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  52771. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  52772. ** is disabled. The default value for the auto-vacuum property is
  52773. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  52774. */
  52775. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  52776. #ifdef SQLITE_OMIT_AUTOVACUUM
  52777. return SQLITE_READONLY;
  52778. #else
  52779. BtShared *pBt = p->pBt;
  52780. int rc = SQLITE_OK;
  52781. u8 av = (u8)autoVacuum;
  52782. sqlite3BtreeEnter(p);
  52783. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  52784. rc = SQLITE_READONLY;
  52785. }else{
  52786. pBt->autoVacuum = av ?1:0;
  52787. pBt->incrVacuum = av==2 ?1:0;
  52788. }
  52789. sqlite3BtreeLeave(p);
  52790. return rc;
  52791. #endif
  52792. }
  52793. /*
  52794. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  52795. ** enabled 1 is returned. Otherwise 0.
  52796. */
  52797. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  52798. #ifdef SQLITE_OMIT_AUTOVACUUM
  52799. return BTREE_AUTOVACUUM_NONE;
  52800. #else
  52801. int rc;
  52802. sqlite3BtreeEnter(p);
  52803. rc = (
  52804. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  52805. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  52806. BTREE_AUTOVACUUM_INCR
  52807. );
  52808. sqlite3BtreeLeave(p);
  52809. return rc;
  52810. #endif
  52811. }
  52812. /*
  52813. ** Get a reference to pPage1 of the database file. This will
  52814. ** also acquire a readlock on that file.
  52815. **
  52816. ** SQLITE_OK is returned on success. If the file is not a
  52817. ** well-formed database file, then SQLITE_CORRUPT is returned.
  52818. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  52819. ** is returned if we run out of memory.
  52820. */
  52821. static int lockBtree(BtShared *pBt){
  52822. int rc; /* Result code from subfunctions */
  52823. MemPage *pPage1; /* Page 1 of the database file */
  52824. int nPage; /* Number of pages in the database */
  52825. int nPageFile = 0; /* Number of pages in the database file */
  52826. int nPageHeader; /* Number of pages in the database according to hdr */
  52827. assert( sqlite3_mutex_held(pBt->mutex) );
  52828. assert( pBt->pPage1==0 );
  52829. rc = sqlite3PagerSharedLock(pBt->pPager);
  52830. if( rc!=SQLITE_OK ) return rc;
  52831. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  52832. if( rc!=SQLITE_OK ) return rc;
  52833. /* Do some checking to help insure the file we opened really is
  52834. ** a valid database file.
  52835. */
  52836. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  52837. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  52838. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  52839. nPage = nPageFile;
  52840. }
  52841. if( nPage>0 ){
  52842. u32 pageSize;
  52843. u32 usableSize;
  52844. u8 *page1 = pPage1->aData;
  52845. rc = SQLITE_NOTADB;
  52846. /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
  52847. ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
  52848. ** 61 74 20 33 00. */
  52849. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  52850. goto page1_init_failed;
  52851. }
  52852. #ifdef SQLITE_OMIT_WAL
  52853. if( page1[18]>1 ){
  52854. pBt->btsFlags |= BTS_READ_ONLY;
  52855. }
  52856. if( page1[19]>1 ){
  52857. goto page1_init_failed;
  52858. }
  52859. #else
  52860. if( page1[18]>2 ){
  52861. pBt->btsFlags |= BTS_READ_ONLY;
  52862. }
  52863. if( page1[19]>2 ){
  52864. goto page1_init_failed;
  52865. }
  52866. /* If the write version is set to 2, this database should be accessed
  52867. ** in WAL mode. If the log is not already open, open it now. Then
  52868. ** return SQLITE_OK and return without populating BtShared.pPage1.
  52869. ** The caller detects this and calls this function again. This is
  52870. ** required as the version of page 1 currently in the page1 buffer
  52871. ** may not be the latest version - there may be a newer one in the log
  52872. ** file.
  52873. */
  52874. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  52875. int isOpen = 0;
  52876. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  52877. if( rc!=SQLITE_OK ){
  52878. goto page1_init_failed;
  52879. }else if( isOpen==0 ){
  52880. releasePage(pPage1);
  52881. return SQLITE_OK;
  52882. }
  52883. rc = SQLITE_NOTADB;
  52884. }
  52885. #endif
  52886. /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
  52887. ** fractions and the leaf payload fraction values must be 64, 32, and 32.
  52888. **
  52889. ** The original design allowed these amounts to vary, but as of
  52890. ** version 3.6.0, we require them to be fixed.
  52891. */
  52892. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  52893. goto page1_init_failed;
  52894. }
  52895. /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
  52896. ** determined by the 2-byte integer located at an offset of 16 bytes from
  52897. ** the beginning of the database file. */
  52898. pageSize = (page1[16]<<8) | (page1[17]<<16);
  52899. /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
  52900. ** between 512 and 65536 inclusive. */
  52901. if( ((pageSize-1)&pageSize)!=0
  52902. || pageSize>SQLITE_MAX_PAGE_SIZE
  52903. || pageSize<=256
  52904. ){
  52905. goto page1_init_failed;
  52906. }
  52907. assert( (pageSize & 7)==0 );
  52908. /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
  52909. ** integer at offset 20 is the number of bytes of space at the end of
  52910. ** each page to reserve for extensions.
  52911. **
  52912. ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
  52913. ** determined by the one-byte unsigned integer found at an offset of 20
  52914. ** into the database file header. */
  52915. usableSize = pageSize - page1[20];
  52916. if( (u32)pageSize!=pBt->pageSize ){
  52917. /* After reading the first page of the database assuming a page size
  52918. ** of BtShared.pageSize, we have discovered that the page-size is
  52919. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  52920. ** zero and return SQLITE_OK. The caller will call this function
  52921. ** again with the correct page-size.
  52922. */
  52923. releasePage(pPage1);
  52924. pBt->usableSize = usableSize;
  52925. pBt->pageSize = pageSize;
  52926. freeTempSpace(pBt);
  52927. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  52928. pageSize-usableSize);
  52929. return rc;
  52930. }
  52931. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  52932. rc = SQLITE_CORRUPT_BKPT;
  52933. goto page1_init_failed;
  52934. }
  52935. /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
  52936. ** be less than 480. In other words, if the page size is 512, then the
  52937. ** reserved space size cannot exceed 32. */
  52938. if( usableSize<480 ){
  52939. goto page1_init_failed;
  52940. }
  52941. pBt->pageSize = pageSize;
  52942. pBt->usableSize = usableSize;
  52943. #ifndef SQLITE_OMIT_AUTOVACUUM
  52944. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  52945. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  52946. #endif
  52947. }
  52948. /* maxLocal is the maximum amount of payload to store locally for
  52949. ** a cell. Make sure it is small enough so that at least minFanout
  52950. ** cells can will fit on one page. We assume a 10-byte page header.
  52951. ** Besides the payload, the cell must store:
  52952. ** 2-byte pointer to the cell
  52953. ** 4-byte child pointer
  52954. ** 9-byte nKey value
  52955. ** 4-byte nData value
  52956. ** 4-byte overflow page pointer
  52957. ** So a cell consists of a 2-byte pointer, a header which is as much as
  52958. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  52959. ** page pointer.
  52960. */
  52961. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  52962. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  52963. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  52964. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  52965. if( pBt->maxLocal>127 ){
  52966. pBt->max1bytePayload = 127;
  52967. }else{
  52968. pBt->max1bytePayload = (u8)pBt->maxLocal;
  52969. }
  52970. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  52971. pBt->pPage1 = pPage1;
  52972. pBt->nPage = nPage;
  52973. return SQLITE_OK;
  52974. page1_init_failed:
  52975. releasePage(pPage1);
  52976. pBt->pPage1 = 0;
  52977. return rc;
  52978. }
  52979. #ifndef NDEBUG
  52980. /*
  52981. ** Return the number of cursors open on pBt. This is for use
  52982. ** in assert() expressions, so it is only compiled if NDEBUG is not
  52983. ** defined.
  52984. **
  52985. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  52986. ** false then all cursors are counted.
  52987. **
  52988. ** For the purposes of this routine, a cursor is any cursor that
  52989. ** is capable of reading or writing to the database. Cursors that
  52990. ** have been tripped into the CURSOR_FAULT state are not counted.
  52991. */
  52992. static int countValidCursors(BtShared *pBt, int wrOnly){
  52993. BtCursor *pCur;
  52994. int r = 0;
  52995. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  52996. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  52997. && pCur->eState!=CURSOR_FAULT ) r++;
  52998. }
  52999. return r;
  53000. }
  53001. #endif
  53002. /*
  53003. ** If there are no outstanding cursors and we are not in the middle
  53004. ** of a transaction but there is a read lock on the database, then
  53005. ** this routine unrefs the first page of the database file which
  53006. ** has the effect of releasing the read lock.
  53007. **
  53008. ** If there is a transaction in progress, this routine is a no-op.
  53009. */
  53010. static void unlockBtreeIfUnused(BtShared *pBt){
  53011. assert( sqlite3_mutex_held(pBt->mutex) );
  53012. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  53013. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  53014. MemPage *pPage1 = pBt->pPage1;
  53015. assert( pPage1->aData );
  53016. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  53017. pBt->pPage1 = 0;
  53018. releasePageNotNull(pPage1);
  53019. }
  53020. }
  53021. /*
  53022. ** If pBt points to an empty file then convert that empty file
  53023. ** into a new empty database by initializing the first page of
  53024. ** the database.
  53025. */
  53026. static int newDatabase(BtShared *pBt){
  53027. MemPage *pP1;
  53028. unsigned char *data;
  53029. int rc;
  53030. assert( sqlite3_mutex_held(pBt->mutex) );
  53031. if( pBt->nPage>0 ){
  53032. return SQLITE_OK;
  53033. }
  53034. pP1 = pBt->pPage1;
  53035. assert( pP1!=0 );
  53036. data = pP1->aData;
  53037. rc = sqlite3PagerWrite(pP1->pDbPage);
  53038. if( rc ) return rc;
  53039. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  53040. assert( sizeof(zMagicHeader)==16 );
  53041. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  53042. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  53043. data[18] = 1;
  53044. data[19] = 1;
  53045. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  53046. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  53047. data[21] = 64;
  53048. data[22] = 32;
  53049. data[23] = 32;
  53050. memset(&data[24], 0, 100-24);
  53051. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  53052. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  53053. #ifndef SQLITE_OMIT_AUTOVACUUM
  53054. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  53055. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  53056. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  53057. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  53058. #endif
  53059. pBt->nPage = 1;
  53060. data[31] = 1;
  53061. return SQLITE_OK;
  53062. }
  53063. /*
  53064. ** Initialize the first page of the database file (creating a database
  53065. ** consisting of a single page and no schema objects). Return SQLITE_OK
  53066. ** if successful, or an SQLite error code otherwise.
  53067. */
  53068. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  53069. int rc;
  53070. sqlite3BtreeEnter(p);
  53071. p->pBt->nPage = 0;
  53072. rc = newDatabase(p->pBt);
  53073. sqlite3BtreeLeave(p);
  53074. return rc;
  53075. }
  53076. /*
  53077. ** Attempt to start a new transaction. A write-transaction
  53078. ** is started if the second argument is nonzero, otherwise a read-
  53079. ** transaction. If the second argument is 2 or more and exclusive
  53080. ** transaction is started, meaning that no other process is allowed
  53081. ** to access the database. A preexisting transaction may not be
  53082. ** upgraded to exclusive by calling this routine a second time - the
  53083. ** exclusivity flag only works for a new transaction.
  53084. **
  53085. ** A write-transaction must be started before attempting any
  53086. ** changes to the database. None of the following routines
  53087. ** will work unless a transaction is started first:
  53088. **
  53089. ** sqlite3BtreeCreateTable()
  53090. ** sqlite3BtreeCreateIndex()
  53091. ** sqlite3BtreeClearTable()
  53092. ** sqlite3BtreeDropTable()
  53093. ** sqlite3BtreeInsert()
  53094. ** sqlite3BtreeDelete()
  53095. ** sqlite3BtreeUpdateMeta()
  53096. **
  53097. ** If an initial attempt to acquire the lock fails because of lock contention
  53098. ** and the database was previously unlocked, then invoke the busy handler
  53099. ** if there is one. But if there was previously a read-lock, do not
  53100. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  53101. ** returned when there is already a read-lock in order to avoid a deadlock.
  53102. **
  53103. ** Suppose there are two processes A and B. A has a read lock and B has
  53104. ** a reserved lock. B tries to promote to exclusive but is blocked because
  53105. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  53106. ** One or the other of the two processes must give way or there can be
  53107. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  53108. ** when A already has a read lock, we encourage A to give up and let B
  53109. ** proceed.
  53110. */
  53111. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  53112. sqlite3 *pBlock = 0;
  53113. BtShared *pBt = p->pBt;
  53114. int rc = SQLITE_OK;
  53115. sqlite3BtreeEnter(p);
  53116. btreeIntegrity(p);
  53117. /* If the btree is already in a write-transaction, or it
  53118. ** is already in a read-transaction and a read-transaction
  53119. ** is requested, this is a no-op.
  53120. */
  53121. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  53122. goto trans_begun;
  53123. }
  53124. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  53125. /* Write transactions are not possible on a read-only database */
  53126. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  53127. rc = SQLITE_READONLY;
  53128. goto trans_begun;
  53129. }
  53130. #ifndef SQLITE_OMIT_SHARED_CACHE
  53131. /* If another database handle has already opened a write transaction
  53132. ** on this shared-btree structure and a second write transaction is
  53133. ** requested, return SQLITE_LOCKED.
  53134. */
  53135. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  53136. || (pBt->btsFlags & BTS_PENDING)!=0
  53137. ){
  53138. pBlock = pBt->pWriter->db;
  53139. }else if( wrflag>1 ){
  53140. BtLock *pIter;
  53141. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  53142. if( pIter->pBtree!=p ){
  53143. pBlock = pIter->pBtree->db;
  53144. break;
  53145. }
  53146. }
  53147. }
  53148. if( pBlock ){
  53149. sqlite3ConnectionBlocked(p->db, pBlock);
  53150. rc = SQLITE_LOCKED_SHAREDCACHE;
  53151. goto trans_begun;
  53152. }
  53153. #endif
  53154. /* Any read-only or read-write transaction implies a read-lock on
  53155. ** page 1. So if some other shared-cache client already has a write-lock
  53156. ** on page 1, the transaction cannot be opened. */
  53157. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  53158. if( SQLITE_OK!=rc ) goto trans_begun;
  53159. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  53160. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  53161. do {
  53162. /* Call lockBtree() until either pBt->pPage1 is populated or
  53163. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  53164. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  53165. ** reading page 1 it discovers that the page-size of the database
  53166. ** file is not pBt->pageSize. In this case lockBtree() will update
  53167. ** pBt->pageSize to the page-size of the file on disk.
  53168. */
  53169. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  53170. if( rc==SQLITE_OK && wrflag ){
  53171. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  53172. rc = SQLITE_READONLY;
  53173. }else{
  53174. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  53175. if( rc==SQLITE_OK ){
  53176. rc = newDatabase(pBt);
  53177. }
  53178. }
  53179. }
  53180. if( rc!=SQLITE_OK ){
  53181. unlockBtreeIfUnused(pBt);
  53182. }
  53183. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  53184. btreeInvokeBusyHandler(pBt) );
  53185. if( rc==SQLITE_OK ){
  53186. if( p->inTrans==TRANS_NONE ){
  53187. pBt->nTransaction++;
  53188. #ifndef SQLITE_OMIT_SHARED_CACHE
  53189. if( p->sharable ){
  53190. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  53191. p->lock.eLock = READ_LOCK;
  53192. p->lock.pNext = pBt->pLock;
  53193. pBt->pLock = &p->lock;
  53194. }
  53195. #endif
  53196. }
  53197. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  53198. if( p->inTrans>pBt->inTransaction ){
  53199. pBt->inTransaction = p->inTrans;
  53200. }
  53201. if( wrflag ){
  53202. MemPage *pPage1 = pBt->pPage1;
  53203. #ifndef SQLITE_OMIT_SHARED_CACHE
  53204. assert( !pBt->pWriter );
  53205. pBt->pWriter = p;
  53206. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  53207. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  53208. #endif
  53209. /* If the db-size header field is incorrect (as it may be if an old
  53210. ** client has been writing the database file), update it now. Doing
  53211. ** this sooner rather than later means the database size can safely
  53212. ** re-read the database size from page 1 if a savepoint or transaction
  53213. ** rollback occurs within the transaction.
  53214. */
  53215. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  53216. rc = sqlite3PagerWrite(pPage1->pDbPage);
  53217. if( rc==SQLITE_OK ){
  53218. put4byte(&pPage1->aData[28], pBt->nPage);
  53219. }
  53220. }
  53221. }
  53222. }
  53223. trans_begun:
  53224. if( rc==SQLITE_OK && wrflag ){
  53225. /* This call makes sure that the pager has the correct number of
  53226. ** open savepoints. If the second parameter is greater than 0 and
  53227. ** the sub-journal is not already open, then it will be opened here.
  53228. */
  53229. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  53230. }
  53231. btreeIntegrity(p);
  53232. sqlite3BtreeLeave(p);
  53233. return rc;
  53234. }
  53235. #ifndef SQLITE_OMIT_AUTOVACUUM
  53236. /*
  53237. ** Set the pointer-map entries for all children of page pPage. Also, if
  53238. ** pPage contains cells that point to overflow pages, set the pointer
  53239. ** map entries for the overflow pages as well.
  53240. */
  53241. static int setChildPtrmaps(MemPage *pPage){
  53242. int i; /* Counter variable */
  53243. int nCell; /* Number of cells in page pPage */
  53244. int rc; /* Return code */
  53245. BtShared *pBt = pPage->pBt;
  53246. u8 isInitOrig = pPage->isInit;
  53247. Pgno pgno = pPage->pgno;
  53248. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53249. rc = btreeInitPage(pPage);
  53250. if( rc!=SQLITE_OK ){
  53251. goto set_child_ptrmaps_out;
  53252. }
  53253. nCell = pPage->nCell;
  53254. for(i=0; i<nCell; i++){
  53255. u8 *pCell = findCell(pPage, i);
  53256. ptrmapPutOvflPtr(pPage, pCell, &rc);
  53257. if( !pPage->leaf ){
  53258. Pgno childPgno = get4byte(pCell);
  53259. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  53260. }
  53261. }
  53262. if( !pPage->leaf ){
  53263. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53264. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  53265. }
  53266. set_child_ptrmaps_out:
  53267. pPage->isInit = isInitOrig;
  53268. return rc;
  53269. }
  53270. /*
  53271. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  53272. ** that it points to iTo. Parameter eType describes the type of pointer to
  53273. ** be modified, as follows:
  53274. **
  53275. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  53276. ** page of pPage.
  53277. **
  53278. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  53279. ** page pointed to by one of the cells on pPage.
  53280. **
  53281. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  53282. ** overflow page in the list.
  53283. */
  53284. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  53285. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53286. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  53287. if( eType==PTRMAP_OVERFLOW2 ){
  53288. /* The pointer is always the first 4 bytes of the page in this case. */
  53289. if( get4byte(pPage->aData)!=iFrom ){
  53290. return SQLITE_CORRUPT_BKPT;
  53291. }
  53292. put4byte(pPage->aData, iTo);
  53293. }else{
  53294. u8 isInitOrig = pPage->isInit;
  53295. int i;
  53296. int nCell;
  53297. int rc;
  53298. rc = btreeInitPage(pPage);
  53299. if( rc ) return rc;
  53300. nCell = pPage->nCell;
  53301. for(i=0; i<nCell; i++){
  53302. u8 *pCell = findCell(pPage, i);
  53303. if( eType==PTRMAP_OVERFLOW1 ){
  53304. CellInfo info;
  53305. pPage->xParseCell(pPage, pCell, &info);
  53306. if( info.iOverflow
  53307. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  53308. && iFrom==get4byte(&pCell[info.iOverflow])
  53309. ){
  53310. put4byte(&pCell[info.iOverflow], iTo);
  53311. break;
  53312. }
  53313. }else{
  53314. if( get4byte(pCell)==iFrom ){
  53315. put4byte(pCell, iTo);
  53316. break;
  53317. }
  53318. }
  53319. }
  53320. if( i==nCell ){
  53321. if( eType!=PTRMAP_BTREE ||
  53322. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  53323. return SQLITE_CORRUPT_BKPT;
  53324. }
  53325. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  53326. }
  53327. pPage->isInit = isInitOrig;
  53328. }
  53329. return SQLITE_OK;
  53330. }
  53331. /*
  53332. ** Move the open database page pDbPage to location iFreePage in the
  53333. ** database. The pDbPage reference remains valid.
  53334. **
  53335. ** The isCommit flag indicates that there is no need to remember that
  53336. ** the journal needs to be sync()ed before database page pDbPage->pgno
  53337. ** can be written to. The caller has already promised not to write to that
  53338. ** page.
  53339. */
  53340. static int relocatePage(
  53341. BtShared *pBt, /* Btree */
  53342. MemPage *pDbPage, /* Open page to move */
  53343. u8 eType, /* Pointer map 'type' entry for pDbPage */
  53344. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  53345. Pgno iFreePage, /* The location to move pDbPage to */
  53346. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  53347. ){
  53348. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  53349. Pgno iDbPage = pDbPage->pgno;
  53350. Pager *pPager = pBt->pPager;
  53351. int rc;
  53352. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  53353. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  53354. assert( sqlite3_mutex_held(pBt->mutex) );
  53355. assert( pDbPage->pBt==pBt );
  53356. /* Move page iDbPage from its current location to page number iFreePage */
  53357. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  53358. iDbPage, iFreePage, iPtrPage, eType));
  53359. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  53360. if( rc!=SQLITE_OK ){
  53361. return rc;
  53362. }
  53363. pDbPage->pgno = iFreePage;
  53364. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  53365. ** that point to overflow pages. The pointer map entries for all these
  53366. ** pages need to be changed.
  53367. **
  53368. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  53369. ** pointer to a subsequent overflow page. If this is the case, then
  53370. ** the pointer map needs to be updated for the subsequent overflow page.
  53371. */
  53372. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  53373. rc = setChildPtrmaps(pDbPage);
  53374. if( rc!=SQLITE_OK ){
  53375. return rc;
  53376. }
  53377. }else{
  53378. Pgno nextOvfl = get4byte(pDbPage->aData);
  53379. if( nextOvfl!=0 ){
  53380. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  53381. if( rc!=SQLITE_OK ){
  53382. return rc;
  53383. }
  53384. }
  53385. }
  53386. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  53387. ** that it points at iFreePage. Also fix the pointer map entry for
  53388. ** iPtrPage.
  53389. */
  53390. if( eType!=PTRMAP_ROOTPAGE ){
  53391. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  53392. if( rc!=SQLITE_OK ){
  53393. return rc;
  53394. }
  53395. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  53396. if( rc!=SQLITE_OK ){
  53397. releasePage(pPtrPage);
  53398. return rc;
  53399. }
  53400. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  53401. releasePage(pPtrPage);
  53402. if( rc==SQLITE_OK ){
  53403. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  53404. }
  53405. }
  53406. return rc;
  53407. }
  53408. /* Forward declaration required by incrVacuumStep(). */
  53409. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  53410. /*
  53411. ** Perform a single step of an incremental-vacuum. If successful, return
  53412. ** SQLITE_OK. If there is no work to do (and therefore no point in
  53413. ** calling this function again), return SQLITE_DONE. Or, if an error
  53414. ** occurs, return some other error code.
  53415. **
  53416. ** More specifically, this function attempts to re-organize the database so
  53417. ** that the last page of the file currently in use is no longer in use.
  53418. **
  53419. ** Parameter nFin is the number of pages that this database would contain
  53420. ** were this function called until it returns SQLITE_DONE.
  53421. **
  53422. ** If the bCommit parameter is non-zero, this function assumes that the
  53423. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  53424. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  53425. ** operation, or false for an incremental vacuum.
  53426. */
  53427. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  53428. Pgno nFreeList; /* Number of pages still on the free-list */
  53429. int rc;
  53430. assert( sqlite3_mutex_held(pBt->mutex) );
  53431. assert( iLastPg>nFin );
  53432. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  53433. u8 eType;
  53434. Pgno iPtrPage;
  53435. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  53436. if( nFreeList==0 ){
  53437. return SQLITE_DONE;
  53438. }
  53439. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  53440. if( rc!=SQLITE_OK ){
  53441. return rc;
  53442. }
  53443. if( eType==PTRMAP_ROOTPAGE ){
  53444. return SQLITE_CORRUPT_BKPT;
  53445. }
  53446. if( eType==PTRMAP_FREEPAGE ){
  53447. if( bCommit==0 ){
  53448. /* Remove the page from the files free-list. This is not required
  53449. ** if bCommit is non-zero. In that case, the free-list will be
  53450. ** truncated to zero after this function returns, so it doesn't
  53451. ** matter if it still contains some garbage entries.
  53452. */
  53453. Pgno iFreePg;
  53454. MemPage *pFreePg;
  53455. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  53456. if( rc!=SQLITE_OK ){
  53457. return rc;
  53458. }
  53459. assert( iFreePg==iLastPg );
  53460. releasePage(pFreePg);
  53461. }
  53462. } else {
  53463. Pgno iFreePg; /* Index of free page to move pLastPg to */
  53464. MemPage *pLastPg;
  53465. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  53466. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  53467. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  53468. if( rc!=SQLITE_OK ){
  53469. return rc;
  53470. }
  53471. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  53472. ** is swapped with the first free page pulled off the free list.
  53473. **
  53474. ** On the other hand, if bCommit is greater than zero, then keep
  53475. ** looping until a free-page located within the first nFin pages
  53476. ** of the file is found.
  53477. */
  53478. if( bCommit==0 ){
  53479. eMode = BTALLOC_LE;
  53480. iNear = nFin;
  53481. }
  53482. do {
  53483. MemPage *pFreePg;
  53484. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  53485. if( rc!=SQLITE_OK ){
  53486. releasePage(pLastPg);
  53487. return rc;
  53488. }
  53489. releasePage(pFreePg);
  53490. }while( bCommit && iFreePg>nFin );
  53491. assert( iFreePg<iLastPg );
  53492. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  53493. releasePage(pLastPg);
  53494. if( rc!=SQLITE_OK ){
  53495. return rc;
  53496. }
  53497. }
  53498. }
  53499. if( bCommit==0 ){
  53500. do {
  53501. iLastPg--;
  53502. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  53503. pBt->bDoTruncate = 1;
  53504. pBt->nPage = iLastPg;
  53505. }
  53506. return SQLITE_OK;
  53507. }
  53508. /*
  53509. ** The database opened by the first argument is an auto-vacuum database
  53510. ** nOrig pages in size containing nFree free pages. Return the expected
  53511. ** size of the database in pages following an auto-vacuum operation.
  53512. */
  53513. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  53514. int nEntry; /* Number of entries on one ptrmap page */
  53515. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  53516. Pgno nFin; /* Return value */
  53517. nEntry = pBt->usableSize/5;
  53518. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  53519. nFin = nOrig - nFree - nPtrmap;
  53520. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  53521. nFin--;
  53522. }
  53523. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  53524. nFin--;
  53525. }
  53526. return nFin;
  53527. }
  53528. /*
  53529. ** A write-transaction must be opened before calling this function.
  53530. ** It performs a single unit of work towards an incremental vacuum.
  53531. **
  53532. ** If the incremental vacuum is finished after this function has run,
  53533. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  53534. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  53535. */
  53536. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  53537. int rc;
  53538. BtShared *pBt = p->pBt;
  53539. sqlite3BtreeEnter(p);
  53540. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  53541. if( !pBt->autoVacuum ){
  53542. rc = SQLITE_DONE;
  53543. }else{
  53544. Pgno nOrig = btreePagecount(pBt);
  53545. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  53546. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  53547. if( nOrig<nFin ){
  53548. rc = SQLITE_CORRUPT_BKPT;
  53549. }else if( nFree>0 ){
  53550. rc = saveAllCursors(pBt, 0, 0);
  53551. if( rc==SQLITE_OK ){
  53552. invalidateAllOverflowCache(pBt);
  53553. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  53554. }
  53555. if( rc==SQLITE_OK ){
  53556. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  53557. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  53558. }
  53559. }else{
  53560. rc = SQLITE_DONE;
  53561. }
  53562. }
  53563. sqlite3BtreeLeave(p);
  53564. return rc;
  53565. }
  53566. /*
  53567. ** This routine is called prior to sqlite3PagerCommit when a transaction
  53568. ** is committed for an auto-vacuum database.
  53569. **
  53570. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  53571. ** the database file should be truncated to during the commit process.
  53572. ** i.e. the database has been reorganized so that only the first *pnTrunc
  53573. ** pages are in use.
  53574. */
  53575. static int autoVacuumCommit(BtShared *pBt){
  53576. int rc = SQLITE_OK;
  53577. Pager *pPager = pBt->pPager;
  53578. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
  53579. assert( sqlite3_mutex_held(pBt->mutex) );
  53580. invalidateAllOverflowCache(pBt);
  53581. assert(pBt->autoVacuum);
  53582. if( !pBt->incrVacuum ){
  53583. Pgno nFin; /* Number of pages in database after autovacuuming */
  53584. Pgno nFree; /* Number of pages on the freelist initially */
  53585. Pgno iFree; /* The next page to be freed */
  53586. Pgno nOrig; /* Database size before freeing */
  53587. nOrig = btreePagecount(pBt);
  53588. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  53589. /* It is not possible to create a database for which the final page
  53590. ** is either a pointer-map page or the pending-byte page. If one
  53591. ** is encountered, this indicates corruption.
  53592. */
  53593. return SQLITE_CORRUPT_BKPT;
  53594. }
  53595. nFree = get4byte(&pBt->pPage1->aData[36]);
  53596. nFin = finalDbSize(pBt, nOrig, nFree);
  53597. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  53598. if( nFin<nOrig ){
  53599. rc = saveAllCursors(pBt, 0, 0);
  53600. }
  53601. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  53602. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  53603. }
  53604. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  53605. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  53606. put4byte(&pBt->pPage1->aData[32], 0);
  53607. put4byte(&pBt->pPage1->aData[36], 0);
  53608. put4byte(&pBt->pPage1->aData[28], nFin);
  53609. pBt->bDoTruncate = 1;
  53610. pBt->nPage = nFin;
  53611. }
  53612. if( rc!=SQLITE_OK ){
  53613. sqlite3PagerRollback(pPager);
  53614. }
  53615. }
  53616. assert( nRef>=sqlite3PagerRefcount(pPager) );
  53617. return rc;
  53618. }
  53619. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  53620. # define setChildPtrmaps(x) SQLITE_OK
  53621. #endif
  53622. /*
  53623. ** This routine does the first phase of a two-phase commit. This routine
  53624. ** causes a rollback journal to be created (if it does not already exist)
  53625. ** and populated with enough information so that if a power loss occurs
  53626. ** the database can be restored to its original state by playing back
  53627. ** the journal. Then the contents of the journal are flushed out to
  53628. ** the disk. After the journal is safely on oxide, the changes to the
  53629. ** database are written into the database file and flushed to oxide.
  53630. ** At the end of this call, the rollback journal still exists on the
  53631. ** disk and we are still holding all locks, so the transaction has not
  53632. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  53633. ** commit process.
  53634. **
  53635. ** This call is a no-op if no write-transaction is currently active on pBt.
  53636. **
  53637. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  53638. ** the name of a master journal file that should be written into the
  53639. ** individual journal file, or is NULL, indicating no master journal file
  53640. ** (single database transaction).
  53641. **
  53642. ** When this is called, the master journal should already have been
  53643. ** created, populated with this journal pointer and synced to disk.
  53644. **
  53645. ** Once this is routine has returned, the only thing required to commit
  53646. ** the write-transaction for this database file is to delete the journal.
  53647. */
  53648. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  53649. int rc = SQLITE_OK;
  53650. if( p->inTrans==TRANS_WRITE ){
  53651. BtShared *pBt = p->pBt;
  53652. sqlite3BtreeEnter(p);
  53653. #ifndef SQLITE_OMIT_AUTOVACUUM
  53654. if( pBt->autoVacuum ){
  53655. rc = autoVacuumCommit(pBt);
  53656. if( rc!=SQLITE_OK ){
  53657. sqlite3BtreeLeave(p);
  53658. return rc;
  53659. }
  53660. }
  53661. if( pBt->bDoTruncate ){
  53662. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  53663. }
  53664. #endif
  53665. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  53666. sqlite3BtreeLeave(p);
  53667. }
  53668. return rc;
  53669. }
  53670. /*
  53671. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  53672. ** at the conclusion of a transaction.
  53673. */
  53674. static void btreeEndTransaction(Btree *p){
  53675. BtShared *pBt = p->pBt;
  53676. sqlite3 *db = p->db;
  53677. assert( sqlite3BtreeHoldsMutex(p) );
  53678. #ifndef SQLITE_OMIT_AUTOVACUUM
  53679. pBt->bDoTruncate = 0;
  53680. #endif
  53681. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  53682. /* If there are other active statements that belong to this database
  53683. ** handle, downgrade to a read-only transaction. The other statements
  53684. ** may still be reading from the database. */
  53685. downgradeAllSharedCacheTableLocks(p);
  53686. p->inTrans = TRANS_READ;
  53687. }else{
  53688. /* If the handle had any kind of transaction open, decrement the
  53689. ** transaction count of the shared btree. If the transaction count
  53690. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  53691. ** call below will unlock the pager. */
  53692. if( p->inTrans!=TRANS_NONE ){
  53693. clearAllSharedCacheTableLocks(p);
  53694. pBt->nTransaction--;
  53695. if( 0==pBt->nTransaction ){
  53696. pBt->inTransaction = TRANS_NONE;
  53697. }
  53698. }
  53699. /* Set the current transaction state to TRANS_NONE and unlock the
  53700. ** pager if this call closed the only read or write transaction. */
  53701. p->inTrans = TRANS_NONE;
  53702. unlockBtreeIfUnused(pBt);
  53703. }
  53704. btreeIntegrity(p);
  53705. }
  53706. /*
  53707. ** Commit the transaction currently in progress.
  53708. **
  53709. ** This routine implements the second phase of a 2-phase commit. The
  53710. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  53711. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  53712. ** routine did all the work of writing information out to disk and flushing the
  53713. ** contents so that they are written onto the disk platter. All this
  53714. ** routine has to do is delete or truncate or zero the header in the
  53715. ** the rollback journal (which causes the transaction to commit) and
  53716. ** drop locks.
  53717. **
  53718. ** Normally, if an error occurs while the pager layer is attempting to
  53719. ** finalize the underlying journal file, this function returns an error and
  53720. ** the upper layer will attempt a rollback. However, if the second argument
  53721. ** is non-zero then this b-tree transaction is part of a multi-file
  53722. ** transaction. In this case, the transaction has already been committed
  53723. ** (by deleting a master journal file) and the caller will ignore this
  53724. ** functions return code. So, even if an error occurs in the pager layer,
  53725. ** reset the b-tree objects internal state to indicate that the write
  53726. ** transaction has been closed. This is quite safe, as the pager will have
  53727. ** transitioned to the error state.
  53728. **
  53729. ** This will release the write lock on the database file. If there
  53730. ** are no active cursors, it also releases the read lock.
  53731. */
  53732. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  53733. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  53734. sqlite3BtreeEnter(p);
  53735. btreeIntegrity(p);
  53736. /* If the handle has a write-transaction open, commit the shared-btrees
  53737. ** transaction and set the shared state to TRANS_READ.
  53738. */
  53739. if( p->inTrans==TRANS_WRITE ){
  53740. int rc;
  53741. BtShared *pBt = p->pBt;
  53742. assert( pBt->inTransaction==TRANS_WRITE );
  53743. assert( pBt->nTransaction>0 );
  53744. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  53745. if( rc!=SQLITE_OK && bCleanup==0 ){
  53746. sqlite3BtreeLeave(p);
  53747. return rc;
  53748. }
  53749. p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
  53750. pBt->inTransaction = TRANS_READ;
  53751. btreeClearHasContent(pBt);
  53752. }
  53753. btreeEndTransaction(p);
  53754. sqlite3BtreeLeave(p);
  53755. return SQLITE_OK;
  53756. }
  53757. /*
  53758. ** Do both phases of a commit.
  53759. */
  53760. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  53761. int rc;
  53762. sqlite3BtreeEnter(p);
  53763. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  53764. if( rc==SQLITE_OK ){
  53765. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  53766. }
  53767. sqlite3BtreeLeave(p);
  53768. return rc;
  53769. }
  53770. /*
  53771. ** This routine sets the state to CURSOR_FAULT and the error
  53772. ** code to errCode for every cursor on any BtShared that pBtree
  53773. ** references. Or if the writeOnly flag is set to 1, then only
  53774. ** trip write cursors and leave read cursors unchanged.
  53775. **
  53776. ** Every cursor is a candidate to be tripped, including cursors
  53777. ** that belong to other database connections that happen to be
  53778. ** sharing the cache with pBtree.
  53779. **
  53780. ** This routine gets called when a rollback occurs. If the writeOnly
  53781. ** flag is true, then only write-cursors need be tripped - read-only
  53782. ** cursors save their current positions so that they may continue
  53783. ** following the rollback. Or, if writeOnly is false, all cursors are
  53784. ** tripped. In general, writeOnly is false if the transaction being
  53785. ** rolled back modified the database schema. In this case b-tree root
  53786. ** pages may be moved or deleted from the database altogether, making
  53787. ** it unsafe for read cursors to continue.
  53788. **
  53789. ** If the writeOnly flag is true and an error is encountered while
  53790. ** saving the current position of a read-only cursor, all cursors,
  53791. ** including all read-cursors are tripped.
  53792. **
  53793. ** SQLITE_OK is returned if successful, or if an error occurs while
  53794. ** saving a cursor position, an SQLite error code.
  53795. */
  53796. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  53797. BtCursor *p;
  53798. int rc = SQLITE_OK;
  53799. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  53800. if( pBtree ){
  53801. sqlite3BtreeEnter(pBtree);
  53802. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  53803. int i;
  53804. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  53805. if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
  53806. rc = saveCursorPosition(p);
  53807. if( rc!=SQLITE_OK ){
  53808. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  53809. break;
  53810. }
  53811. }
  53812. }else{
  53813. sqlite3BtreeClearCursor(p);
  53814. p->eState = CURSOR_FAULT;
  53815. p->skipNext = errCode;
  53816. }
  53817. for(i=0; i<=p->iPage; i++){
  53818. releasePage(p->apPage[i]);
  53819. p->apPage[i] = 0;
  53820. }
  53821. }
  53822. sqlite3BtreeLeave(pBtree);
  53823. }
  53824. return rc;
  53825. }
  53826. /*
  53827. ** Rollback the transaction in progress.
  53828. **
  53829. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  53830. ** Only write cursors are tripped if writeOnly is true but all cursors are
  53831. ** tripped if writeOnly is false. Any attempt to use
  53832. ** a tripped cursor will result in an error.
  53833. **
  53834. ** This will release the write lock on the database file. If there
  53835. ** are no active cursors, it also releases the read lock.
  53836. */
  53837. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  53838. int rc;
  53839. BtShared *pBt = p->pBt;
  53840. MemPage *pPage1;
  53841. assert( writeOnly==1 || writeOnly==0 );
  53842. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  53843. sqlite3BtreeEnter(p);
  53844. if( tripCode==SQLITE_OK ){
  53845. rc = tripCode = saveAllCursors(pBt, 0, 0);
  53846. if( rc ) writeOnly = 0;
  53847. }else{
  53848. rc = SQLITE_OK;
  53849. }
  53850. if( tripCode ){
  53851. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  53852. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  53853. if( rc2!=SQLITE_OK ) rc = rc2;
  53854. }
  53855. btreeIntegrity(p);
  53856. if( p->inTrans==TRANS_WRITE ){
  53857. int rc2;
  53858. assert( TRANS_WRITE==pBt->inTransaction );
  53859. rc2 = sqlite3PagerRollback(pBt->pPager);
  53860. if( rc2!=SQLITE_OK ){
  53861. rc = rc2;
  53862. }
  53863. /* The rollback may have destroyed the pPage1->aData value. So
  53864. ** call btreeGetPage() on page 1 again to make
  53865. ** sure pPage1->aData is set correctly. */
  53866. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  53867. int nPage = get4byte(28+(u8*)pPage1->aData);
  53868. testcase( nPage==0 );
  53869. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  53870. testcase( pBt->nPage!=nPage );
  53871. pBt->nPage = nPage;
  53872. releasePage(pPage1);
  53873. }
  53874. assert( countValidCursors(pBt, 1)==0 );
  53875. pBt->inTransaction = TRANS_READ;
  53876. btreeClearHasContent(pBt);
  53877. }
  53878. btreeEndTransaction(p);
  53879. sqlite3BtreeLeave(p);
  53880. return rc;
  53881. }
  53882. /*
  53883. ** Start a statement subtransaction. The subtransaction can be rolled
  53884. ** back independently of the main transaction. You must start a transaction
  53885. ** before starting a subtransaction. The subtransaction is ended automatically
  53886. ** if the main transaction commits or rolls back.
  53887. **
  53888. ** Statement subtransactions are used around individual SQL statements
  53889. ** that are contained within a BEGIN...COMMIT block. If a constraint
  53890. ** error occurs within the statement, the effect of that one statement
  53891. ** can be rolled back without having to rollback the entire transaction.
  53892. **
  53893. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  53894. ** value passed as the second parameter is the total number of savepoints,
  53895. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  53896. ** are no active savepoints and no other statement-transactions open,
  53897. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  53898. ** using the sqlite3BtreeSavepoint() function.
  53899. */
  53900. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  53901. int rc;
  53902. BtShared *pBt = p->pBt;
  53903. sqlite3BtreeEnter(p);
  53904. assert( p->inTrans==TRANS_WRITE );
  53905. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  53906. assert( iStatement>0 );
  53907. assert( iStatement>p->db->nSavepoint );
  53908. assert( pBt->inTransaction==TRANS_WRITE );
  53909. /* At the pager level, a statement transaction is a savepoint with
  53910. ** an index greater than all savepoints created explicitly using
  53911. ** SQL statements. It is illegal to open, release or rollback any
  53912. ** such savepoints while the statement transaction savepoint is active.
  53913. */
  53914. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  53915. sqlite3BtreeLeave(p);
  53916. return rc;
  53917. }
  53918. /*
  53919. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  53920. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  53921. ** savepoint identified by parameter iSavepoint, depending on the value
  53922. ** of op.
  53923. **
  53924. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  53925. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  53926. ** contents of the entire transaction are rolled back. This is different
  53927. ** from a normal transaction rollback, as no locks are released and the
  53928. ** transaction remains open.
  53929. */
  53930. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  53931. int rc = SQLITE_OK;
  53932. if( p && p->inTrans==TRANS_WRITE ){
  53933. BtShared *pBt = p->pBt;
  53934. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  53935. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  53936. sqlite3BtreeEnter(p);
  53937. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  53938. if( rc==SQLITE_OK ){
  53939. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  53940. pBt->nPage = 0;
  53941. }
  53942. rc = newDatabase(pBt);
  53943. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  53944. /* The database size was written into the offset 28 of the header
  53945. ** when the transaction started, so we know that the value at offset
  53946. ** 28 is nonzero. */
  53947. assert( pBt->nPage>0 );
  53948. }
  53949. sqlite3BtreeLeave(p);
  53950. }
  53951. return rc;
  53952. }
  53953. /*
  53954. ** Create a new cursor for the BTree whose root is on the page
  53955. ** iTable. If a read-only cursor is requested, it is assumed that
  53956. ** the caller already has at least a read-only transaction open
  53957. ** on the database already. If a write-cursor is requested, then
  53958. ** the caller is assumed to have an open write transaction.
  53959. **
  53960. ** If wrFlag==0, then the cursor can only be used for reading.
  53961. ** If wrFlag==1, then the cursor can be used for reading or for
  53962. ** writing if other conditions for writing are also met. These
  53963. ** are the conditions that must be met in order for writing to
  53964. ** be allowed:
  53965. **
  53966. ** 1: The cursor must have been opened with wrFlag==1
  53967. **
  53968. ** 2: Other database connections that share the same pager cache
  53969. ** but which are not in the READ_UNCOMMITTED state may not have
  53970. ** cursors open with wrFlag==0 on the same table. Otherwise
  53971. ** the changes made by this write cursor would be visible to
  53972. ** the read cursors in the other database connection.
  53973. **
  53974. ** 3: The database must be writable (not on read-only media)
  53975. **
  53976. ** 4: There must be an active transaction.
  53977. **
  53978. ** No checking is done to make sure that page iTable really is the
  53979. ** root page of a b-tree. If it is not, then the cursor acquired
  53980. ** will not work correctly.
  53981. **
  53982. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  53983. ** on pCur to initialize the memory space prior to invoking this routine.
  53984. */
  53985. static int btreeCursor(
  53986. Btree *p, /* The btree */
  53987. int iTable, /* Root page of table to open */
  53988. int wrFlag, /* 1 to write. 0 read-only */
  53989. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  53990. BtCursor *pCur /* Space for new cursor */
  53991. ){
  53992. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  53993. BtCursor *pX; /* Looping over other all cursors */
  53994. assert( sqlite3BtreeHoldsMutex(p) );
  53995. assert( wrFlag==0 || wrFlag==1 );
  53996. /* The following assert statements verify that if this is a sharable
  53997. ** b-tree database, the connection is holding the required table locks,
  53998. ** and that no other connection has any open cursor that conflicts with
  53999. ** this lock. */
  54000. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  54001. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  54002. /* Assert that the caller has opened the required transaction. */
  54003. assert( p->inTrans>TRANS_NONE );
  54004. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  54005. assert( pBt->pPage1 && pBt->pPage1->aData );
  54006. assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
  54007. if( wrFlag ){
  54008. allocateTempSpace(pBt);
  54009. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
  54010. }
  54011. if( iTable==1 && btreePagecount(pBt)==0 ){
  54012. assert( wrFlag==0 );
  54013. iTable = 0;
  54014. }
  54015. /* Now that no other errors can occur, finish filling in the BtCursor
  54016. ** variables and link the cursor into the BtShared list. */
  54017. pCur->pgnoRoot = (Pgno)iTable;
  54018. pCur->iPage = -1;
  54019. pCur->pKeyInfo = pKeyInfo;
  54020. pCur->pBtree = p;
  54021. pCur->pBt = pBt;
  54022. assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
  54023. pCur->curFlags = wrFlag;
  54024. pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
  54025. /* If there are two or more cursors on the same btree, then all such
  54026. ** cursors *must* have the BTCF_Multiple flag set. */
  54027. for(pX=pBt->pCursor; pX; pX=pX->pNext){
  54028. if( pX->pgnoRoot==(Pgno)iTable ){
  54029. pX->curFlags |= BTCF_Multiple;
  54030. pCur->curFlags |= BTCF_Multiple;
  54031. }
  54032. }
  54033. pCur->pNext = pBt->pCursor;
  54034. pBt->pCursor = pCur;
  54035. pCur->eState = CURSOR_INVALID;
  54036. return SQLITE_OK;
  54037. }
  54038. SQLITE_PRIVATE int sqlite3BtreeCursor(
  54039. Btree *p, /* The btree */
  54040. int iTable, /* Root page of table to open */
  54041. int wrFlag, /* 1 to write. 0 read-only */
  54042. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  54043. BtCursor *pCur /* Write new cursor here */
  54044. ){
  54045. int rc;
  54046. if( iTable<1 ){
  54047. rc = SQLITE_CORRUPT_BKPT;
  54048. }else{
  54049. sqlite3BtreeEnter(p);
  54050. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  54051. sqlite3BtreeLeave(p);
  54052. }
  54053. return rc;
  54054. }
  54055. /*
  54056. ** Return the size of a BtCursor object in bytes.
  54057. **
  54058. ** This interfaces is needed so that users of cursors can preallocate
  54059. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  54060. ** to users so they cannot do the sizeof() themselves - they must call
  54061. ** this routine.
  54062. */
  54063. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  54064. return ROUND8(sizeof(BtCursor));
  54065. }
  54066. /*
  54067. ** Initialize memory that will be converted into a BtCursor object.
  54068. **
  54069. ** The simple approach here would be to memset() the entire object
  54070. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  54071. ** do not need to be zeroed and they are large, so we can save a lot
  54072. ** of run-time by skipping the initialization of those elements.
  54073. */
  54074. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  54075. memset(p, 0, offsetof(BtCursor, iPage));
  54076. }
  54077. /*
  54078. ** Close a cursor. The read lock on the database file is released
  54079. ** when the last cursor is closed.
  54080. */
  54081. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  54082. Btree *pBtree = pCur->pBtree;
  54083. if( pBtree ){
  54084. int i;
  54085. BtShared *pBt = pCur->pBt;
  54086. sqlite3BtreeEnter(pBtree);
  54087. sqlite3BtreeClearCursor(pCur);
  54088. assert( pBt->pCursor!=0 );
  54089. if( pBt->pCursor==pCur ){
  54090. pBt->pCursor = pCur->pNext;
  54091. }else{
  54092. BtCursor *pPrev = pBt->pCursor;
  54093. do{
  54094. if( pPrev->pNext==pCur ){
  54095. pPrev->pNext = pCur->pNext;
  54096. break;
  54097. }
  54098. pPrev = pPrev->pNext;
  54099. }while( ALWAYS(pPrev) );
  54100. }
  54101. for(i=0; i<=pCur->iPage; i++){
  54102. releasePage(pCur->apPage[i]);
  54103. }
  54104. unlockBtreeIfUnused(pBt);
  54105. sqlite3_free(pCur->aOverflow);
  54106. /* sqlite3_free(pCur); */
  54107. sqlite3BtreeLeave(pBtree);
  54108. }
  54109. return SQLITE_OK;
  54110. }
  54111. /*
  54112. ** Make sure the BtCursor* given in the argument has a valid
  54113. ** BtCursor.info structure. If it is not already valid, call
  54114. ** btreeParseCell() to fill it in.
  54115. **
  54116. ** BtCursor.info is a cache of the information in the current cell.
  54117. ** Using this cache reduces the number of calls to btreeParseCell().
  54118. */
  54119. #ifndef NDEBUG
  54120. static void assertCellInfo(BtCursor *pCur){
  54121. CellInfo info;
  54122. int iPage = pCur->iPage;
  54123. memset(&info, 0, sizeof(info));
  54124. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  54125. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  54126. }
  54127. #else
  54128. #define assertCellInfo(x)
  54129. #endif
  54130. static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur){
  54131. if( pCur->info.nSize==0 ){
  54132. int iPage = pCur->iPage;
  54133. pCur->curFlags |= BTCF_ValidNKey;
  54134. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  54135. }else{
  54136. assertCellInfo(pCur);
  54137. }
  54138. }
  54139. #ifndef NDEBUG /* The next routine used only within assert() statements */
  54140. /*
  54141. ** Return true if the given BtCursor is valid. A valid cursor is one
  54142. ** that is currently pointing to a row in a (non-empty) table.
  54143. ** This is a verification routine is used only within assert() statements.
  54144. */
  54145. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  54146. return pCur && pCur->eState==CURSOR_VALID;
  54147. }
  54148. #endif /* NDEBUG */
  54149. /*
  54150. ** Set *pSize to the size of the buffer needed to hold the value of
  54151. ** the key for the current entry. If the cursor is not pointing
  54152. ** to a valid entry, *pSize is set to 0.
  54153. **
  54154. ** For a table with the INTKEY flag set, this routine returns the key
  54155. ** itself, not the number of bytes in the key.
  54156. **
  54157. ** The caller must position the cursor prior to invoking this routine.
  54158. **
  54159. ** This routine cannot fail. It always returns SQLITE_OK.
  54160. */
  54161. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  54162. assert( cursorHoldsMutex(pCur) );
  54163. assert( pCur->eState==CURSOR_VALID );
  54164. getCellInfo(pCur);
  54165. *pSize = pCur->info.nKey;
  54166. return SQLITE_OK;
  54167. }
  54168. /*
  54169. ** Set *pSize to the number of bytes of data in the entry the
  54170. ** cursor currently points to.
  54171. **
  54172. ** The caller must guarantee that the cursor is pointing to a non-NULL
  54173. ** valid entry. In other words, the calling procedure must guarantee
  54174. ** that the cursor has Cursor.eState==CURSOR_VALID.
  54175. **
  54176. ** Failure is not possible. This function always returns SQLITE_OK.
  54177. ** It might just as well be a procedure (returning void) but we continue
  54178. ** to return an integer result code for historical reasons.
  54179. */
  54180. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  54181. assert( cursorHoldsMutex(pCur) );
  54182. assert( pCur->eState==CURSOR_VALID );
  54183. assert( pCur->iPage>=0 );
  54184. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  54185. assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  54186. getCellInfo(pCur);
  54187. *pSize = pCur->info.nPayload;
  54188. return SQLITE_OK;
  54189. }
  54190. /*
  54191. ** Given the page number of an overflow page in the database (parameter
  54192. ** ovfl), this function finds the page number of the next page in the
  54193. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  54194. ** pointer-map data instead of reading the content of page ovfl to do so.
  54195. **
  54196. ** If an error occurs an SQLite error code is returned. Otherwise:
  54197. **
  54198. ** The page number of the next overflow page in the linked list is
  54199. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  54200. ** list, *pPgnoNext is set to zero.
  54201. **
  54202. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  54203. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  54204. ** reference. It is the responsibility of the caller to call releasePage()
  54205. ** on *ppPage to free the reference. In no reference was obtained (because
  54206. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  54207. ** *ppPage is set to zero.
  54208. */
  54209. static int getOverflowPage(
  54210. BtShared *pBt, /* The database file */
  54211. Pgno ovfl, /* Current overflow page number */
  54212. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  54213. Pgno *pPgnoNext /* OUT: Next overflow page number */
  54214. ){
  54215. Pgno next = 0;
  54216. MemPage *pPage = 0;
  54217. int rc = SQLITE_OK;
  54218. assert( sqlite3_mutex_held(pBt->mutex) );
  54219. assert(pPgnoNext);
  54220. #ifndef SQLITE_OMIT_AUTOVACUUM
  54221. /* Try to find the next page in the overflow list using the
  54222. ** autovacuum pointer-map pages. Guess that the next page in
  54223. ** the overflow list is page number (ovfl+1). If that guess turns
  54224. ** out to be wrong, fall back to loading the data of page
  54225. ** number ovfl to determine the next page number.
  54226. */
  54227. if( pBt->autoVacuum ){
  54228. Pgno pgno;
  54229. Pgno iGuess = ovfl+1;
  54230. u8 eType;
  54231. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  54232. iGuess++;
  54233. }
  54234. if( iGuess<=btreePagecount(pBt) ){
  54235. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  54236. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  54237. next = iGuess;
  54238. rc = SQLITE_DONE;
  54239. }
  54240. }
  54241. }
  54242. #endif
  54243. assert( next==0 || rc==SQLITE_DONE );
  54244. if( rc==SQLITE_OK ){
  54245. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  54246. assert( rc==SQLITE_OK || pPage==0 );
  54247. if( rc==SQLITE_OK ){
  54248. next = get4byte(pPage->aData);
  54249. }
  54250. }
  54251. *pPgnoNext = next;
  54252. if( ppPage ){
  54253. *ppPage = pPage;
  54254. }else{
  54255. releasePage(pPage);
  54256. }
  54257. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  54258. }
  54259. /*
  54260. ** Copy data from a buffer to a page, or from a page to a buffer.
  54261. **
  54262. ** pPayload is a pointer to data stored on database page pDbPage.
  54263. ** If argument eOp is false, then nByte bytes of data are copied
  54264. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  54265. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  54266. ** of data are copied from the buffer pBuf to pPayload.
  54267. **
  54268. ** SQLITE_OK is returned on success, otherwise an error code.
  54269. */
  54270. static int copyPayload(
  54271. void *pPayload, /* Pointer to page data */
  54272. void *pBuf, /* Pointer to buffer */
  54273. int nByte, /* Number of bytes to copy */
  54274. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  54275. DbPage *pDbPage /* Page containing pPayload */
  54276. ){
  54277. if( eOp ){
  54278. /* Copy data from buffer to page (a write operation) */
  54279. int rc = sqlite3PagerWrite(pDbPage);
  54280. if( rc!=SQLITE_OK ){
  54281. return rc;
  54282. }
  54283. memcpy(pPayload, pBuf, nByte);
  54284. }else{
  54285. /* Copy data from page to buffer (a read operation) */
  54286. memcpy(pBuf, pPayload, nByte);
  54287. }
  54288. return SQLITE_OK;
  54289. }
  54290. /*
  54291. ** This function is used to read or overwrite payload information
  54292. ** for the entry that the pCur cursor is pointing to. The eOp
  54293. ** argument is interpreted as follows:
  54294. **
  54295. ** 0: The operation is a read. Populate the overflow cache.
  54296. ** 1: The operation is a write. Populate the overflow cache.
  54297. ** 2: The operation is a read. Do not populate the overflow cache.
  54298. **
  54299. ** A total of "amt" bytes are read or written beginning at "offset".
  54300. ** Data is read to or from the buffer pBuf.
  54301. **
  54302. ** The content being read or written might appear on the main page
  54303. ** or be scattered out on multiple overflow pages.
  54304. **
  54305. ** If the current cursor entry uses one or more overflow pages and the
  54306. ** eOp argument is not 2, this function may allocate space for and lazily
  54307. ** populates the overflow page-list cache array (BtCursor.aOverflow).
  54308. ** Subsequent calls use this cache to make seeking to the supplied offset
  54309. ** more efficient.
  54310. **
  54311. ** Once an overflow page-list cache has been allocated, it may be
  54312. ** invalidated if some other cursor writes to the same table, or if
  54313. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  54314. ** mode, the following events may invalidate an overflow page-list cache.
  54315. **
  54316. ** * An incremental vacuum,
  54317. ** * A commit in auto_vacuum="full" mode,
  54318. ** * Creating a table (may require moving an overflow page).
  54319. */
  54320. static int accessPayload(
  54321. BtCursor *pCur, /* Cursor pointing to entry to read from */
  54322. u32 offset, /* Begin reading this far into payload */
  54323. u32 amt, /* Read this many bytes */
  54324. unsigned char *pBuf, /* Write the bytes into this buffer */
  54325. int eOp /* zero to read. non-zero to write. */
  54326. ){
  54327. unsigned char *aPayload;
  54328. int rc = SQLITE_OK;
  54329. int iIdx = 0;
  54330. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  54331. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  54332. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  54333. unsigned char * const pBufStart = pBuf;
  54334. int bEnd; /* True if reading to end of data */
  54335. #endif
  54336. assert( pPage );
  54337. assert( pCur->eState==CURSOR_VALID );
  54338. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  54339. assert( cursorHoldsMutex(pCur) );
  54340. assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
  54341. getCellInfo(pCur);
  54342. aPayload = pCur->info.pPayload;
  54343. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  54344. bEnd = offset+amt==pCur->info.nPayload;
  54345. #endif
  54346. assert( offset+amt <= pCur->info.nPayload );
  54347. if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
  54348. /* Trying to read or write past the end of the data is an error */
  54349. return SQLITE_CORRUPT_BKPT;
  54350. }
  54351. /* Check if data must be read/written to/from the btree page itself. */
  54352. if( offset<pCur->info.nLocal ){
  54353. int a = amt;
  54354. if( a+offset>pCur->info.nLocal ){
  54355. a = pCur->info.nLocal - offset;
  54356. }
  54357. rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
  54358. offset = 0;
  54359. pBuf += a;
  54360. amt -= a;
  54361. }else{
  54362. offset -= pCur->info.nLocal;
  54363. }
  54364. if( rc==SQLITE_OK && amt>0 ){
  54365. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  54366. Pgno nextPage;
  54367. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  54368. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  54369. ** Except, do not allocate aOverflow[] for eOp==2.
  54370. **
  54371. ** The aOverflow[] array is sized at one entry for each overflow page
  54372. ** in the overflow chain. The page number of the first overflow page is
  54373. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  54374. ** means "not yet known" (the cache is lazily populated).
  54375. */
  54376. if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  54377. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  54378. if( nOvfl>pCur->nOvflAlloc ){
  54379. Pgno *aNew = (Pgno*)sqlite3Realloc(
  54380. pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  54381. );
  54382. if( aNew==0 ){
  54383. rc = SQLITE_NOMEM;
  54384. }else{
  54385. pCur->nOvflAlloc = nOvfl*2;
  54386. pCur->aOverflow = aNew;
  54387. }
  54388. }
  54389. if( rc==SQLITE_OK ){
  54390. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  54391. pCur->curFlags |= BTCF_ValidOvfl;
  54392. }
  54393. }
  54394. /* If the overflow page-list cache has been allocated and the
  54395. ** entry for the first required overflow page is valid, skip
  54396. ** directly to it.
  54397. */
  54398. if( (pCur->curFlags & BTCF_ValidOvfl)!=0
  54399. && pCur->aOverflow[offset/ovflSize]
  54400. ){
  54401. iIdx = (offset/ovflSize);
  54402. nextPage = pCur->aOverflow[iIdx];
  54403. offset = (offset%ovflSize);
  54404. }
  54405. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  54406. /* If required, populate the overflow page-list cache. */
  54407. if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
  54408. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  54409. pCur->aOverflow[iIdx] = nextPage;
  54410. }
  54411. if( offset>=ovflSize ){
  54412. /* The only reason to read this page is to obtain the page
  54413. ** number for the next page in the overflow chain. The page
  54414. ** data is not required. So first try to lookup the overflow
  54415. ** page-list cache, if any, then fall back to the getOverflowPage()
  54416. ** function.
  54417. **
  54418. ** Note that the aOverflow[] array must be allocated because eOp!=2
  54419. ** here. If eOp==2, then offset==0 and this branch is never taken.
  54420. */
  54421. assert( eOp!=2 );
  54422. assert( pCur->curFlags & BTCF_ValidOvfl );
  54423. assert( pCur->pBtree->db==pBt->db );
  54424. if( pCur->aOverflow[iIdx+1] ){
  54425. nextPage = pCur->aOverflow[iIdx+1];
  54426. }else{
  54427. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  54428. }
  54429. offset -= ovflSize;
  54430. }else{
  54431. /* Need to read this page properly. It contains some of the
  54432. ** range of data that is being read (eOp==0) or written (eOp!=0).
  54433. */
  54434. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  54435. sqlite3_file *fd;
  54436. #endif
  54437. int a = amt;
  54438. if( a + offset > ovflSize ){
  54439. a = ovflSize - offset;
  54440. }
  54441. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  54442. /* If all the following are true:
  54443. **
  54444. ** 1) this is a read operation, and
  54445. ** 2) data is required from the start of this overflow page, and
  54446. ** 3) the database is file-backed, and
  54447. ** 4) there is no open write-transaction, and
  54448. ** 5) the database is not a WAL database,
  54449. ** 6) all data from the page is being read.
  54450. ** 7) at least 4 bytes have already been read into the output buffer
  54451. **
  54452. ** then data can be read directly from the database file into the
  54453. ** output buffer, bypassing the page-cache altogether. This speeds
  54454. ** up loading large records that span many overflow pages.
  54455. */
  54456. if( (eOp&0x01)==0 /* (1) */
  54457. && offset==0 /* (2) */
  54458. && (bEnd || a==ovflSize) /* (6) */
  54459. && pBt->inTransaction==TRANS_READ /* (4) */
  54460. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  54461. && pBt->pPage1->aData[19]==0x01 /* (5) */
  54462. && &pBuf[-4]>=pBufStart /* (7) */
  54463. ){
  54464. u8 aSave[4];
  54465. u8 *aWrite = &pBuf[-4];
  54466. assert( aWrite>=pBufStart ); /* hence (7) */
  54467. memcpy(aSave, aWrite, 4);
  54468. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  54469. nextPage = get4byte(aWrite);
  54470. memcpy(aWrite, aSave, 4);
  54471. }else
  54472. #endif
  54473. {
  54474. DbPage *pDbPage;
  54475. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  54476. ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
  54477. );
  54478. if( rc==SQLITE_OK ){
  54479. aPayload = sqlite3PagerGetData(pDbPage);
  54480. nextPage = get4byte(aPayload);
  54481. rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
  54482. sqlite3PagerUnref(pDbPage);
  54483. offset = 0;
  54484. }
  54485. }
  54486. amt -= a;
  54487. pBuf += a;
  54488. }
  54489. }
  54490. }
  54491. if( rc==SQLITE_OK && amt>0 ){
  54492. return SQLITE_CORRUPT_BKPT;
  54493. }
  54494. return rc;
  54495. }
  54496. /*
  54497. ** Read part of the key associated with cursor pCur. Exactly
  54498. ** "amt" bytes will be transferred into pBuf[]. The transfer
  54499. ** begins at "offset".
  54500. **
  54501. ** The caller must ensure that pCur is pointing to a valid row
  54502. ** in the table.
  54503. **
  54504. ** Return SQLITE_OK on success or an error code if anything goes
  54505. ** wrong. An error is returned if "offset+amt" is larger than
  54506. ** the available payload.
  54507. */
  54508. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  54509. assert( cursorHoldsMutex(pCur) );
  54510. assert( pCur->eState==CURSOR_VALID );
  54511. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  54512. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  54513. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  54514. }
  54515. /*
  54516. ** Read part of the data associated with cursor pCur. Exactly
  54517. ** "amt" bytes will be transfered into pBuf[]. The transfer
  54518. ** begins at "offset".
  54519. **
  54520. ** Return SQLITE_OK on success or an error code if anything goes
  54521. ** wrong. An error is returned if "offset+amt" is larger than
  54522. ** the available payload.
  54523. */
  54524. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  54525. int rc;
  54526. #ifndef SQLITE_OMIT_INCRBLOB
  54527. if ( pCur->eState==CURSOR_INVALID ){
  54528. return SQLITE_ABORT;
  54529. }
  54530. #endif
  54531. assert( cursorHoldsMutex(pCur) );
  54532. rc = restoreCursorPosition(pCur);
  54533. if( rc==SQLITE_OK ){
  54534. assert( pCur->eState==CURSOR_VALID );
  54535. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  54536. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  54537. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  54538. }
  54539. return rc;
  54540. }
  54541. /*
  54542. ** Return a pointer to payload information from the entry that the
  54543. ** pCur cursor is pointing to. The pointer is to the beginning of
  54544. ** the key if index btrees (pPage->intKey==0) and is the data for
  54545. ** table btrees (pPage->intKey==1). The number of bytes of available
  54546. ** key/data is written into *pAmt. If *pAmt==0, then the value
  54547. ** returned will not be a valid pointer.
  54548. **
  54549. ** This routine is an optimization. It is common for the entire key
  54550. ** and data to fit on the local page and for there to be no overflow
  54551. ** pages. When that is so, this routine can be used to access the
  54552. ** key and data without making a copy. If the key and/or data spills
  54553. ** onto overflow pages, then accessPayload() must be used to reassemble
  54554. ** the key/data and copy it into a preallocated buffer.
  54555. **
  54556. ** The pointer returned by this routine looks directly into the cached
  54557. ** page of the database. The data might change or move the next time
  54558. ** any btree routine is called.
  54559. */
  54560. static const void *fetchPayload(
  54561. BtCursor *pCur, /* Cursor pointing to entry to read from */
  54562. u32 *pAmt /* Write the number of available bytes here */
  54563. ){
  54564. u32 amt;
  54565. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  54566. assert( pCur->eState==CURSOR_VALID );
  54567. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  54568. assert( cursorHoldsMutex(pCur) );
  54569. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  54570. assert( pCur->info.nSize>0 );
  54571. assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
  54572. assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
  54573. amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
  54574. if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
  54575. *pAmt = amt;
  54576. return (void*)pCur->info.pPayload;
  54577. }
  54578. /*
  54579. ** For the entry that cursor pCur is point to, return as
  54580. ** many bytes of the key or data as are available on the local
  54581. ** b-tree page. Write the number of available bytes into *pAmt.
  54582. **
  54583. ** The pointer returned is ephemeral. The key/data may move
  54584. ** or be destroyed on the next call to any Btree routine,
  54585. ** including calls from other threads against the same cache.
  54586. ** Hence, a mutex on the BtShared should be held prior to calling
  54587. ** this routine.
  54588. **
  54589. ** These routines is used to get quick access to key and data
  54590. ** in the common case where no overflow pages are used.
  54591. */
  54592. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
  54593. return fetchPayload(pCur, pAmt);
  54594. }
  54595. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
  54596. return fetchPayload(pCur, pAmt);
  54597. }
  54598. /*
  54599. ** Move the cursor down to a new child page. The newPgno argument is the
  54600. ** page number of the child page to move to.
  54601. **
  54602. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  54603. ** the new child page does not match the flags field of the parent (i.e.
  54604. ** if an intkey page appears to be the parent of a non-intkey page, or
  54605. ** vice-versa).
  54606. */
  54607. static int moveToChild(BtCursor *pCur, u32 newPgno){
  54608. BtShared *pBt = pCur->pBt;
  54609. assert( cursorHoldsMutex(pCur) );
  54610. assert( pCur->eState==CURSOR_VALID );
  54611. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  54612. assert( pCur->iPage>=0 );
  54613. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  54614. return SQLITE_CORRUPT_BKPT;
  54615. }
  54616. pCur->info.nSize = 0;
  54617. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  54618. pCur->iPage++;
  54619. pCur->aiIdx[pCur->iPage] = 0;
  54620. return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
  54621. pCur, pCur->curPagerFlags);
  54622. }
  54623. #if SQLITE_DEBUG
  54624. /*
  54625. ** Page pParent is an internal (non-leaf) tree page. This function
  54626. ** asserts that page number iChild is the left-child if the iIdx'th
  54627. ** cell in page pParent. Or, if iIdx is equal to the total number of
  54628. ** cells in pParent, that page number iChild is the right-child of
  54629. ** the page.
  54630. */
  54631. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  54632. if( CORRUPT_DB ) return; /* The conditions tested below might not be true
  54633. ** in a corrupt database */
  54634. assert( iIdx<=pParent->nCell );
  54635. if( iIdx==pParent->nCell ){
  54636. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  54637. }else{
  54638. assert( get4byte(findCell(pParent, iIdx))==iChild );
  54639. }
  54640. }
  54641. #else
  54642. # define assertParentIndex(x,y,z)
  54643. #endif
  54644. /*
  54645. ** Move the cursor up to the parent page.
  54646. **
  54647. ** pCur->idx is set to the cell index that contains the pointer
  54648. ** to the page we are coming from. If we are coming from the
  54649. ** right-most child page then pCur->idx is set to one more than
  54650. ** the largest cell index.
  54651. */
  54652. static void moveToParent(BtCursor *pCur){
  54653. assert( cursorHoldsMutex(pCur) );
  54654. assert( pCur->eState==CURSOR_VALID );
  54655. assert( pCur->iPage>0 );
  54656. assert( pCur->apPage[pCur->iPage] );
  54657. assertParentIndex(
  54658. pCur->apPage[pCur->iPage-1],
  54659. pCur->aiIdx[pCur->iPage-1],
  54660. pCur->apPage[pCur->iPage]->pgno
  54661. );
  54662. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  54663. pCur->info.nSize = 0;
  54664. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  54665. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  54666. }
  54667. /*
  54668. ** Move the cursor to point to the root page of its b-tree structure.
  54669. **
  54670. ** If the table has a virtual root page, then the cursor is moved to point
  54671. ** to the virtual root page instead of the actual root page. A table has a
  54672. ** virtual root page when the actual root page contains no cells and a
  54673. ** single child page. This can only happen with the table rooted at page 1.
  54674. **
  54675. ** If the b-tree structure is empty, the cursor state is set to
  54676. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  54677. ** cell located on the root (or virtual root) page and the cursor state
  54678. ** is set to CURSOR_VALID.
  54679. **
  54680. ** If this function returns successfully, it may be assumed that the
  54681. ** page-header flags indicate that the [virtual] root-page is the expected
  54682. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  54683. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  54684. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  54685. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  54686. ** b-tree).
  54687. */
  54688. static int moveToRoot(BtCursor *pCur){
  54689. MemPage *pRoot;
  54690. int rc = SQLITE_OK;
  54691. assert( cursorHoldsMutex(pCur) );
  54692. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  54693. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  54694. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  54695. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  54696. if( pCur->eState==CURSOR_FAULT ){
  54697. assert( pCur->skipNext!=SQLITE_OK );
  54698. return pCur->skipNext;
  54699. }
  54700. sqlite3BtreeClearCursor(pCur);
  54701. }
  54702. if( pCur->iPage>=0 ){
  54703. while( pCur->iPage ){
  54704. assert( pCur->apPage[pCur->iPage]!=0 );
  54705. releasePageNotNull(pCur->apPage[pCur->iPage--]);
  54706. }
  54707. }else if( pCur->pgnoRoot==0 ){
  54708. pCur->eState = CURSOR_INVALID;
  54709. return SQLITE_OK;
  54710. }else{
  54711. assert( pCur->iPage==(-1) );
  54712. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  54713. 0, pCur->curPagerFlags);
  54714. if( rc!=SQLITE_OK ){
  54715. pCur->eState = CURSOR_INVALID;
  54716. return rc;
  54717. }
  54718. pCur->iPage = 0;
  54719. pCur->curIntKey = pCur->apPage[0]->intKey;
  54720. }
  54721. pRoot = pCur->apPage[0];
  54722. assert( pRoot->pgno==pCur->pgnoRoot );
  54723. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  54724. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  54725. ** NULL, the caller expects a table b-tree. If this is not the case,
  54726. ** return an SQLITE_CORRUPT error.
  54727. **
  54728. ** Earlier versions of SQLite assumed that this test could not fail
  54729. ** if the root page was already loaded when this function was called (i.e.
  54730. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  54731. ** in such a way that page pRoot is linked into a second b-tree table
  54732. ** (or the freelist). */
  54733. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  54734. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  54735. return SQLITE_CORRUPT_BKPT;
  54736. }
  54737. pCur->aiIdx[0] = 0;
  54738. pCur->info.nSize = 0;
  54739. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  54740. if( pRoot->nCell>0 ){
  54741. pCur->eState = CURSOR_VALID;
  54742. }else if( !pRoot->leaf ){
  54743. Pgno subpage;
  54744. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  54745. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  54746. pCur->eState = CURSOR_VALID;
  54747. rc = moveToChild(pCur, subpage);
  54748. }else{
  54749. pCur->eState = CURSOR_INVALID;
  54750. }
  54751. return rc;
  54752. }
  54753. /*
  54754. ** Move the cursor down to the left-most leaf entry beneath the
  54755. ** entry to which it is currently pointing.
  54756. **
  54757. ** The left-most leaf is the one with the smallest key - the first
  54758. ** in ascending order.
  54759. */
  54760. static int moveToLeftmost(BtCursor *pCur){
  54761. Pgno pgno;
  54762. int rc = SQLITE_OK;
  54763. MemPage *pPage;
  54764. assert( cursorHoldsMutex(pCur) );
  54765. assert( pCur->eState==CURSOR_VALID );
  54766. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  54767. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  54768. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  54769. rc = moveToChild(pCur, pgno);
  54770. }
  54771. return rc;
  54772. }
  54773. /*
  54774. ** Move the cursor down to the right-most leaf entry beneath the
  54775. ** page to which it is currently pointing. Notice the difference
  54776. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  54777. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  54778. ** finds the right-most entry beneath the *page*.
  54779. **
  54780. ** The right-most entry is the one with the largest key - the last
  54781. ** key in ascending order.
  54782. */
  54783. static int moveToRightmost(BtCursor *pCur){
  54784. Pgno pgno;
  54785. int rc = SQLITE_OK;
  54786. MemPage *pPage = 0;
  54787. assert( cursorHoldsMutex(pCur) );
  54788. assert( pCur->eState==CURSOR_VALID );
  54789. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  54790. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  54791. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  54792. rc = moveToChild(pCur, pgno);
  54793. if( rc ) return rc;
  54794. }
  54795. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  54796. assert( pCur->info.nSize==0 );
  54797. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  54798. return SQLITE_OK;
  54799. }
  54800. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  54801. ** on success. Set *pRes to 0 if the cursor actually points to something
  54802. ** or set *pRes to 1 if the table is empty.
  54803. */
  54804. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  54805. int rc;
  54806. assert( cursorHoldsMutex(pCur) );
  54807. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  54808. rc = moveToRoot(pCur);
  54809. if( rc==SQLITE_OK ){
  54810. if( pCur->eState==CURSOR_INVALID ){
  54811. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  54812. *pRes = 1;
  54813. }else{
  54814. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  54815. *pRes = 0;
  54816. rc = moveToLeftmost(pCur);
  54817. }
  54818. }
  54819. return rc;
  54820. }
  54821. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  54822. ** on success. Set *pRes to 0 if the cursor actually points to something
  54823. ** or set *pRes to 1 if the table is empty.
  54824. */
  54825. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  54826. int rc;
  54827. assert( cursorHoldsMutex(pCur) );
  54828. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  54829. /* If the cursor already points to the last entry, this is a no-op. */
  54830. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  54831. #ifdef SQLITE_DEBUG
  54832. /* This block serves to assert() that the cursor really does point
  54833. ** to the last entry in the b-tree. */
  54834. int ii;
  54835. for(ii=0; ii<pCur->iPage; ii++){
  54836. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  54837. }
  54838. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  54839. assert( pCur->apPage[pCur->iPage]->leaf );
  54840. #endif
  54841. return SQLITE_OK;
  54842. }
  54843. rc = moveToRoot(pCur);
  54844. if( rc==SQLITE_OK ){
  54845. if( CURSOR_INVALID==pCur->eState ){
  54846. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  54847. *pRes = 1;
  54848. }else{
  54849. assert( pCur->eState==CURSOR_VALID );
  54850. *pRes = 0;
  54851. rc = moveToRightmost(pCur);
  54852. if( rc==SQLITE_OK ){
  54853. pCur->curFlags |= BTCF_AtLast;
  54854. }else{
  54855. pCur->curFlags &= ~BTCF_AtLast;
  54856. }
  54857. }
  54858. }
  54859. return rc;
  54860. }
  54861. /* Move the cursor so that it points to an entry near the key
  54862. ** specified by pIdxKey or intKey. Return a success code.
  54863. **
  54864. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  54865. ** must be NULL. For index tables, pIdxKey is used and intKey
  54866. ** is ignored.
  54867. **
  54868. ** If an exact match is not found, then the cursor is always
  54869. ** left pointing at a leaf page which would hold the entry if it
  54870. ** were present. The cursor might point to an entry that comes
  54871. ** before or after the key.
  54872. **
  54873. ** An integer is written into *pRes which is the result of
  54874. ** comparing the key with the entry to which the cursor is
  54875. ** pointing. The meaning of the integer written into
  54876. ** *pRes is as follows:
  54877. **
  54878. ** *pRes<0 The cursor is left pointing at an entry that
  54879. ** is smaller than intKey/pIdxKey or if the table is empty
  54880. ** and the cursor is therefore left point to nothing.
  54881. **
  54882. ** *pRes==0 The cursor is left pointing at an entry that
  54883. ** exactly matches intKey/pIdxKey.
  54884. **
  54885. ** *pRes>0 The cursor is left pointing at an entry that
  54886. ** is larger than intKey/pIdxKey.
  54887. **
  54888. */
  54889. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  54890. BtCursor *pCur, /* The cursor to be moved */
  54891. UnpackedRecord *pIdxKey, /* Unpacked index key */
  54892. i64 intKey, /* The table key */
  54893. int biasRight, /* If true, bias the search to the high end */
  54894. int *pRes /* Write search results here */
  54895. ){
  54896. int rc;
  54897. RecordCompare xRecordCompare;
  54898. assert( cursorHoldsMutex(pCur) );
  54899. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  54900. assert( pRes );
  54901. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  54902. /* If the cursor is already positioned at the point we are trying
  54903. ** to move to, then just return without doing any work */
  54904. if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  54905. && pCur->curIntKey
  54906. ){
  54907. if( pCur->info.nKey==intKey ){
  54908. *pRes = 0;
  54909. return SQLITE_OK;
  54910. }
  54911. if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
  54912. *pRes = -1;
  54913. return SQLITE_OK;
  54914. }
  54915. }
  54916. if( pIdxKey ){
  54917. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  54918. pIdxKey->errCode = 0;
  54919. assert( pIdxKey->default_rc==1
  54920. || pIdxKey->default_rc==0
  54921. || pIdxKey->default_rc==-1
  54922. );
  54923. }else{
  54924. xRecordCompare = 0; /* All keys are integers */
  54925. }
  54926. rc = moveToRoot(pCur);
  54927. if( rc ){
  54928. return rc;
  54929. }
  54930. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  54931. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  54932. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  54933. if( pCur->eState==CURSOR_INVALID ){
  54934. *pRes = -1;
  54935. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  54936. return SQLITE_OK;
  54937. }
  54938. assert( pCur->apPage[0]->intKey==pCur->curIntKey );
  54939. assert( pCur->curIntKey || pIdxKey );
  54940. for(;;){
  54941. int lwr, upr, idx, c;
  54942. Pgno chldPg;
  54943. MemPage *pPage = pCur->apPage[pCur->iPage];
  54944. u8 *pCell; /* Pointer to current cell in pPage */
  54945. /* pPage->nCell must be greater than zero. If this is the root-page
  54946. ** the cursor would have been INVALID above and this for(;;) loop
  54947. ** not run. If this is not the root-page, then the moveToChild() routine
  54948. ** would have already detected db corruption. Similarly, pPage must
  54949. ** be the right kind (index or table) of b-tree page. Otherwise
  54950. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  54951. assert( pPage->nCell>0 );
  54952. assert( pPage->intKey==(pIdxKey==0) );
  54953. lwr = 0;
  54954. upr = pPage->nCell-1;
  54955. assert( biasRight==0 || biasRight==1 );
  54956. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  54957. pCur->aiIdx[pCur->iPage] = (u16)idx;
  54958. if( xRecordCompare==0 ){
  54959. for(;;){
  54960. i64 nCellKey;
  54961. pCell = findCellPastPtr(pPage, idx);
  54962. if( pPage->intKeyLeaf ){
  54963. while( 0x80 <= *(pCell++) ){
  54964. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  54965. }
  54966. }
  54967. getVarint(pCell, (u64*)&nCellKey);
  54968. if( nCellKey<intKey ){
  54969. lwr = idx+1;
  54970. if( lwr>upr ){ c = -1; break; }
  54971. }else if( nCellKey>intKey ){
  54972. upr = idx-1;
  54973. if( lwr>upr ){ c = +1; break; }
  54974. }else{
  54975. assert( nCellKey==intKey );
  54976. pCur->curFlags |= BTCF_ValidNKey;
  54977. pCur->info.nKey = nCellKey;
  54978. pCur->aiIdx[pCur->iPage] = (u16)idx;
  54979. if( !pPage->leaf ){
  54980. lwr = idx;
  54981. goto moveto_next_layer;
  54982. }else{
  54983. *pRes = 0;
  54984. rc = SQLITE_OK;
  54985. goto moveto_finish;
  54986. }
  54987. }
  54988. assert( lwr+upr>=0 );
  54989. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  54990. }
  54991. }else{
  54992. for(;;){
  54993. int nCell; /* Size of the pCell cell in bytes */
  54994. pCell = findCellPastPtr(pPage, idx);
  54995. /* The maximum supported page-size is 65536 bytes. This means that
  54996. ** the maximum number of record bytes stored on an index B-Tree
  54997. ** page is less than 16384 bytes and may be stored as a 2-byte
  54998. ** varint. This information is used to attempt to avoid parsing
  54999. ** the entire cell by checking for the cases where the record is
  55000. ** stored entirely within the b-tree page by inspecting the first
  55001. ** 2 bytes of the cell.
  55002. */
  55003. nCell = pCell[0];
  55004. if( nCell<=pPage->max1bytePayload ){
  55005. /* This branch runs if the record-size field of the cell is a
  55006. ** single byte varint and the record fits entirely on the main
  55007. ** b-tree page. */
  55008. testcase( pCell+nCell+1==pPage->aDataEnd );
  55009. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  55010. }else if( !(pCell[1] & 0x80)
  55011. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  55012. ){
  55013. /* The record-size field is a 2 byte varint and the record
  55014. ** fits entirely on the main b-tree page. */
  55015. testcase( pCell+nCell+2==pPage->aDataEnd );
  55016. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  55017. }else{
  55018. /* The record flows over onto one or more overflow pages. In
  55019. ** this case the whole cell needs to be parsed, a buffer allocated
  55020. ** and accessPayload() used to retrieve the record into the
  55021. ** buffer before VdbeRecordCompare() can be called.
  55022. **
  55023. ** If the record is corrupt, the xRecordCompare routine may read
  55024. ** up to two varints past the end of the buffer. An extra 18
  55025. ** bytes of padding is allocated at the end of the buffer in
  55026. ** case this happens. */
  55027. void *pCellKey;
  55028. u8 * const pCellBody = pCell - pPage->childPtrSize;
  55029. pPage->xParseCell(pPage, pCellBody, &pCur->info);
  55030. nCell = (int)pCur->info.nKey;
  55031. testcase( nCell<0 ); /* True if key size is 2^32 or more */
  55032. testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
  55033. testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
  55034. testcase( nCell==2 ); /* Minimum legal index key size */
  55035. if( nCell<2 ){
  55036. rc = SQLITE_CORRUPT_BKPT;
  55037. goto moveto_finish;
  55038. }
  55039. pCellKey = sqlite3Malloc( nCell+18 );
  55040. if( pCellKey==0 ){
  55041. rc = SQLITE_NOMEM;
  55042. goto moveto_finish;
  55043. }
  55044. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55045. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
  55046. if( rc ){
  55047. sqlite3_free(pCellKey);
  55048. goto moveto_finish;
  55049. }
  55050. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  55051. sqlite3_free(pCellKey);
  55052. }
  55053. assert(
  55054. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  55055. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  55056. );
  55057. if( c<0 ){
  55058. lwr = idx+1;
  55059. }else if( c>0 ){
  55060. upr = idx-1;
  55061. }else{
  55062. assert( c==0 );
  55063. *pRes = 0;
  55064. rc = SQLITE_OK;
  55065. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55066. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  55067. goto moveto_finish;
  55068. }
  55069. if( lwr>upr ) break;
  55070. assert( lwr+upr>=0 );
  55071. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  55072. }
  55073. }
  55074. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  55075. assert( pPage->isInit );
  55076. if( pPage->leaf ){
  55077. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  55078. pCur->aiIdx[pCur->iPage] = (u16)idx;
  55079. *pRes = c;
  55080. rc = SQLITE_OK;
  55081. goto moveto_finish;
  55082. }
  55083. moveto_next_layer:
  55084. if( lwr>=pPage->nCell ){
  55085. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  55086. }else{
  55087. chldPg = get4byte(findCell(pPage, lwr));
  55088. }
  55089. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  55090. rc = moveToChild(pCur, chldPg);
  55091. if( rc ) break;
  55092. }
  55093. moveto_finish:
  55094. pCur->info.nSize = 0;
  55095. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55096. return rc;
  55097. }
  55098. /*
  55099. ** Return TRUE if the cursor is not pointing at an entry of the table.
  55100. **
  55101. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  55102. ** past the last entry in the table or sqlite3BtreePrev() moves past
  55103. ** the first entry. TRUE is also returned if the table is empty.
  55104. */
  55105. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  55106. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  55107. ** have been deleted? This API will need to change to return an error code
  55108. ** as well as the boolean result value.
  55109. */
  55110. return (CURSOR_VALID!=pCur->eState);
  55111. }
  55112. /*
  55113. ** Advance the cursor to the next entry in the database. If
  55114. ** successful then set *pRes=0. If the cursor
  55115. ** was already pointing to the last entry in the database before
  55116. ** this routine was called, then set *pRes=1.
  55117. **
  55118. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  55119. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  55120. ** to the next cell on the current page. The (slower) btreeNext() helper
  55121. ** routine is called when it is necessary to move to a different page or
  55122. ** to restore the cursor.
  55123. **
  55124. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  55125. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  55126. ** if this routine could have been skipped if that SQL index had been
  55127. ** a unique index. Otherwise the caller will have set *pRes to zero.
  55128. ** Zero is the common case. The btree implementation is free to use the
  55129. ** initial *pRes value as a hint to improve performance, but the current
  55130. ** SQLite btree implementation does not. (Note that the comdb2 btree
  55131. ** implementation does use this hint, however.)
  55132. */
  55133. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  55134. int rc;
  55135. int idx;
  55136. MemPage *pPage;
  55137. assert( cursorHoldsMutex(pCur) );
  55138. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55139. assert( *pRes==0 );
  55140. if( pCur->eState!=CURSOR_VALID ){
  55141. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  55142. rc = restoreCursorPosition(pCur);
  55143. if( rc!=SQLITE_OK ){
  55144. return rc;
  55145. }
  55146. if( CURSOR_INVALID==pCur->eState ){
  55147. *pRes = 1;
  55148. return SQLITE_OK;
  55149. }
  55150. if( pCur->skipNext ){
  55151. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  55152. pCur->eState = CURSOR_VALID;
  55153. if( pCur->skipNext>0 ){
  55154. pCur->skipNext = 0;
  55155. return SQLITE_OK;
  55156. }
  55157. pCur->skipNext = 0;
  55158. }
  55159. }
  55160. pPage = pCur->apPage[pCur->iPage];
  55161. idx = ++pCur->aiIdx[pCur->iPage];
  55162. assert( pPage->isInit );
  55163. /* If the database file is corrupt, it is possible for the value of idx
  55164. ** to be invalid here. This can only occur if a second cursor modifies
  55165. ** the page while cursor pCur is holding a reference to it. Which can
  55166. ** only happen if the database is corrupt in such a way as to link the
  55167. ** page into more than one b-tree structure. */
  55168. testcase( idx>pPage->nCell );
  55169. if( idx>=pPage->nCell ){
  55170. if( !pPage->leaf ){
  55171. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  55172. if( rc ) return rc;
  55173. return moveToLeftmost(pCur);
  55174. }
  55175. do{
  55176. if( pCur->iPage==0 ){
  55177. *pRes = 1;
  55178. pCur->eState = CURSOR_INVALID;
  55179. return SQLITE_OK;
  55180. }
  55181. moveToParent(pCur);
  55182. pPage = pCur->apPage[pCur->iPage];
  55183. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  55184. if( pPage->intKey ){
  55185. return sqlite3BtreeNext(pCur, pRes);
  55186. }else{
  55187. return SQLITE_OK;
  55188. }
  55189. }
  55190. if( pPage->leaf ){
  55191. return SQLITE_OK;
  55192. }else{
  55193. return moveToLeftmost(pCur);
  55194. }
  55195. }
  55196. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  55197. MemPage *pPage;
  55198. assert( cursorHoldsMutex(pCur) );
  55199. assert( pRes!=0 );
  55200. assert( *pRes==0 || *pRes==1 );
  55201. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55202. pCur->info.nSize = 0;
  55203. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  55204. *pRes = 0;
  55205. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  55206. pPage = pCur->apPage[pCur->iPage];
  55207. if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
  55208. pCur->aiIdx[pCur->iPage]--;
  55209. return btreeNext(pCur, pRes);
  55210. }
  55211. if( pPage->leaf ){
  55212. return SQLITE_OK;
  55213. }else{
  55214. return moveToLeftmost(pCur);
  55215. }
  55216. }
  55217. /*
  55218. ** Step the cursor to the back to the previous entry in the database. If
  55219. ** successful then set *pRes=0. If the cursor
  55220. ** was already pointing to the first entry in the database before
  55221. ** this routine was called, then set *pRes=1.
  55222. **
  55223. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  55224. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  55225. ** to the previous cell on the current page. The (slower) btreePrevious()
  55226. ** helper routine is called when it is necessary to move to a different page
  55227. ** or to restore the cursor.
  55228. **
  55229. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  55230. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  55231. ** if this routine could have been skipped if that SQL index had been
  55232. ** a unique index. Otherwise the caller will have set *pRes to zero.
  55233. ** Zero is the common case. The btree implementation is free to use the
  55234. ** initial *pRes value as a hint to improve performance, but the current
  55235. ** SQLite btree implementation does not. (Note that the comdb2 btree
  55236. ** implementation does use this hint, however.)
  55237. */
  55238. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  55239. int rc;
  55240. MemPage *pPage;
  55241. assert( cursorHoldsMutex(pCur) );
  55242. assert( pRes!=0 );
  55243. assert( *pRes==0 );
  55244. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55245. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  55246. assert( pCur->info.nSize==0 );
  55247. if( pCur->eState!=CURSOR_VALID ){
  55248. rc = restoreCursorPosition(pCur);
  55249. if( rc!=SQLITE_OK ){
  55250. return rc;
  55251. }
  55252. if( CURSOR_INVALID==pCur->eState ){
  55253. *pRes = 1;
  55254. return SQLITE_OK;
  55255. }
  55256. if( pCur->skipNext ){
  55257. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  55258. pCur->eState = CURSOR_VALID;
  55259. if( pCur->skipNext<0 ){
  55260. pCur->skipNext = 0;
  55261. return SQLITE_OK;
  55262. }
  55263. pCur->skipNext = 0;
  55264. }
  55265. }
  55266. pPage = pCur->apPage[pCur->iPage];
  55267. assert( pPage->isInit );
  55268. if( !pPage->leaf ){
  55269. int idx = pCur->aiIdx[pCur->iPage];
  55270. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  55271. if( rc ) return rc;
  55272. rc = moveToRightmost(pCur);
  55273. }else{
  55274. while( pCur->aiIdx[pCur->iPage]==0 ){
  55275. if( pCur->iPage==0 ){
  55276. pCur->eState = CURSOR_INVALID;
  55277. *pRes = 1;
  55278. return SQLITE_OK;
  55279. }
  55280. moveToParent(pCur);
  55281. }
  55282. assert( pCur->info.nSize==0 );
  55283. assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
  55284. pCur->aiIdx[pCur->iPage]--;
  55285. pPage = pCur->apPage[pCur->iPage];
  55286. if( pPage->intKey && !pPage->leaf ){
  55287. rc = sqlite3BtreePrevious(pCur, pRes);
  55288. }else{
  55289. rc = SQLITE_OK;
  55290. }
  55291. }
  55292. return rc;
  55293. }
  55294. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  55295. assert( cursorHoldsMutex(pCur) );
  55296. assert( pRes!=0 );
  55297. assert( *pRes==0 || *pRes==1 );
  55298. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  55299. *pRes = 0;
  55300. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  55301. pCur->info.nSize = 0;
  55302. if( pCur->eState!=CURSOR_VALID
  55303. || pCur->aiIdx[pCur->iPage]==0
  55304. || pCur->apPage[pCur->iPage]->leaf==0
  55305. ){
  55306. return btreePrevious(pCur, pRes);
  55307. }
  55308. pCur->aiIdx[pCur->iPage]--;
  55309. return SQLITE_OK;
  55310. }
  55311. /*
  55312. ** Allocate a new page from the database file.
  55313. **
  55314. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  55315. ** has already been called on the new page.) The new page has also
  55316. ** been referenced and the calling routine is responsible for calling
  55317. ** sqlite3PagerUnref() on the new page when it is done.
  55318. **
  55319. ** SQLITE_OK is returned on success. Any other return value indicates
  55320. ** an error. *ppPage is set to NULL in the event of an error.
  55321. **
  55322. ** If the "nearby" parameter is not 0, then an effort is made to
  55323. ** locate a page close to the page number "nearby". This can be used in an
  55324. ** attempt to keep related pages close to each other in the database file,
  55325. ** which in turn can make database access faster.
  55326. **
  55327. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  55328. ** anywhere on the free-list, then it is guaranteed to be returned. If
  55329. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  55330. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  55331. ** are no restrictions on which page is returned.
  55332. */
  55333. static int allocateBtreePage(
  55334. BtShared *pBt, /* The btree */
  55335. MemPage **ppPage, /* Store pointer to the allocated page here */
  55336. Pgno *pPgno, /* Store the page number here */
  55337. Pgno nearby, /* Search for a page near this one */
  55338. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  55339. ){
  55340. MemPage *pPage1;
  55341. int rc;
  55342. u32 n; /* Number of pages on the freelist */
  55343. u32 k; /* Number of leaves on the trunk of the freelist */
  55344. MemPage *pTrunk = 0;
  55345. MemPage *pPrevTrunk = 0;
  55346. Pgno mxPage; /* Total size of the database file */
  55347. assert( sqlite3_mutex_held(pBt->mutex) );
  55348. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  55349. pPage1 = pBt->pPage1;
  55350. mxPage = btreePagecount(pBt);
  55351. /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
  55352. ** stores stores the total number of pages on the freelist. */
  55353. n = get4byte(&pPage1->aData[36]);
  55354. testcase( n==mxPage-1 );
  55355. if( n>=mxPage ){
  55356. return SQLITE_CORRUPT_BKPT;
  55357. }
  55358. if( n>0 ){
  55359. /* There are pages on the freelist. Reuse one of those pages. */
  55360. Pgno iTrunk;
  55361. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  55362. u32 nSearch = 0; /* Count of the number of search attempts */
  55363. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  55364. ** shows that the page 'nearby' is somewhere on the free-list, then
  55365. ** the entire-list will be searched for that page.
  55366. */
  55367. #ifndef SQLITE_OMIT_AUTOVACUUM
  55368. if( eMode==BTALLOC_EXACT ){
  55369. if( nearby<=mxPage ){
  55370. u8 eType;
  55371. assert( nearby>0 );
  55372. assert( pBt->autoVacuum );
  55373. rc = ptrmapGet(pBt, nearby, &eType, 0);
  55374. if( rc ) return rc;
  55375. if( eType==PTRMAP_FREEPAGE ){
  55376. searchList = 1;
  55377. }
  55378. }
  55379. }else if( eMode==BTALLOC_LE ){
  55380. searchList = 1;
  55381. }
  55382. #endif
  55383. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  55384. ** first free-list trunk page. iPrevTrunk is initially 1.
  55385. */
  55386. rc = sqlite3PagerWrite(pPage1->pDbPage);
  55387. if( rc ) return rc;
  55388. put4byte(&pPage1->aData[36], n-1);
  55389. /* The code within this loop is run only once if the 'searchList' variable
  55390. ** is not true. Otherwise, it runs once for each trunk-page on the
  55391. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  55392. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  55393. */
  55394. do {
  55395. pPrevTrunk = pTrunk;
  55396. if( pPrevTrunk ){
  55397. /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
  55398. ** is the page number of the next freelist trunk page in the list or
  55399. ** zero if this is the last freelist trunk page. */
  55400. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  55401. }else{
  55402. /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
  55403. ** stores the page number of the first page of the freelist, or zero if
  55404. ** the freelist is empty. */
  55405. iTrunk = get4byte(&pPage1->aData[32]);
  55406. }
  55407. testcase( iTrunk==mxPage );
  55408. if( iTrunk>mxPage || nSearch++ > n ){
  55409. rc = SQLITE_CORRUPT_BKPT;
  55410. }else{
  55411. rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
  55412. }
  55413. if( rc ){
  55414. pTrunk = 0;
  55415. goto end_allocate_page;
  55416. }
  55417. assert( pTrunk!=0 );
  55418. assert( pTrunk->aData!=0 );
  55419. /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
  55420. ** is the number of leaf page pointers to follow. */
  55421. k = get4byte(&pTrunk->aData[4]);
  55422. if( k==0 && !searchList ){
  55423. /* The trunk has no leaves and the list is not being searched.
  55424. ** So extract the trunk page itself and use it as the newly
  55425. ** allocated page */
  55426. assert( pPrevTrunk==0 );
  55427. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  55428. if( rc ){
  55429. goto end_allocate_page;
  55430. }
  55431. *pPgno = iTrunk;
  55432. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  55433. *ppPage = pTrunk;
  55434. pTrunk = 0;
  55435. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  55436. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  55437. /* Value of k is out of range. Database corruption */
  55438. rc = SQLITE_CORRUPT_BKPT;
  55439. goto end_allocate_page;
  55440. #ifndef SQLITE_OMIT_AUTOVACUUM
  55441. }else if( searchList
  55442. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  55443. ){
  55444. /* The list is being searched and this trunk page is the page
  55445. ** to allocate, regardless of whether it has leaves.
  55446. */
  55447. *pPgno = iTrunk;
  55448. *ppPage = pTrunk;
  55449. searchList = 0;
  55450. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  55451. if( rc ){
  55452. goto end_allocate_page;
  55453. }
  55454. if( k==0 ){
  55455. if( !pPrevTrunk ){
  55456. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  55457. }else{
  55458. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  55459. if( rc!=SQLITE_OK ){
  55460. goto end_allocate_page;
  55461. }
  55462. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  55463. }
  55464. }else{
  55465. /* The trunk page is required by the caller but it contains
  55466. ** pointers to free-list leaves. The first leaf becomes a trunk
  55467. ** page in this case.
  55468. */
  55469. MemPage *pNewTrunk;
  55470. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  55471. if( iNewTrunk>mxPage ){
  55472. rc = SQLITE_CORRUPT_BKPT;
  55473. goto end_allocate_page;
  55474. }
  55475. testcase( iNewTrunk==mxPage );
  55476. rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
  55477. if( rc!=SQLITE_OK ){
  55478. goto end_allocate_page;
  55479. }
  55480. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  55481. if( rc!=SQLITE_OK ){
  55482. releasePage(pNewTrunk);
  55483. goto end_allocate_page;
  55484. }
  55485. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  55486. put4byte(&pNewTrunk->aData[4], k-1);
  55487. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  55488. releasePage(pNewTrunk);
  55489. if( !pPrevTrunk ){
  55490. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  55491. put4byte(&pPage1->aData[32], iNewTrunk);
  55492. }else{
  55493. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  55494. if( rc ){
  55495. goto end_allocate_page;
  55496. }
  55497. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  55498. }
  55499. }
  55500. pTrunk = 0;
  55501. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  55502. #endif
  55503. }else if( k>0 ){
  55504. /* Extract a leaf from the trunk */
  55505. u32 closest;
  55506. Pgno iPage;
  55507. unsigned char *aData = pTrunk->aData;
  55508. if( nearby>0 ){
  55509. u32 i;
  55510. closest = 0;
  55511. if( eMode==BTALLOC_LE ){
  55512. for(i=0; i<k; i++){
  55513. iPage = get4byte(&aData[8+i*4]);
  55514. if( iPage<=nearby ){
  55515. closest = i;
  55516. break;
  55517. }
  55518. }
  55519. }else{
  55520. int dist;
  55521. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  55522. for(i=1; i<k; i++){
  55523. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  55524. if( d2<dist ){
  55525. closest = i;
  55526. dist = d2;
  55527. }
  55528. }
  55529. }
  55530. }else{
  55531. closest = 0;
  55532. }
  55533. iPage = get4byte(&aData[8+closest*4]);
  55534. testcase( iPage==mxPage );
  55535. if( iPage>mxPage ){
  55536. rc = SQLITE_CORRUPT_BKPT;
  55537. goto end_allocate_page;
  55538. }
  55539. testcase( iPage==mxPage );
  55540. if( !searchList
  55541. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  55542. ){
  55543. int noContent;
  55544. *pPgno = iPage;
  55545. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  55546. ": %d more free pages\n",
  55547. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  55548. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  55549. if( rc ) goto end_allocate_page;
  55550. if( closest<k-1 ){
  55551. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  55552. }
  55553. put4byte(&aData[4], k-1);
  55554. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  55555. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
  55556. if( rc==SQLITE_OK ){
  55557. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  55558. if( rc!=SQLITE_OK ){
  55559. releasePage(*ppPage);
  55560. *ppPage = 0;
  55561. }
  55562. }
  55563. searchList = 0;
  55564. }
  55565. }
  55566. releasePage(pPrevTrunk);
  55567. pPrevTrunk = 0;
  55568. }while( searchList );
  55569. }else{
  55570. /* There are no pages on the freelist, so append a new page to the
  55571. ** database image.
  55572. **
  55573. ** Normally, new pages allocated by this block can be requested from the
  55574. ** pager layer with the 'no-content' flag set. This prevents the pager
  55575. ** from trying to read the pages content from disk. However, if the
  55576. ** current transaction has already run one or more incremental-vacuum
  55577. ** steps, then the page we are about to allocate may contain content
  55578. ** that is required in the event of a rollback. In this case, do
  55579. ** not set the no-content flag. This causes the pager to load and journal
  55580. ** the current page content before overwriting it.
  55581. **
  55582. ** Note that the pager will not actually attempt to load or journal
  55583. ** content for any page that really does lie past the end of the database
  55584. ** file on disk. So the effects of disabling the no-content optimization
  55585. ** here are confined to those pages that lie between the end of the
  55586. ** database image and the end of the database file.
  55587. */
  55588. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  55589. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  55590. if( rc ) return rc;
  55591. pBt->nPage++;
  55592. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  55593. #ifndef SQLITE_OMIT_AUTOVACUUM
  55594. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  55595. /* If *pPgno refers to a pointer-map page, allocate two new pages
  55596. ** at the end of the file instead of one. The first allocated page
  55597. ** becomes a new pointer-map page, the second is used by the caller.
  55598. */
  55599. MemPage *pPg = 0;
  55600. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  55601. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  55602. rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
  55603. if( rc==SQLITE_OK ){
  55604. rc = sqlite3PagerWrite(pPg->pDbPage);
  55605. releasePage(pPg);
  55606. }
  55607. if( rc ) return rc;
  55608. pBt->nPage++;
  55609. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  55610. }
  55611. #endif
  55612. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  55613. *pPgno = pBt->nPage;
  55614. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  55615. rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
  55616. if( rc ) return rc;
  55617. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  55618. if( rc!=SQLITE_OK ){
  55619. releasePage(*ppPage);
  55620. *ppPage = 0;
  55621. }
  55622. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  55623. }
  55624. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  55625. end_allocate_page:
  55626. releasePage(pTrunk);
  55627. releasePage(pPrevTrunk);
  55628. assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
  55629. assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
  55630. return rc;
  55631. }
  55632. /*
  55633. ** This function is used to add page iPage to the database file free-list.
  55634. ** It is assumed that the page is not already a part of the free-list.
  55635. **
  55636. ** The value passed as the second argument to this function is optional.
  55637. ** If the caller happens to have a pointer to the MemPage object
  55638. ** corresponding to page iPage handy, it may pass it as the second value.
  55639. ** Otherwise, it may pass NULL.
  55640. **
  55641. ** If a pointer to a MemPage object is passed as the second argument,
  55642. ** its reference count is not altered by this function.
  55643. */
  55644. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  55645. MemPage *pTrunk = 0; /* Free-list trunk page */
  55646. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  55647. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  55648. MemPage *pPage; /* Page being freed. May be NULL. */
  55649. int rc; /* Return Code */
  55650. int nFree; /* Initial number of pages on free-list */
  55651. assert( sqlite3_mutex_held(pBt->mutex) );
  55652. assert( CORRUPT_DB || iPage>1 );
  55653. assert( !pMemPage || pMemPage->pgno==iPage );
  55654. if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
  55655. if( pMemPage ){
  55656. pPage = pMemPage;
  55657. sqlite3PagerRef(pPage->pDbPage);
  55658. }else{
  55659. pPage = btreePageLookup(pBt, iPage);
  55660. }
  55661. /* Increment the free page count on pPage1 */
  55662. rc = sqlite3PagerWrite(pPage1->pDbPage);
  55663. if( rc ) goto freepage_out;
  55664. nFree = get4byte(&pPage1->aData[36]);
  55665. put4byte(&pPage1->aData[36], nFree+1);
  55666. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  55667. /* If the secure_delete option is enabled, then
  55668. ** always fully overwrite deleted information with zeros.
  55669. */
  55670. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  55671. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  55672. ){
  55673. goto freepage_out;
  55674. }
  55675. memset(pPage->aData, 0, pPage->pBt->pageSize);
  55676. }
  55677. /* If the database supports auto-vacuum, write an entry in the pointer-map
  55678. ** to indicate that the page is free.
  55679. */
  55680. if( ISAUTOVACUUM ){
  55681. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  55682. if( rc ) goto freepage_out;
  55683. }
  55684. /* Now manipulate the actual database free-list structure. There are two
  55685. ** possibilities. If the free-list is currently empty, or if the first
  55686. ** trunk page in the free-list is full, then this page will become a
  55687. ** new free-list trunk page. Otherwise, it will become a leaf of the
  55688. ** first trunk page in the current free-list. This block tests if it
  55689. ** is possible to add the page as a new free-list leaf.
  55690. */
  55691. if( nFree!=0 ){
  55692. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  55693. iTrunk = get4byte(&pPage1->aData[32]);
  55694. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  55695. if( rc!=SQLITE_OK ){
  55696. goto freepage_out;
  55697. }
  55698. nLeaf = get4byte(&pTrunk->aData[4]);
  55699. assert( pBt->usableSize>32 );
  55700. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  55701. rc = SQLITE_CORRUPT_BKPT;
  55702. goto freepage_out;
  55703. }
  55704. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  55705. /* In this case there is room on the trunk page to insert the page
  55706. ** being freed as a new leaf.
  55707. **
  55708. ** Note that the trunk page is not really full until it contains
  55709. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  55710. ** coded. But due to a coding error in versions of SQLite prior to
  55711. ** 3.6.0, databases with freelist trunk pages holding more than
  55712. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  55713. ** to maintain backwards compatibility with older versions of SQLite,
  55714. ** we will continue to restrict the number of entries to usableSize/4 - 8
  55715. ** for now. At some point in the future (once everyone has upgraded
  55716. ** to 3.6.0 or later) we should consider fixing the conditional above
  55717. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  55718. **
  55719. ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
  55720. ** avoid using the last six entries in the freelist trunk page array in
  55721. ** order that database files created by newer versions of SQLite can be
  55722. ** read by older versions of SQLite.
  55723. */
  55724. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  55725. if( rc==SQLITE_OK ){
  55726. put4byte(&pTrunk->aData[4], nLeaf+1);
  55727. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  55728. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  55729. sqlite3PagerDontWrite(pPage->pDbPage);
  55730. }
  55731. rc = btreeSetHasContent(pBt, iPage);
  55732. }
  55733. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  55734. goto freepage_out;
  55735. }
  55736. }
  55737. /* If control flows to this point, then it was not possible to add the
  55738. ** the page being freed as a leaf page of the first trunk in the free-list.
  55739. ** Possibly because the free-list is empty, or possibly because the
  55740. ** first trunk in the free-list is full. Either way, the page being freed
  55741. ** will become the new first trunk page in the free-list.
  55742. */
  55743. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  55744. goto freepage_out;
  55745. }
  55746. rc = sqlite3PagerWrite(pPage->pDbPage);
  55747. if( rc!=SQLITE_OK ){
  55748. goto freepage_out;
  55749. }
  55750. put4byte(pPage->aData, iTrunk);
  55751. put4byte(&pPage->aData[4], 0);
  55752. put4byte(&pPage1->aData[32], iPage);
  55753. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  55754. freepage_out:
  55755. if( pPage ){
  55756. pPage->isInit = 0;
  55757. }
  55758. releasePage(pPage);
  55759. releasePage(pTrunk);
  55760. return rc;
  55761. }
  55762. static void freePage(MemPage *pPage, int *pRC){
  55763. if( (*pRC)==SQLITE_OK ){
  55764. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  55765. }
  55766. }
  55767. /*
  55768. ** Free any overflow pages associated with the given Cell. Write the
  55769. ** local Cell size (the number of bytes on the original page, omitting
  55770. ** overflow) into *pnSize.
  55771. */
  55772. static int clearCell(
  55773. MemPage *pPage, /* The page that contains the Cell */
  55774. unsigned char *pCell, /* First byte of the Cell */
  55775. u16 *pnSize /* Write the size of the Cell here */
  55776. ){
  55777. BtShared *pBt = pPage->pBt;
  55778. CellInfo info;
  55779. Pgno ovflPgno;
  55780. int rc;
  55781. int nOvfl;
  55782. u32 ovflPageSize;
  55783. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55784. pPage->xParseCell(pPage, pCell, &info);
  55785. *pnSize = info.nSize;
  55786. if( info.iOverflow==0 ){
  55787. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  55788. }
  55789. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  55790. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  55791. }
  55792. ovflPgno = get4byte(&pCell[info.iOverflow]);
  55793. assert( pBt->usableSize > 4 );
  55794. ovflPageSize = pBt->usableSize - 4;
  55795. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  55796. assert( nOvfl>0 ||
  55797. (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
  55798. );
  55799. while( nOvfl-- ){
  55800. Pgno iNext = 0;
  55801. MemPage *pOvfl = 0;
  55802. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  55803. /* 0 is not a legal page number and page 1 cannot be an
  55804. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  55805. ** file the database must be corrupt. */
  55806. return SQLITE_CORRUPT_BKPT;
  55807. }
  55808. if( nOvfl ){
  55809. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  55810. if( rc ) return rc;
  55811. }
  55812. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  55813. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  55814. ){
  55815. /* There is no reason any cursor should have an outstanding reference
  55816. ** to an overflow page belonging to a cell that is being deleted/updated.
  55817. ** So if there exists more than one reference to this page, then it
  55818. ** must not really be an overflow page and the database must be corrupt.
  55819. ** It is helpful to detect this before calling freePage2(), as
  55820. ** freePage2() may zero the page contents if secure-delete mode is
  55821. ** enabled. If this 'overflow' page happens to be a page that the
  55822. ** caller is iterating through or using in some other way, this
  55823. ** can be problematic.
  55824. */
  55825. rc = SQLITE_CORRUPT_BKPT;
  55826. }else{
  55827. rc = freePage2(pBt, pOvfl, ovflPgno);
  55828. }
  55829. if( pOvfl ){
  55830. sqlite3PagerUnref(pOvfl->pDbPage);
  55831. }
  55832. if( rc ) return rc;
  55833. ovflPgno = iNext;
  55834. }
  55835. return SQLITE_OK;
  55836. }
  55837. /*
  55838. ** Create the byte sequence used to represent a cell on page pPage
  55839. ** and write that byte sequence into pCell[]. Overflow pages are
  55840. ** allocated and filled in as necessary. The calling procedure
  55841. ** is responsible for making sure sufficient space has been allocated
  55842. ** for pCell[].
  55843. **
  55844. ** Note that pCell does not necessary need to point to the pPage->aData
  55845. ** area. pCell might point to some temporary storage. The cell will
  55846. ** be constructed in this temporary area then copied into pPage->aData
  55847. ** later.
  55848. */
  55849. static int fillInCell(
  55850. MemPage *pPage, /* The page that contains the cell */
  55851. unsigned char *pCell, /* Complete text of the cell */
  55852. const void *pKey, i64 nKey, /* The key */
  55853. const void *pData,int nData, /* The data */
  55854. int nZero, /* Extra zero bytes to append to pData */
  55855. int *pnSize /* Write cell size here */
  55856. ){
  55857. int nPayload;
  55858. const u8 *pSrc;
  55859. int nSrc, n, rc;
  55860. int spaceLeft;
  55861. MemPage *pOvfl = 0;
  55862. MemPage *pToRelease = 0;
  55863. unsigned char *pPrior;
  55864. unsigned char *pPayload;
  55865. BtShared *pBt = pPage->pBt;
  55866. Pgno pgnoOvfl = 0;
  55867. int nHeader;
  55868. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55869. /* pPage is not necessarily writeable since pCell might be auxiliary
  55870. ** buffer space that is separate from the pPage buffer area */
  55871. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  55872. || sqlite3PagerIswriteable(pPage->pDbPage) );
  55873. /* Fill in the header. */
  55874. nHeader = pPage->childPtrSize;
  55875. nPayload = nData + nZero;
  55876. if( pPage->intKeyLeaf ){
  55877. nHeader += putVarint32(&pCell[nHeader], nPayload);
  55878. }else{
  55879. assert( nData==0 );
  55880. assert( nZero==0 );
  55881. }
  55882. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  55883. /* Fill in the payload size */
  55884. if( pPage->intKey ){
  55885. pSrc = pData;
  55886. nSrc = nData;
  55887. nData = 0;
  55888. }else{
  55889. assert( nKey<=0x7fffffff && pKey!=0 );
  55890. nPayload = (int)nKey;
  55891. pSrc = pKey;
  55892. nSrc = (int)nKey;
  55893. }
  55894. if( nPayload<=pPage->maxLocal ){
  55895. n = nHeader + nPayload;
  55896. testcase( n==3 );
  55897. testcase( n==4 );
  55898. if( n<4 ) n = 4;
  55899. *pnSize = n;
  55900. spaceLeft = nPayload;
  55901. pPrior = pCell;
  55902. }else{
  55903. int mn = pPage->minLocal;
  55904. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  55905. testcase( n==pPage->maxLocal );
  55906. testcase( n==pPage->maxLocal+1 );
  55907. if( n > pPage->maxLocal ) n = mn;
  55908. spaceLeft = n;
  55909. *pnSize = n + nHeader + 4;
  55910. pPrior = &pCell[nHeader+n];
  55911. }
  55912. pPayload = &pCell[nHeader];
  55913. /* At this point variables should be set as follows:
  55914. **
  55915. ** nPayload Total payload size in bytes
  55916. ** pPayload Begin writing payload here
  55917. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  55918. ** that means content must spill into overflow pages.
  55919. ** *pnSize Size of the local cell (not counting overflow pages)
  55920. ** pPrior Where to write the pgno of the first overflow page
  55921. **
  55922. ** Use a call to btreeParseCellPtr() to verify that the values above
  55923. ** were computed correctly.
  55924. */
  55925. #if SQLITE_DEBUG
  55926. {
  55927. CellInfo info;
  55928. pPage->xParseCell(pPage, pCell, &info);
  55929. assert( nHeader=(int)(info.pPayload - pCell) );
  55930. assert( info.nKey==nKey );
  55931. assert( *pnSize == info.nSize );
  55932. assert( spaceLeft == info.nLocal );
  55933. assert( pPrior == &pCell[info.iOverflow] );
  55934. }
  55935. #endif
  55936. /* Write the payload into the local Cell and any extra into overflow pages */
  55937. while( nPayload>0 ){
  55938. if( spaceLeft==0 ){
  55939. #ifndef SQLITE_OMIT_AUTOVACUUM
  55940. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  55941. if( pBt->autoVacuum ){
  55942. do{
  55943. pgnoOvfl++;
  55944. } while(
  55945. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  55946. );
  55947. }
  55948. #endif
  55949. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  55950. #ifndef SQLITE_OMIT_AUTOVACUUM
  55951. /* If the database supports auto-vacuum, and the second or subsequent
  55952. ** overflow page is being allocated, add an entry to the pointer-map
  55953. ** for that page now.
  55954. **
  55955. ** If this is the first overflow page, then write a partial entry
  55956. ** to the pointer-map. If we write nothing to this pointer-map slot,
  55957. ** then the optimistic overflow chain processing in clearCell()
  55958. ** may misinterpret the uninitialized values and delete the
  55959. ** wrong pages from the database.
  55960. */
  55961. if( pBt->autoVacuum && rc==SQLITE_OK ){
  55962. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  55963. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  55964. if( rc ){
  55965. releasePage(pOvfl);
  55966. }
  55967. }
  55968. #endif
  55969. if( rc ){
  55970. releasePage(pToRelease);
  55971. return rc;
  55972. }
  55973. /* If pToRelease is not zero than pPrior points into the data area
  55974. ** of pToRelease. Make sure pToRelease is still writeable. */
  55975. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  55976. /* If pPrior is part of the data area of pPage, then make sure pPage
  55977. ** is still writeable */
  55978. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  55979. || sqlite3PagerIswriteable(pPage->pDbPage) );
  55980. put4byte(pPrior, pgnoOvfl);
  55981. releasePage(pToRelease);
  55982. pToRelease = pOvfl;
  55983. pPrior = pOvfl->aData;
  55984. put4byte(pPrior, 0);
  55985. pPayload = &pOvfl->aData[4];
  55986. spaceLeft = pBt->usableSize - 4;
  55987. }
  55988. n = nPayload;
  55989. if( n>spaceLeft ) n = spaceLeft;
  55990. /* If pToRelease is not zero than pPayload points into the data area
  55991. ** of pToRelease. Make sure pToRelease is still writeable. */
  55992. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  55993. /* If pPayload is part of the data area of pPage, then make sure pPage
  55994. ** is still writeable */
  55995. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  55996. || sqlite3PagerIswriteable(pPage->pDbPage) );
  55997. if( nSrc>0 ){
  55998. if( n>nSrc ) n = nSrc;
  55999. assert( pSrc );
  56000. memcpy(pPayload, pSrc, n);
  56001. }else{
  56002. memset(pPayload, 0, n);
  56003. }
  56004. nPayload -= n;
  56005. pPayload += n;
  56006. pSrc += n;
  56007. nSrc -= n;
  56008. spaceLeft -= n;
  56009. if( nSrc==0 ){
  56010. nSrc = nData;
  56011. pSrc = pData;
  56012. }
  56013. }
  56014. releasePage(pToRelease);
  56015. return SQLITE_OK;
  56016. }
  56017. /*
  56018. ** Remove the i-th cell from pPage. This routine effects pPage only.
  56019. ** The cell content is not freed or deallocated. It is assumed that
  56020. ** the cell content has been copied someplace else. This routine just
  56021. ** removes the reference to the cell from pPage.
  56022. **
  56023. ** "sz" must be the number of bytes in the cell.
  56024. */
  56025. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  56026. u32 pc; /* Offset to cell content of cell being deleted */
  56027. u8 *data; /* pPage->aData */
  56028. u8 *ptr; /* Used to move bytes around within data[] */
  56029. int rc; /* The return code */
  56030. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  56031. if( *pRC ) return;
  56032. assert( idx>=0 && idx<pPage->nCell );
  56033. assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
  56034. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56035. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56036. data = pPage->aData;
  56037. ptr = &pPage->aCellIdx[2*idx];
  56038. pc = get2byte(ptr);
  56039. hdr = pPage->hdrOffset;
  56040. testcase( pc==get2byte(&data[hdr+5]) );
  56041. testcase( pc+sz==pPage->pBt->usableSize );
  56042. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  56043. *pRC = SQLITE_CORRUPT_BKPT;
  56044. return;
  56045. }
  56046. rc = freeSpace(pPage, pc, sz);
  56047. if( rc ){
  56048. *pRC = rc;
  56049. return;
  56050. }
  56051. pPage->nCell--;
  56052. if( pPage->nCell==0 ){
  56053. memset(&data[hdr+1], 0, 4);
  56054. data[hdr+7] = 0;
  56055. put2byte(&data[hdr+5], pPage->pBt->usableSize);
  56056. pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
  56057. - pPage->childPtrSize - 8;
  56058. }else{
  56059. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  56060. put2byte(&data[hdr+3], pPage->nCell);
  56061. pPage->nFree += 2;
  56062. }
  56063. }
  56064. /*
  56065. ** Insert a new cell on pPage at cell index "i". pCell points to the
  56066. ** content of the cell.
  56067. **
  56068. ** If the cell content will fit on the page, then put it there. If it
  56069. ** will not fit, then make a copy of the cell content into pTemp if
  56070. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  56071. ** in pPage->apOvfl[] and make it point to the cell content (either
  56072. ** in pTemp or the original pCell) and also record its index.
  56073. ** Allocating a new entry in pPage->aCell[] implies that
  56074. ** pPage->nOverflow is incremented.
  56075. */
  56076. static void insertCell(
  56077. MemPage *pPage, /* Page into which we are copying */
  56078. int i, /* New cell becomes the i-th cell of the page */
  56079. u8 *pCell, /* Content of the new cell */
  56080. int sz, /* Bytes of content in pCell */
  56081. u8 *pTemp, /* Temp storage space for pCell, if needed */
  56082. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  56083. int *pRC /* Read and write return code from here */
  56084. ){
  56085. int idx = 0; /* Where to write new cell content in data[] */
  56086. int j; /* Loop counter */
  56087. u8 *data; /* The content of the whole page */
  56088. u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
  56089. if( *pRC ) return;
  56090. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  56091. assert( MX_CELL(pPage->pBt)<=10921 );
  56092. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  56093. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  56094. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  56095. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56096. /* The cell should normally be sized correctly. However, when moving a
  56097. ** malformed cell from a leaf page to an interior page, if the cell size
  56098. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  56099. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  56100. ** the term after the || in the following assert(). */
  56101. assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
  56102. if( pPage->nOverflow || sz+2>pPage->nFree ){
  56103. if( pTemp ){
  56104. memcpy(pTemp, pCell, sz);
  56105. pCell = pTemp;
  56106. }
  56107. if( iChild ){
  56108. put4byte(pCell, iChild);
  56109. }
  56110. j = pPage->nOverflow++;
  56111. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  56112. pPage->apOvfl[j] = pCell;
  56113. pPage->aiOvfl[j] = (u16)i;
  56114. /* When multiple overflows occur, they are always sequential and in
  56115. ** sorted order. This invariants arise because multiple overflows can
  56116. ** only occur when inserting divider cells into the parent page during
  56117. ** balancing, and the dividers are adjacent and sorted.
  56118. */
  56119. assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
  56120. assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
  56121. }else{
  56122. int rc = sqlite3PagerWrite(pPage->pDbPage);
  56123. if( rc!=SQLITE_OK ){
  56124. *pRC = rc;
  56125. return;
  56126. }
  56127. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  56128. data = pPage->aData;
  56129. assert( &data[pPage->cellOffset]==pPage->aCellIdx );
  56130. rc = allocateSpace(pPage, sz, &idx);
  56131. if( rc ){ *pRC = rc; return; }
  56132. /* The allocateSpace() routine guarantees the following properties
  56133. ** if it returns successfully */
  56134. assert( idx >= 0 );
  56135. assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
  56136. assert( idx+sz <= (int)pPage->pBt->usableSize );
  56137. pPage->nFree -= (u16)(2 + sz);
  56138. memcpy(&data[idx], pCell, sz);
  56139. if( iChild ){
  56140. put4byte(&data[idx], iChild);
  56141. }
  56142. pIns = pPage->aCellIdx + i*2;
  56143. memmove(pIns+2, pIns, 2*(pPage->nCell - i));
  56144. put2byte(pIns, idx);
  56145. pPage->nCell++;
  56146. /* increment the cell count */
  56147. if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
  56148. assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
  56149. #ifndef SQLITE_OMIT_AUTOVACUUM
  56150. if( pPage->pBt->autoVacuum ){
  56151. /* The cell may contain a pointer to an overflow page. If so, write
  56152. ** the entry for the overflow page into the pointer map.
  56153. */
  56154. ptrmapPutOvflPtr(pPage, pCell, pRC);
  56155. }
  56156. #endif
  56157. }
  56158. }
  56159. /*
  56160. ** A CellArray object contains a cache of pointers and sizes for a
  56161. ** consecutive sequence of cells that might be held multiple pages.
  56162. */
  56163. typedef struct CellArray CellArray;
  56164. struct CellArray {
  56165. int nCell; /* Number of cells in apCell[] */
  56166. MemPage *pRef; /* Reference page */
  56167. u8 **apCell; /* All cells begin balanced */
  56168. u16 *szCell; /* Local size of all cells in apCell[] */
  56169. };
  56170. /*
  56171. ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
  56172. ** computed.
  56173. */
  56174. static void populateCellCache(CellArray *p, int idx, int N){
  56175. assert( idx>=0 && idx+N<=p->nCell );
  56176. while( N>0 ){
  56177. assert( p->apCell[idx]!=0 );
  56178. if( p->szCell[idx]==0 ){
  56179. p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
  56180. }else{
  56181. assert( CORRUPT_DB ||
  56182. p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
  56183. }
  56184. idx++;
  56185. N--;
  56186. }
  56187. }
  56188. /*
  56189. ** Return the size of the Nth element of the cell array
  56190. */
  56191. static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N){
  56192. assert( N>=0 && N<p->nCell );
  56193. assert( p->szCell[N]==0 );
  56194. p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
  56195. return p->szCell[N];
  56196. }
  56197. static u16 cachedCellSize(CellArray *p, int N){
  56198. assert( N>=0 && N<p->nCell );
  56199. if( p->szCell[N] ) return p->szCell[N];
  56200. return computeCellSize(p, N);
  56201. }
  56202. /*
  56203. ** Array apCell[] contains pointers to nCell b-tree page cells. The
  56204. ** szCell[] array contains the size in bytes of each cell. This function
  56205. ** replaces the current contents of page pPg with the contents of the cell
  56206. ** array.
  56207. **
  56208. ** Some of the cells in apCell[] may currently be stored in pPg. This
  56209. ** function works around problems caused by this by making a copy of any
  56210. ** such cells before overwriting the page data.
  56211. **
  56212. ** The MemPage.nFree field is invalidated by this function. It is the
  56213. ** responsibility of the caller to set it correctly.
  56214. */
  56215. static int rebuildPage(
  56216. MemPage *pPg, /* Edit this page */
  56217. int nCell, /* Final number of cells on page */
  56218. u8 **apCell, /* Array of cells */
  56219. u16 *szCell /* Array of cell sizes */
  56220. ){
  56221. const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
  56222. u8 * const aData = pPg->aData; /* Pointer to data for pPg */
  56223. const int usableSize = pPg->pBt->usableSize;
  56224. u8 * const pEnd = &aData[usableSize];
  56225. int i;
  56226. u8 *pCellptr = pPg->aCellIdx;
  56227. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  56228. u8 *pData;
  56229. i = get2byte(&aData[hdr+5]);
  56230. memcpy(&pTmp[i], &aData[i], usableSize - i);
  56231. pData = pEnd;
  56232. for(i=0; i<nCell; i++){
  56233. u8 *pCell = apCell[i];
  56234. if( pCell>aData && pCell<pEnd ){
  56235. pCell = &pTmp[pCell - aData];
  56236. }
  56237. pData -= szCell[i];
  56238. put2byte(pCellptr, (pData - aData));
  56239. pCellptr += 2;
  56240. if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
  56241. memcpy(pData, pCell, szCell[i]);
  56242. assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
  56243. testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
  56244. }
  56245. /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
  56246. pPg->nCell = nCell;
  56247. pPg->nOverflow = 0;
  56248. put2byte(&aData[hdr+1], 0);
  56249. put2byte(&aData[hdr+3], pPg->nCell);
  56250. put2byte(&aData[hdr+5], pData - aData);
  56251. aData[hdr+7] = 0x00;
  56252. return SQLITE_OK;
  56253. }
  56254. /*
  56255. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  56256. ** contains the size in bytes of each such cell. This function attempts to
  56257. ** add the cells stored in the array to page pPg. If it cannot (because
  56258. ** the page needs to be defragmented before the cells will fit), non-zero
  56259. ** is returned. Otherwise, if the cells are added successfully, zero is
  56260. ** returned.
  56261. **
  56262. ** Argument pCellptr points to the first entry in the cell-pointer array
  56263. ** (part of page pPg) to populate. After cell apCell[0] is written to the
  56264. ** page body, a 16-bit offset is written to pCellptr. And so on, for each
  56265. ** cell in the array. It is the responsibility of the caller to ensure
  56266. ** that it is safe to overwrite this part of the cell-pointer array.
  56267. **
  56268. ** When this function is called, *ppData points to the start of the
  56269. ** content area on page pPg. If the size of the content area is extended,
  56270. ** *ppData is updated to point to the new start of the content area
  56271. ** before returning.
  56272. **
  56273. ** Finally, argument pBegin points to the byte immediately following the
  56274. ** end of the space required by this page for the cell-pointer area (for
  56275. ** all cells - not just those inserted by the current call). If the content
  56276. ** area must be extended to before this point in order to accomodate all
  56277. ** cells in apCell[], then the cells do not fit and non-zero is returned.
  56278. */
  56279. static int pageInsertArray(
  56280. MemPage *pPg, /* Page to add cells to */
  56281. u8 *pBegin, /* End of cell-pointer array */
  56282. u8 **ppData, /* IN/OUT: Page content -area pointer */
  56283. u8 *pCellptr, /* Pointer to cell-pointer area */
  56284. int iFirst, /* Index of first cell to add */
  56285. int nCell, /* Number of cells to add to pPg */
  56286. CellArray *pCArray /* Array of cells */
  56287. ){
  56288. int i;
  56289. u8 *aData = pPg->aData;
  56290. u8 *pData = *ppData;
  56291. int iEnd = iFirst + nCell;
  56292. assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
  56293. for(i=iFirst; i<iEnd; i++){
  56294. int sz, rc;
  56295. u8 *pSlot;
  56296. sz = cachedCellSize(pCArray, i);
  56297. if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
  56298. pData -= sz;
  56299. if( pData<pBegin ) return 1;
  56300. pSlot = pData;
  56301. }
  56302. memcpy(pSlot, pCArray->apCell[i], sz);
  56303. put2byte(pCellptr, (pSlot - aData));
  56304. pCellptr += 2;
  56305. }
  56306. *ppData = pData;
  56307. return 0;
  56308. }
  56309. /*
  56310. ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
  56311. ** contains the size in bytes of each such cell. This function adds the
  56312. ** space associated with each cell in the array that is currently stored
  56313. ** within the body of pPg to the pPg free-list. The cell-pointers and other
  56314. ** fields of the page are not updated.
  56315. **
  56316. ** This function returns the total number of cells added to the free-list.
  56317. */
  56318. static int pageFreeArray(
  56319. MemPage *pPg, /* Page to edit */
  56320. int iFirst, /* First cell to delete */
  56321. int nCell, /* Cells to delete */
  56322. CellArray *pCArray /* Array of cells */
  56323. ){
  56324. u8 * const aData = pPg->aData;
  56325. u8 * const pEnd = &aData[pPg->pBt->usableSize];
  56326. u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
  56327. int nRet = 0;
  56328. int i;
  56329. int iEnd = iFirst + nCell;
  56330. u8 *pFree = 0;
  56331. int szFree = 0;
  56332. for(i=iFirst; i<iEnd; i++){
  56333. u8 *pCell = pCArray->apCell[i];
  56334. if( pCell>=pStart && pCell<pEnd ){
  56335. int sz;
  56336. /* No need to use cachedCellSize() here. The sizes of all cells that
  56337. ** are to be freed have already been computing while deciding which
  56338. ** cells need freeing */
  56339. sz = pCArray->szCell[i]; assert( sz>0 );
  56340. if( pFree!=(pCell + sz) ){
  56341. if( pFree ){
  56342. assert( pFree>aData && (pFree - aData)<65536 );
  56343. freeSpace(pPg, (u16)(pFree - aData), szFree);
  56344. }
  56345. pFree = pCell;
  56346. szFree = sz;
  56347. if( pFree+sz>pEnd ) return 0;
  56348. }else{
  56349. pFree = pCell;
  56350. szFree += sz;
  56351. }
  56352. nRet++;
  56353. }
  56354. }
  56355. if( pFree ){
  56356. assert( pFree>aData && (pFree - aData)<65536 );
  56357. freeSpace(pPg, (u16)(pFree - aData), szFree);
  56358. }
  56359. return nRet;
  56360. }
  56361. /*
  56362. ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
  56363. ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
  56364. ** with apCell[iOld]. After balancing, this page should hold nNew cells
  56365. ** starting at apCell[iNew].
  56366. **
  56367. ** This routine makes the necessary adjustments to pPg so that it contains
  56368. ** the correct cells after being balanced.
  56369. **
  56370. ** The pPg->nFree field is invalid when this function returns. It is the
  56371. ** responsibility of the caller to set it correctly.
  56372. */
  56373. static int editPage(
  56374. MemPage *pPg, /* Edit this page */
  56375. int iOld, /* Index of first cell currently on page */
  56376. int iNew, /* Index of new first cell on page */
  56377. int nNew, /* Final number of cells on page */
  56378. CellArray *pCArray /* Array of cells and sizes */
  56379. ){
  56380. u8 * const aData = pPg->aData;
  56381. const int hdr = pPg->hdrOffset;
  56382. u8 *pBegin = &pPg->aCellIdx[nNew * 2];
  56383. int nCell = pPg->nCell; /* Cells stored on pPg */
  56384. u8 *pData;
  56385. u8 *pCellptr;
  56386. int i;
  56387. int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
  56388. int iNewEnd = iNew + nNew;
  56389. #ifdef SQLITE_DEBUG
  56390. u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
  56391. memcpy(pTmp, aData, pPg->pBt->usableSize);
  56392. #endif
  56393. /* Remove cells from the start and end of the page */
  56394. if( iOld<iNew ){
  56395. int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
  56396. memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
  56397. nCell -= nShift;
  56398. }
  56399. if( iNewEnd < iOldEnd ){
  56400. nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
  56401. }
  56402. pData = &aData[get2byteNotZero(&aData[hdr+5])];
  56403. if( pData<pBegin ) goto editpage_fail;
  56404. /* Add cells to the start of the page */
  56405. if( iNew<iOld ){
  56406. int nAdd = MIN(nNew,iOld-iNew);
  56407. assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
  56408. pCellptr = pPg->aCellIdx;
  56409. memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
  56410. if( pageInsertArray(
  56411. pPg, pBegin, &pData, pCellptr,
  56412. iNew, nAdd, pCArray
  56413. ) ) goto editpage_fail;
  56414. nCell += nAdd;
  56415. }
  56416. /* Add any overflow cells */
  56417. for(i=0; i<pPg->nOverflow; i++){
  56418. int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
  56419. if( iCell>=0 && iCell<nNew ){
  56420. pCellptr = &pPg->aCellIdx[iCell * 2];
  56421. memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
  56422. nCell++;
  56423. if( pageInsertArray(
  56424. pPg, pBegin, &pData, pCellptr,
  56425. iCell+iNew, 1, pCArray
  56426. ) ) goto editpage_fail;
  56427. }
  56428. }
  56429. /* Append cells to the end of the page */
  56430. pCellptr = &pPg->aCellIdx[nCell*2];
  56431. if( pageInsertArray(
  56432. pPg, pBegin, &pData, pCellptr,
  56433. iNew+nCell, nNew-nCell, pCArray
  56434. ) ) goto editpage_fail;
  56435. pPg->nCell = nNew;
  56436. pPg->nOverflow = 0;
  56437. put2byte(&aData[hdr+3], pPg->nCell);
  56438. put2byte(&aData[hdr+5], pData - aData);
  56439. #ifdef SQLITE_DEBUG
  56440. for(i=0; i<nNew && !CORRUPT_DB; i++){
  56441. u8 *pCell = pCArray->apCell[i+iNew];
  56442. int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
  56443. if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
  56444. pCell = &pTmp[pCell - aData];
  56445. }
  56446. assert( 0==memcmp(pCell, &aData[iOff],
  56447. pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
  56448. }
  56449. #endif
  56450. return SQLITE_OK;
  56451. editpage_fail:
  56452. /* Unable to edit this page. Rebuild it from scratch instead. */
  56453. populateCellCache(pCArray, iNew, nNew);
  56454. return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
  56455. }
  56456. /*
  56457. ** The following parameters determine how many adjacent pages get involved
  56458. ** in a balancing operation. NN is the number of neighbors on either side
  56459. ** of the page that participate in the balancing operation. NB is the
  56460. ** total number of pages that participate, including the target page and
  56461. ** NN neighbors on either side.
  56462. **
  56463. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  56464. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  56465. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  56466. ** The value of NN appears to give the best results overall.
  56467. */
  56468. #define NN 1 /* Number of neighbors on either side of pPage */
  56469. #define NB (NN*2+1) /* Total pages involved in the balance */
  56470. #ifndef SQLITE_OMIT_QUICKBALANCE
  56471. /*
  56472. ** This version of balance() handles the common special case where
  56473. ** a new entry is being inserted on the extreme right-end of the
  56474. ** tree, in other words, when the new entry will become the largest
  56475. ** entry in the tree.
  56476. **
  56477. ** Instead of trying to balance the 3 right-most leaf pages, just add
  56478. ** a new page to the right-hand side and put the one new entry in
  56479. ** that page. This leaves the right side of the tree somewhat
  56480. ** unbalanced. But odds are that we will be inserting new entries
  56481. ** at the end soon afterwards so the nearly empty page will quickly
  56482. ** fill up. On average.
  56483. **
  56484. ** pPage is the leaf page which is the right-most page in the tree.
  56485. ** pParent is its parent. pPage must have a single overflow entry
  56486. ** which is also the right-most entry on the page.
  56487. **
  56488. ** The pSpace buffer is used to store a temporary copy of the divider
  56489. ** cell that will be inserted into pParent. Such a cell consists of a 4
  56490. ** byte page number followed by a variable length integer. In other
  56491. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  56492. ** least 13 bytes in size.
  56493. */
  56494. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  56495. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  56496. MemPage *pNew; /* Newly allocated page */
  56497. int rc; /* Return Code */
  56498. Pgno pgnoNew; /* Page number of pNew */
  56499. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  56500. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  56501. assert( pPage->nOverflow==1 );
  56502. /* This error condition is now caught prior to reaching this function */
  56503. if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
  56504. /* Allocate a new page. This page will become the right-sibling of
  56505. ** pPage. Make the parent page writable, so that the new divider cell
  56506. ** may be inserted. If both these operations are successful, proceed.
  56507. */
  56508. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  56509. if( rc==SQLITE_OK ){
  56510. u8 *pOut = &pSpace[4];
  56511. u8 *pCell = pPage->apOvfl[0];
  56512. u16 szCell = pPage->xCellSize(pPage, pCell);
  56513. u8 *pStop;
  56514. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  56515. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  56516. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  56517. rc = rebuildPage(pNew, 1, &pCell, &szCell);
  56518. if( NEVER(rc) ) return rc;
  56519. pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
  56520. /* If this is an auto-vacuum database, update the pointer map
  56521. ** with entries for the new page, and any pointer from the
  56522. ** cell on the page to an overflow page. If either of these
  56523. ** operations fails, the return code is set, but the contents
  56524. ** of the parent page are still manipulated by thh code below.
  56525. ** That is Ok, at this point the parent page is guaranteed to
  56526. ** be marked as dirty. Returning an error code will cause a
  56527. ** rollback, undoing any changes made to the parent page.
  56528. */
  56529. if( ISAUTOVACUUM ){
  56530. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  56531. if( szCell>pNew->minLocal ){
  56532. ptrmapPutOvflPtr(pNew, pCell, &rc);
  56533. }
  56534. }
  56535. /* Create a divider cell to insert into pParent. The divider cell
  56536. ** consists of a 4-byte page number (the page number of pPage) and
  56537. ** a variable length key value (which must be the same value as the
  56538. ** largest key on pPage).
  56539. **
  56540. ** To find the largest key value on pPage, first find the right-most
  56541. ** cell on pPage. The first two fields of this cell are the
  56542. ** record-length (a variable length integer at most 32-bits in size)
  56543. ** and the key value (a variable length integer, may have any value).
  56544. ** The first of the while(...) loops below skips over the record-length
  56545. ** field. The second while(...) loop copies the key value from the
  56546. ** cell on pPage into the pSpace buffer.
  56547. */
  56548. pCell = findCell(pPage, pPage->nCell-1);
  56549. pStop = &pCell[9];
  56550. while( (*(pCell++)&0x80) && pCell<pStop );
  56551. pStop = &pCell[9];
  56552. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  56553. /* Insert the new divider cell into pParent. */
  56554. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  56555. 0, pPage->pgno, &rc);
  56556. /* Set the right-child pointer of pParent to point to the new page. */
  56557. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  56558. /* Release the reference to the new page. */
  56559. releasePage(pNew);
  56560. }
  56561. return rc;
  56562. }
  56563. #endif /* SQLITE_OMIT_QUICKBALANCE */
  56564. #if 0
  56565. /*
  56566. ** This function does not contribute anything to the operation of SQLite.
  56567. ** it is sometimes activated temporarily while debugging code responsible
  56568. ** for setting pointer-map entries.
  56569. */
  56570. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  56571. int i, j;
  56572. for(i=0; i<nPage; i++){
  56573. Pgno n;
  56574. u8 e;
  56575. MemPage *pPage = apPage[i];
  56576. BtShared *pBt = pPage->pBt;
  56577. assert( pPage->isInit );
  56578. for(j=0; j<pPage->nCell; j++){
  56579. CellInfo info;
  56580. u8 *z;
  56581. z = findCell(pPage, j);
  56582. pPage->xParseCell(pPage, z, &info);
  56583. if( info.iOverflow ){
  56584. Pgno ovfl = get4byte(&z[info.iOverflow]);
  56585. ptrmapGet(pBt, ovfl, &e, &n);
  56586. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  56587. }
  56588. if( !pPage->leaf ){
  56589. Pgno child = get4byte(z);
  56590. ptrmapGet(pBt, child, &e, &n);
  56591. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  56592. }
  56593. }
  56594. if( !pPage->leaf ){
  56595. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  56596. ptrmapGet(pBt, child, &e, &n);
  56597. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  56598. }
  56599. }
  56600. return 1;
  56601. }
  56602. #endif
  56603. /*
  56604. ** This function is used to copy the contents of the b-tree node stored
  56605. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  56606. ** the pointer-map entries for each child page are updated so that the
  56607. ** parent page stored in the pointer map is page pTo. If pFrom contained
  56608. ** any cells with overflow page pointers, then the corresponding pointer
  56609. ** map entries are also updated so that the parent page is page pTo.
  56610. **
  56611. ** If pFrom is currently carrying any overflow cells (entries in the
  56612. ** MemPage.apOvfl[] array), they are not copied to pTo.
  56613. **
  56614. ** Before returning, page pTo is reinitialized using btreeInitPage().
  56615. **
  56616. ** The performance of this function is not critical. It is only used by
  56617. ** the balance_shallower() and balance_deeper() procedures, neither of
  56618. ** which are called often under normal circumstances.
  56619. */
  56620. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  56621. if( (*pRC)==SQLITE_OK ){
  56622. BtShared * const pBt = pFrom->pBt;
  56623. u8 * const aFrom = pFrom->aData;
  56624. u8 * const aTo = pTo->aData;
  56625. int const iFromHdr = pFrom->hdrOffset;
  56626. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  56627. int rc;
  56628. int iData;
  56629. assert( pFrom->isInit );
  56630. assert( pFrom->nFree>=iToHdr );
  56631. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  56632. /* Copy the b-tree node content from page pFrom to page pTo. */
  56633. iData = get2byte(&aFrom[iFromHdr+5]);
  56634. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  56635. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  56636. /* Reinitialize page pTo so that the contents of the MemPage structure
  56637. ** match the new data. The initialization of pTo can actually fail under
  56638. ** fairly obscure circumstances, even though it is a copy of initialized
  56639. ** page pFrom.
  56640. */
  56641. pTo->isInit = 0;
  56642. rc = btreeInitPage(pTo);
  56643. if( rc!=SQLITE_OK ){
  56644. *pRC = rc;
  56645. return;
  56646. }
  56647. /* If this is an auto-vacuum database, update the pointer-map entries
  56648. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  56649. */
  56650. if( ISAUTOVACUUM ){
  56651. *pRC = setChildPtrmaps(pTo);
  56652. }
  56653. }
  56654. }
  56655. /*
  56656. ** This routine redistributes cells on the iParentIdx'th child of pParent
  56657. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  56658. ** same amount of free space. Usually a single sibling on either side of the
  56659. ** page are used in the balancing, though both siblings might come from one
  56660. ** side if the page is the first or last child of its parent. If the page
  56661. ** has fewer than 2 siblings (something which can only happen if the page
  56662. ** is a root page or a child of a root page) then all available siblings
  56663. ** participate in the balancing.
  56664. **
  56665. ** The number of siblings of the page might be increased or decreased by
  56666. ** one or two in an effort to keep pages nearly full but not over full.
  56667. **
  56668. ** Note that when this routine is called, some of the cells on the page
  56669. ** might not actually be stored in MemPage.aData[]. This can happen
  56670. ** if the page is overfull. This routine ensures that all cells allocated
  56671. ** to the page and its siblings fit into MemPage.aData[] before returning.
  56672. **
  56673. ** In the course of balancing the page and its siblings, cells may be
  56674. ** inserted into or removed from the parent page (pParent). Doing so
  56675. ** may cause the parent page to become overfull or underfull. If this
  56676. ** happens, it is the responsibility of the caller to invoke the correct
  56677. ** balancing routine to fix this problem (see the balance() routine).
  56678. **
  56679. ** If this routine fails for any reason, it might leave the database
  56680. ** in a corrupted state. So if this routine fails, the database should
  56681. ** be rolled back.
  56682. **
  56683. ** The third argument to this function, aOvflSpace, is a pointer to a
  56684. ** buffer big enough to hold one page. If while inserting cells into the parent
  56685. ** page (pParent) the parent page becomes overfull, this buffer is
  56686. ** used to store the parent's overflow cells. Because this function inserts
  56687. ** a maximum of four divider cells into the parent page, and the maximum
  56688. ** size of a cell stored within an internal node is always less than 1/4
  56689. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  56690. ** enough for all overflow cells.
  56691. **
  56692. ** If aOvflSpace is set to a null pointer, this function returns
  56693. ** SQLITE_NOMEM.
  56694. */
  56695. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  56696. #pragma optimize("", off)
  56697. #endif
  56698. static int balance_nonroot(
  56699. MemPage *pParent, /* Parent page of siblings being balanced */
  56700. int iParentIdx, /* Index of "the page" in pParent */
  56701. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  56702. int isRoot, /* True if pParent is a root-page */
  56703. int bBulk /* True if this call is part of a bulk load */
  56704. ){
  56705. BtShared *pBt; /* The whole database */
  56706. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  56707. int nNew = 0; /* Number of pages in apNew[] */
  56708. int nOld; /* Number of pages in apOld[] */
  56709. int i, j, k; /* Loop counters */
  56710. int nxDiv; /* Next divider slot in pParent->aCell[] */
  56711. int rc = SQLITE_OK; /* The return code */
  56712. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  56713. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  56714. int usableSpace; /* Bytes in pPage beyond the header */
  56715. int pageFlags; /* Value of pPage->aData[0] */
  56716. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  56717. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  56718. int szScratch; /* Size of scratch memory requested */
  56719. MemPage *apOld[NB]; /* pPage and up to two siblings */
  56720. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  56721. u8 *pRight; /* Location in parent of right-sibling pointer */
  56722. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  56723. int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
  56724. int cntOld[NB+2]; /* Old index in b.apCell[] */
  56725. int szNew[NB+2]; /* Combined size of cells placed on i-th page */
  56726. u8 *aSpace1; /* Space for copies of dividers cells */
  56727. Pgno pgno; /* Temp var to store a page number in */
  56728. u8 abDone[NB+2]; /* True after i'th new page is populated */
  56729. Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
  56730. Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
  56731. u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
  56732. CellArray b; /* Parsed information on cells being balanced */
  56733. memset(abDone, 0, sizeof(abDone));
  56734. b.nCell = 0;
  56735. b.apCell = 0;
  56736. pBt = pParent->pBt;
  56737. assert( sqlite3_mutex_held(pBt->mutex) );
  56738. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  56739. #if 0
  56740. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  56741. #endif
  56742. /* At this point pParent may have at most one overflow cell. And if
  56743. ** this overflow cell is present, it must be the cell with
  56744. ** index iParentIdx. This scenario comes about when this function
  56745. ** is called (indirectly) from sqlite3BtreeDelete().
  56746. */
  56747. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  56748. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  56749. if( !aOvflSpace ){
  56750. return SQLITE_NOMEM;
  56751. }
  56752. /* Find the sibling pages to balance. Also locate the cells in pParent
  56753. ** that divide the siblings. An attempt is made to find NN siblings on
  56754. ** either side of pPage. More siblings are taken from one side, however,
  56755. ** if there are fewer than NN siblings on the other side. If pParent
  56756. ** has NB or fewer children then all children of pParent are taken.
  56757. **
  56758. ** This loop also drops the divider cells from the parent page. This
  56759. ** way, the remainder of the function does not have to deal with any
  56760. ** overflow cells in the parent page, since if any existed they will
  56761. ** have already been removed.
  56762. */
  56763. i = pParent->nOverflow + pParent->nCell;
  56764. if( i<2 ){
  56765. nxDiv = 0;
  56766. }else{
  56767. assert( bBulk==0 || bBulk==1 );
  56768. if( iParentIdx==0 ){
  56769. nxDiv = 0;
  56770. }else if( iParentIdx==i ){
  56771. nxDiv = i-2+bBulk;
  56772. }else{
  56773. nxDiv = iParentIdx-1;
  56774. }
  56775. i = 2-bBulk;
  56776. }
  56777. nOld = i+1;
  56778. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  56779. pRight = &pParent->aData[pParent->hdrOffset+8];
  56780. }else{
  56781. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  56782. }
  56783. pgno = get4byte(pRight);
  56784. while( 1 ){
  56785. rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
  56786. if( rc ){
  56787. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  56788. goto balance_cleanup;
  56789. }
  56790. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  56791. if( (i--)==0 ) break;
  56792. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  56793. apDiv[i] = pParent->apOvfl[0];
  56794. pgno = get4byte(apDiv[i]);
  56795. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  56796. pParent->nOverflow = 0;
  56797. }else{
  56798. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  56799. pgno = get4byte(apDiv[i]);
  56800. szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
  56801. /* Drop the cell from the parent page. apDiv[i] still points to
  56802. ** the cell within the parent, even though it has been dropped.
  56803. ** This is safe because dropping a cell only overwrites the first
  56804. ** four bytes of it, and this function does not need the first
  56805. ** four bytes of the divider cell. So the pointer is safe to use
  56806. ** later on.
  56807. **
  56808. ** But not if we are in secure-delete mode. In secure-delete mode,
  56809. ** the dropCell() routine will overwrite the entire cell with zeroes.
  56810. ** In this case, temporarily copy the cell into the aOvflSpace[]
  56811. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  56812. ** is allocated. */
  56813. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  56814. int iOff;
  56815. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  56816. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  56817. rc = SQLITE_CORRUPT_BKPT;
  56818. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  56819. goto balance_cleanup;
  56820. }else{
  56821. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  56822. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  56823. }
  56824. }
  56825. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  56826. }
  56827. }
  56828. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  56829. ** alignment */
  56830. nMaxCells = (nMaxCells + 3)&~3;
  56831. /*
  56832. ** Allocate space for memory structures
  56833. */
  56834. szScratch =
  56835. nMaxCells*sizeof(u8*) /* b.apCell */
  56836. + nMaxCells*sizeof(u16) /* b.szCell */
  56837. + pBt->pageSize; /* aSpace1 */
  56838. /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
  56839. ** that is more than 6 times the database page size. */
  56840. assert( szScratch<=6*(int)pBt->pageSize );
  56841. b.apCell = sqlite3ScratchMalloc( szScratch );
  56842. if( b.apCell==0 ){
  56843. rc = SQLITE_NOMEM;
  56844. goto balance_cleanup;
  56845. }
  56846. b.szCell = (u16*)&b.apCell[nMaxCells];
  56847. aSpace1 = (u8*)&b.szCell[nMaxCells];
  56848. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  56849. /*
  56850. ** Load pointers to all cells on sibling pages and the divider cells
  56851. ** into the local b.apCell[] array. Make copies of the divider cells
  56852. ** into space obtained from aSpace1[]. The divider cells have already
  56853. ** been removed from pParent.
  56854. **
  56855. ** If the siblings are on leaf pages, then the child pointers of the
  56856. ** divider cells are stripped from the cells before they are copied
  56857. ** into aSpace1[]. In this way, all cells in b.apCell[] are without
  56858. ** child pointers. If siblings are not leaves, then all cell in
  56859. ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
  56860. ** are alike.
  56861. **
  56862. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  56863. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  56864. */
  56865. b.pRef = apOld[0];
  56866. leafCorrection = b.pRef->leaf*4;
  56867. leafData = b.pRef->intKeyLeaf;
  56868. for(i=0; i<nOld; i++){
  56869. MemPage *pOld = apOld[i];
  56870. int limit = pOld->nCell;
  56871. u8 *aData = pOld->aData;
  56872. u16 maskPage = pOld->maskPage;
  56873. u8 *piCell = aData + pOld->cellOffset;
  56874. u8 *piEnd;
  56875. /* Verify that all sibling pages are of the same "type" (table-leaf,
  56876. ** table-interior, index-leaf, or index-interior).
  56877. */
  56878. if( pOld->aData[0]!=apOld[0]->aData[0] ){
  56879. rc = SQLITE_CORRUPT_BKPT;
  56880. goto balance_cleanup;
  56881. }
  56882. /* Load b.apCell[] with pointers to all cells in pOld. If pOld
  56883. ** constains overflow cells, include them in the b.apCell[] array
  56884. ** in the correct spot.
  56885. **
  56886. ** Note that when there are multiple overflow cells, it is always the
  56887. ** case that they are sequential and adjacent. This invariant arises
  56888. ** because multiple overflows can only occurs when inserting divider
  56889. ** cells into a parent on a prior balance, and divider cells are always
  56890. ** adjacent and are inserted in order. There is an assert() tagged
  56891. ** with "NOTE 1" in the overflow cell insertion loop to prove this
  56892. ** invariant.
  56893. **
  56894. ** This must be done in advance. Once the balance starts, the cell
  56895. ** offset section of the btree page will be overwritten and we will no
  56896. ** long be able to find the cells if a pointer to each cell is not saved
  56897. ** first.
  56898. */
  56899. memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*limit);
  56900. if( pOld->nOverflow>0 ){
  56901. memset(&b.szCell[b.nCell+limit], 0, sizeof(b.szCell[0])*pOld->nOverflow);
  56902. limit = pOld->aiOvfl[0];
  56903. for(j=0; j<limit; j++){
  56904. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  56905. piCell += 2;
  56906. b.nCell++;
  56907. }
  56908. for(k=0; k<pOld->nOverflow; k++){
  56909. assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
  56910. b.apCell[b.nCell] = pOld->apOvfl[k];
  56911. b.nCell++;
  56912. }
  56913. }
  56914. piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
  56915. while( piCell<piEnd ){
  56916. assert( b.nCell<nMaxCells );
  56917. b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
  56918. piCell += 2;
  56919. b.nCell++;
  56920. }
  56921. cntOld[i] = b.nCell;
  56922. if( i<nOld-1 && !leafData){
  56923. u16 sz = (u16)szNew[i];
  56924. u8 *pTemp;
  56925. assert( b.nCell<nMaxCells );
  56926. b.szCell[b.nCell] = sz;
  56927. pTemp = &aSpace1[iSpace1];
  56928. iSpace1 += sz;
  56929. assert( sz<=pBt->maxLocal+23 );
  56930. assert( iSpace1 <= (int)pBt->pageSize );
  56931. memcpy(pTemp, apDiv[i], sz);
  56932. b.apCell[b.nCell] = pTemp+leafCorrection;
  56933. assert( leafCorrection==0 || leafCorrection==4 );
  56934. b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
  56935. if( !pOld->leaf ){
  56936. assert( leafCorrection==0 );
  56937. assert( pOld->hdrOffset==0 );
  56938. /* The right pointer of the child page pOld becomes the left
  56939. ** pointer of the divider cell */
  56940. memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
  56941. }else{
  56942. assert( leafCorrection==4 );
  56943. while( b.szCell[b.nCell]<4 ){
  56944. /* Do not allow any cells smaller than 4 bytes. If a smaller cell
  56945. ** does exist, pad it with 0x00 bytes. */
  56946. assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
  56947. assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
  56948. aSpace1[iSpace1++] = 0x00;
  56949. b.szCell[b.nCell]++;
  56950. }
  56951. }
  56952. b.nCell++;
  56953. }
  56954. }
  56955. /*
  56956. ** Figure out the number of pages needed to hold all b.nCell cells.
  56957. ** Store this number in "k". Also compute szNew[] which is the total
  56958. ** size of all cells on the i-th page and cntNew[] which is the index
  56959. ** in b.apCell[] of the cell that divides page i from page i+1.
  56960. ** cntNew[k] should equal b.nCell.
  56961. **
  56962. ** Values computed by this block:
  56963. **
  56964. ** k: The total number of sibling pages
  56965. ** szNew[i]: Spaced used on the i-th sibling page.
  56966. ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
  56967. ** the right of the i-th sibling page.
  56968. ** usableSpace: Number of bytes of space available on each sibling.
  56969. **
  56970. */
  56971. usableSpace = pBt->usableSize - 12 + leafCorrection;
  56972. for(i=0; i<nOld; i++){
  56973. MemPage *p = apOld[i];
  56974. szNew[i] = usableSpace - p->nFree;
  56975. if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  56976. for(j=0; j<p->nOverflow; j++){
  56977. szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
  56978. }
  56979. cntNew[i] = cntOld[i];
  56980. }
  56981. k = nOld;
  56982. for(i=0; i<k; i++){
  56983. int sz;
  56984. while( szNew[i]>usableSpace ){
  56985. if( i+1>=k ){
  56986. k = i+2;
  56987. if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  56988. szNew[k-1] = 0;
  56989. cntNew[k-1] = b.nCell;
  56990. }
  56991. sz = 2 + cachedCellSize(&b, cntNew[i]-1);
  56992. szNew[i] -= sz;
  56993. if( !leafData ){
  56994. if( cntNew[i]<b.nCell ){
  56995. sz = 2 + cachedCellSize(&b, cntNew[i]);
  56996. }else{
  56997. sz = 0;
  56998. }
  56999. }
  57000. szNew[i+1] += sz;
  57001. cntNew[i]--;
  57002. }
  57003. while( cntNew[i]<b.nCell ){
  57004. sz = 2 + cachedCellSize(&b, cntNew[i]);
  57005. if( szNew[i]+sz>usableSpace ) break;
  57006. szNew[i] += sz;
  57007. cntNew[i]++;
  57008. if( !leafData ){
  57009. if( cntNew[i]<b.nCell ){
  57010. sz = 2 + cachedCellSize(&b, cntNew[i]);
  57011. }else{
  57012. sz = 0;
  57013. }
  57014. }
  57015. szNew[i+1] -= sz;
  57016. }
  57017. if( cntNew[i]>=b.nCell ){
  57018. k = i+1;
  57019. }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
  57020. rc = SQLITE_CORRUPT_BKPT;
  57021. goto balance_cleanup;
  57022. }
  57023. }
  57024. /*
  57025. ** The packing computed by the previous block is biased toward the siblings
  57026. ** on the left side (siblings with smaller keys). The left siblings are
  57027. ** always nearly full, while the right-most sibling might be nearly empty.
  57028. ** The next block of code attempts to adjust the packing of siblings to
  57029. ** get a better balance.
  57030. **
  57031. ** This adjustment is more than an optimization. The packing above might
  57032. ** be so out of balance as to be illegal. For example, the right-most
  57033. ** sibling might be completely empty. This adjustment is not optional.
  57034. */
  57035. for(i=k-1; i>0; i--){
  57036. int szRight = szNew[i]; /* Size of sibling on the right */
  57037. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  57038. int r; /* Index of right-most cell in left sibling */
  57039. int d; /* Index of first cell to the left of right sibling */
  57040. r = cntNew[i-1] - 1;
  57041. d = r + 1 - leafData;
  57042. (void)cachedCellSize(&b, d);
  57043. do{
  57044. assert( d<nMaxCells );
  57045. assert( r<nMaxCells );
  57046. (void)cachedCellSize(&b, r);
  57047. if( szRight!=0
  57048. && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){
  57049. break;
  57050. }
  57051. szRight += b.szCell[d] + 2;
  57052. szLeft -= b.szCell[r] + 2;
  57053. cntNew[i-1] = r;
  57054. r--;
  57055. d--;
  57056. }while( r>=0 );
  57057. szNew[i] = szRight;
  57058. szNew[i-1] = szLeft;
  57059. if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
  57060. rc = SQLITE_CORRUPT_BKPT;
  57061. goto balance_cleanup;
  57062. }
  57063. }
  57064. /* Sanity check: For a non-corrupt database file one of the follwing
  57065. ** must be true:
  57066. ** (1) We found one or more cells (cntNew[0])>0), or
  57067. ** (2) pPage is a virtual root page. A virtual root page is when
  57068. ** the real root page is page 1 and we are the only child of
  57069. ** that page.
  57070. */
  57071. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
  57072. TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
  57073. apOld[0]->pgno, apOld[0]->nCell,
  57074. nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
  57075. nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
  57076. ));
  57077. /*
  57078. ** Allocate k new pages. Reuse old pages where possible.
  57079. */
  57080. pageFlags = apOld[0]->aData[0];
  57081. for(i=0; i<k; i++){
  57082. MemPage *pNew;
  57083. if( i<nOld ){
  57084. pNew = apNew[i] = apOld[i];
  57085. apOld[i] = 0;
  57086. rc = sqlite3PagerWrite(pNew->pDbPage);
  57087. nNew++;
  57088. if( rc ) goto balance_cleanup;
  57089. }else{
  57090. assert( i>0 );
  57091. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  57092. if( rc ) goto balance_cleanup;
  57093. zeroPage(pNew, pageFlags);
  57094. apNew[i] = pNew;
  57095. nNew++;
  57096. cntOld[i] = b.nCell;
  57097. /* Set the pointer-map entry for the new sibling page. */
  57098. if( ISAUTOVACUUM ){
  57099. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  57100. if( rc!=SQLITE_OK ){
  57101. goto balance_cleanup;
  57102. }
  57103. }
  57104. }
  57105. }
  57106. /*
  57107. ** Reassign page numbers so that the new pages are in ascending order.
  57108. ** This helps to keep entries in the disk file in order so that a scan
  57109. ** of the table is closer to a linear scan through the file. That in turn
  57110. ** helps the operating system to deliver pages from the disk more rapidly.
  57111. **
  57112. ** An O(n^2) insertion sort algorithm is used, but since n is never more
  57113. ** than (NB+2) (a small constant), that should not be a problem.
  57114. **
  57115. ** When NB==3, this one optimization makes the database about 25% faster
  57116. ** for large insertions and deletions.
  57117. */
  57118. for(i=0; i<nNew; i++){
  57119. aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
  57120. aPgFlags[i] = apNew[i]->pDbPage->flags;
  57121. for(j=0; j<i; j++){
  57122. if( aPgno[j]==aPgno[i] ){
  57123. /* This branch is taken if the set of sibling pages somehow contains
  57124. ** duplicate entries. This can happen if the database is corrupt.
  57125. ** It would be simpler to detect this as part of the loop below, but
  57126. ** we do the detection here in order to avoid populating the pager
  57127. ** cache with two separate objects associated with the same
  57128. ** page number. */
  57129. assert( CORRUPT_DB );
  57130. rc = SQLITE_CORRUPT_BKPT;
  57131. goto balance_cleanup;
  57132. }
  57133. }
  57134. }
  57135. for(i=0; i<nNew; i++){
  57136. int iBest = 0; /* aPgno[] index of page number to use */
  57137. for(j=1; j<nNew; j++){
  57138. if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
  57139. }
  57140. pgno = aPgOrder[iBest];
  57141. aPgOrder[iBest] = 0xffffffff;
  57142. if( iBest!=i ){
  57143. if( iBest>i ){
  57144. sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
  57145. }
  57146. sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
  57147. apNew[i]->pgno = pgno;
  57148. }
  57149. }
  57150. TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
  57151. "%d(%d nc=%d) %d(%d nc=%d)\n",
  57152. apNew[0]->pgno, szNew[0], cntNew[0],
  57153. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  57154. nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
  57155. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  57156. nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
  57157. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  57158. nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
  57159. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
  57160. nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
  57161. ));
  57162. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  57163. put4byte(pRight, apNew[nNew-1]->pgno);
  57164. /* If the sibling pages are not leaves, ensure that the right-child pointer
  57165. ** of the right-most new sibling page is set to the value that was
  57166. ** originally in the same field of the right-most old sibling page. */
  57167. if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
  57168. MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
  57169. memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
  57170. }
  57171. /* Make any required updates to pointer map entries associated with
  57172. ** cells stored on sibling pages following the balance operation. Pointer
  57173. ** map entries associated with divider cells are set by the insertCell()
  57174. ** routine. The associated pointer map entries are:
  57175. **
  57176. ** a) if the cell contains a reference to an overflow chain, the
  57177. ** entry associated with the first page in the overflow chain, and
  57178. **
  57179. ** b) if the sibling pages are not leaves, the child page associated
  57180. ** with the cell.
  57181. **
  57182. ** If the sibling pages are not leaves, then the pointer map entry
  57183. ** associated with the right-child of each sibling may also need to be
  57184. ** updated. This happens below, after the sibling pages have been
  57185. ** populated, not here.
  57186. */
  57187. if( ISAUTOVACUUM ){
  57188. MemPage *pNew = apNew[0];
  57189. u8 *aOld = pNew->aData;
  57190. int cntOldNext = pNew->nCell + pNew->nOverflow;
  57191. int usableSize = pBt->usableSize;
  57192. int iNew = 0;
  57193. int iOld = 0;
  57194. for(i=0; i<b.nCell; i++){
  57195. u8 *pCell = b.apCell[i];
  57196. if( i==cntOldNext ){
  57197. MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
  57198. cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
  57199. aOld = pOld->aData;
  57200. }
  57201. if( i==cntNew[iNew] ){
  57202. pNew = apNew[++iNew];
  57203. if( !leafData ) continue;
  57204. }
  57205. /* Cell pCell is destined for new sibling page pNew. Originally, it
  57206. ** was either part of sibling page iOld (possibly an overflow cell),
  57207. ** or else the divider cell to the left of sibling page iOld. So,
  57208. ** if sibling page iOld had the same page number as pNew, and if
  57209. ** pCell really was a part of sibling page iOld (not a divider or
  57210. ** overflow cell), we can skip updating the pointer map entries. */
  57211. if( iOld>=nNew
  57212. || pNew->pgno!=aPgno[iOld]
  57213. || pCell<aOld
  57214. || pCell>=&aOld[usableSize]
  57215. ){
  57216. if( !leafCorrection ){
  57217. ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
  57218. }
  57219. if( cachedCellSize(&b,i)>pNew->minLocal ){
  57220. ptrmapPutOvflPtr(pNew, pCell, &rc);
  57221. }
  57222. if( rc ) goto balance_cleanup;
  57223. }
  57224. }
  57225. }
  57226. /* Insert new divider cells into pParent. */
  57227. for(i=0; i<nNew-1; i++){
  57228. u8 *pCell;
  57229. u8 *pTemp;
  57230. int sz;
  57231. MemPage *pNew = apNew[i];
  57232. j = cntNew[i];
  57233. assert( j<nMaxCells );
  57234. assert( b.apCell[j]!=0 );
  57235. pCell = b.apCell[j];
  57236. sz = b.szCell[j] + leafCorrection;
  57237. pTemp = &aOvflSpace[iOvflSpace];
  57238. if( !pNew->leaf ){
  57239. memcpy(&pNew->aData[8], pCell, 4);
  57240. }else if( leafData ){
  57241. /* If the tree is a leaf-data tree, and the siblings are leaves,
  57242. ** then there is no divider cell in b.apCell[]. Instead, the divider
  57243. ** cell consists of the integer key for the right-most cell of
  57244. ** the sibling-page assembled above only.
  57245. */
  57246. CellInfo info;
  57247. j--;
  57248. pNew->xParseCell(pNew, b.apCell[j], &info);
  57249. pCell = pTemp;
  57250. sz = 4 + putVarint(&pCell[4], info.nKey);
  57251. pTemp = 0;
  57252. }else{
  57253. pCell -= 4;
  57254. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  57255. ** previously stored on a leaf node, and its reported size was 4
  57256. ** bytes, then it may actually be smaller than this
  57257. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  57258. ** any cell). But it is important to pass the correct size to
  57259. ** insertCell(), so reparse the cell now.
  57260. **
  57261. ** Note that this can never happen in an SQLite data file, as all
  57262. ** cells are at least 4 bytes. It only happens in b-trees used
  57263. ** to evaluate "IN (SELECT ...)" and similar clauses.
  57264. */
  57265. if( b.szCell[j]==4 ){
  57266. assert(leafCorrection==4);
  57267. sz = pParent->xCellSize(pParent, pCell);
  57268. }
  57269. }
  57270. iOvflSpace += sz;
  57271. assert( sz<=pBt->maxLocal+23 );
  57272. assert( iOvflSpace <= (int)pBt->pageSize );
  57273. insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
  57274. if( rc!=SQLITE_OK ) goto balance_cleanup;
  57275. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  57276. }
  57277. /* Now update the actual sibling pages. The order in which they are updated
  57278. ** is important, as this code needs to avoid disrupting any page from which
  57279. ** cells may still to be read. In practice, this means:
  57280. **
  57281. ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
  57282. ** then it is not safe to update page apNew[iPg] until after
  57283. ** the left-hand sibling apNew[iPg-1] has been updated.
  57284. **
  57285. ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
  57286. ** then it is not safe to update page apNew[iPg] until after
  57287. ** the right-hand sibling apNew[iPg+1] has been updated.
  57288. **
  57289. ** If neither of the above apply, the page is safe to update.
  57290. **
  57291. ** The iPg value in the following loop starts at nNew-1 goes down
  57292. ** to 0, then back up to nNew-1 again, thus making two passes over
  57293. ** the pages. On the initial downward pass, only condition (1) above
  57294. ** needs to be tested because (2) will always be true from the previous
  57295. ** step. On the upward pass, both conditions are always true, so the
  57296. ** upwards pass simply processes pages that were missed on the downward
  57297. ** pass.
  57298. */
  57299. for(i=1-nNew; i<nNew; i++){
  57300. int iPg = i<0 ? -i : i;
  57301. assert( iPg>=0 && iPg<nNew );
  57302. if( abDone[iPg] ) continue; /* Skip pages already processed */
  57303. if( i>=0 /* On the upwards pass, or... */
  57304. || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
  57305. ){
  57306. int iNew;
  57307. int iOld;
  57308. int nNewCell;
  57309. /* Verify condition (1): If cells are moving left, update iPg
  57310. ** only after iPg-1 has already been updated. */
  57311. assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
  57312. /* Verify condition (2): If cells are moving right, update iPg
  57313. ** only after iPg+1 has already been updated. */
  57314. assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
  57315. if( iPg==0 ){
  57316. iNew = iOld = 0;
  57317. nNewCell = cntNew[0];
  57318. }else{
  57319. iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
  57320. iNew = cntNew[iPg-1] + !leafData;
  57321. nNewCell = cntNew[iPg] - iNew;
  57322. }
  57323. rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
  57324. if( rc ) goto balance_cleanup;
  57325. abDone[iPg]++;
  57326. apNew[iPg]->nFree = usableSpace-szNew[iPg];
  57327. assert( apNew[iPg]->nOverflow==0 );
  57328. assert( apNew[iPg]->nCell==nNewCell );
  57329. }
  57330. }
  57331. /* All pages have been processed exactly once */
  57332. assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
  57333. assert( nOld>0 );
  57334. assert( nNew>0 );
  57335. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  57336. /* The root page of the b-tree now contains no cells. The only sibling
  57337. ** page is the right-child of the parent. Copy the contents of the
  57338. ** child page into the parent, decreasing the overall height of the
  57339. ** b-tree structure by one. This is described as the "balance-shallower"
  57340. ** sub-algorithm in some documentation.
  57341. **
  57342. ** If this is an auto-vacuum database, the call to copyNodeContent()
  57343. ** sets all pointer-map entries corresponding to database image pages
  57344. ** for which the pointer is stored within the content being copied.
  57345. **
  57346. ** It is critical that the child page be defragmented before being
  57347. ** copied into the parent, because if the parent is page 1 then it will
  57348. ** by smaller than the child due to the database header, and so all the
  57349. ** free space needs to be up front.
  57350. */
  57351. assert( nNew==1 );
  57352. rc = defragmentPage(apNew[0]);
  57353. testcase( rc!=SQLITE_OK );
  57354. assert( apNew[0]->nFree ==
  57355. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  57356. || rc!=SQLITE_OK
  57357. );
  57358. copyNodeContent(apNew[0], pParent, &rc);
  57359. freePage(apNew[0], &rc);
  57360. }else if( ISAUTOVACUUM && !leafCorrection ){
  57361. /* Fix the pointer map entries associated with the right-child of each
  57362. ** sibling page. All other pointer map entries have already been taken
  57363. ** care of. */
  57364. for(i=0; i<nNew; i++){
  57365. u32 key = get4byte(&apNew[i]->aData[8]);
  57366. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  57367. }
  57368. }
  57369. assert( pParent->isInit );
  57370. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  57371. nOld, nNew, b.nCell));
  57372. /* Free any old pages that were not reused as new pages.
  57373. */
  57374. for(i=nNew; i<nOld; i++){
  57375. freePage(apOld[i], &rc);
  57376. }
  57377. #if 0
  57378. if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
  57379. /* The ptrmapCheckPages() contains assert() statements that verify that
  57380. ** all pointer map pages are set correctly. This is helpful while
  57381. ** debugging. This is usually disabled because a corrupt database may
  57382. ** cause an assert() statement to fail. */
  57383. ptrmapCheckPages(apNew, nNew);
  57384. ptrmapCheckPages(&pParent, 1);
  57385. }
  57386. #endif
  57387. /*
  57388. ** Cleanup before returning.
  57389. */
  57390. balance_cleanup:
  57391. sqlite3ScratchFree(b.apCell);
  57392. for(i=0; i<nOld; i++){
  57393. releasePage(apOld[i]);
  57394. }
  57395. for(i=0; i<nNew; i++){
  57396. releasePage(apNew[i]);
  57397. }
  57398. return rc;
  57399. }
  57400. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  57401. #pragma optimize("", on)
  57402. #endif
  57403. /*
  57404. ** This function is called when the root page of a b-tree structure is
  57405. ** overfull (has one or more overflow pages).
  57406. **
  57407. ** A new child page is allocated and the contents of the current root
  57408. ** page, including overflow cells, are copied into the child. The root
  57409. ** page is then overwritten to make it an empty page with the right-child
  57410. ** pointer pointing to the new page.
  57411. **
  57412. ** Before returning, all pointer-map entries corresponding to pages
  57413. ** that the new child-page now contains pointers to are updated. The
  57414. ** entry corresponding to the new right-child pointer of the root
  57415. ** page is also updated.
  57416. **
  57417. ** If successful, *ppChild is set to contain a reference to the child
  57418. ** page and SQLITE_OK is returned. In this case the caller is required
  57419. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  57420. ** an error code is returned and *ppChild is set to 0.
  57421. */
  57422. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  57423. int rc; /* Return value from subprocedures */
  57424. MemPage *pChild = 0; /* Pointer to a new child page */
  57425. Pgno pgnoChild = 0; /* Page number of the new child page */
  57426. BtShared *pBt = pRoot->pBt; /* The BTree */
  57427. assert( pRoot->nOverflow>0 );
  57428. assert( sqlite3_mutex_held(pBt->mutex) );
  57429. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  57430. ** page that will become the new right-child of pPage. Copy the contents
  57431. ** of the node stored on pRoot into the new child page.
  57432. */
  57433. rc = sqlite3PagerWrite(pRoot->pDbPage);
  57434. if( rc==SQLITE_OK ){
  57435. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  57436. copyNodeContent(pRoot, pChild, &rc);
  57437. if( ISAUTOVACUUM ){
  57438. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  57439. }
  57440. }
  57441. if( rc ){
  57442. *ppChild = 0;
  57443. releasePage(pChild);
  57444. return rc;
  57445. }
  57446. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  57447. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  57448. assert( pChild->nCell==pRoot->nCell );
  57449. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  57450. /* Copy the overflow cells from pRoot to pChild */
  57451. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  57452. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  57453. memcpy(pChild->apOvfl, pRoot->apOvfl,
  57454. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  57455. pChild->nOverflow = pRoot->nOverflow;
  57456. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  57457. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  57458. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  57459. *ppChild = pChild;
  57460. return SQLITE_OK;
  57461. }
  57462. /*
  57463. ** The page that pCur currently points to has just been modified in
  57464. ** some way. This function figures out if this modification means the
  57465. ** tree needs to be balanced, and if so calls the appropriate balancing
  57466. ** routine. Balancing routines are:
  57467. **
  57468. ** balance_quick()
  57469. ** balance_deeper()
  57470. ** balance_nonroot()
  57471. */
  57472. static int balance(BtCursor *pCur){
  57473. int rc = SQLITE_OK;
  57474. const int nMin = pCur->pBt->usableSize * 2 / 3;
  57475. u8 aBalanceQuickSpace[13];
  57476. u8 *pFree = 0;
  57477. TESTONLY( int balance_quick_called = 0 );
  57478. TESTONLY( int balance_deeper_called = 0 );
  57479. do {
  57480. int iPage = pCur->iPage;
  57481. MemPage *pPage = pCur->apPage[iPage];
  57482. if( iPage==0 ){
  57483. if( pPage->nOverflow ){
  57484. /* The root page of the b-tree is overfull. In this case call the
  57485. ** balance_deeper() function to create a new child for the root-page
  57486. ** and copy the current contents of the root-page to it. The
  57487. ** next iteration of the do-loop will balance the child page.
  57488. */
  57489. assert( (balance_deeper_called++)==0 );
  57490. rc = balance_deeper(pPage, &pCur->apPage[1]);
  57491. if( rc==SQLITE_OK ){
  57492. pCur->iPage = 1;
  57493. pCur->aiIdx[0] = 0;
  57494. pCur->aiIdx[1] = 0;
  57495. assert( pCur->apPage[1]->nOverflow );
  57496. }
  57497. }else{
  57498. break;
  57499. }
  57500. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  57501. break;
  57502. }else{
  57503. MemPage * const pParent = pCur->apPage[iPage-1];
  57504. int const iIdx = pCur->aiIdx[iPage-1];
  57505. rc = sqlite3PagerWrite(pParent->pDbPage);
  57506. if( rc==SQLITE_OK ){
  57507. #ifndef SQLITE_OMIT_QUICKBALANCE
  57508. if( pPage->intKeyLeaf
  57509. && pPage->nOverflow==1
  57510. && pPage->aiOvfl[0]==pPage->nCell
  57511. && pParent->pgno!=1
  57512. && pParent->nCell==iIdx
  57513. ){
  57514. /* Call balance_quick() to create a new sibling of pPage on which
  57515. ** to store the overflow cell. balance_quick() inserts a new cell
  57516. ** into pParent, which may cause pParent overflow. If this
  57517. ** happens, the next iteration of the do-loop will balance pParent
  57518. ** use either balance_nonroot() or balance_deeper(). Until this
  57519. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  57520. ** buffer.
  57521. **
  57522. ** The purpose of the following assert() is to check that only a
  57523. ** single call to balance_quick() is made for each call to this
  57524. ** function. If this were not verified, a subtle bug involving reuse
  57525. ** of the aBalanceQuickSpace[] might sneak in.
  57526. */
  57527. assert( (balance_quick_called++)==0 );
  57528. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  57529. }else
  57530. #endif
  57531. {
  57532. /* In this case, call balance_nonroot() to redistribute cells
  57533. ** between pPage and up to 2 of its sibling pages. This involves
  57534. ** modifying the contents of pParent, which may cause pParent to
  57535. ** become overfull or underfull. The next iteration of the do-loop
  57536. ** will balance the parent page to correct this.
  57537. **
  57538. ** If the parent page becomes overfull, the overflow cell or cells
  57539. ** are stored in the pSpace buffer allocated immediately below.
  57540. ** A subsequent iteration of the do-loop will deal with this by
  57541. ** calling balance_nonroot() (balance_deeper() may be called first,
  57542. ** but it doesn't deal with overflow cells - just moves them to a
  57543. ** different page). Once this subsequent call to balance_nonroot()
  57544. ** has completed, it is safe to release the pSpace buffer used by
  57545. ** the previous call, as the overflow cell data will have been
  57546. ** copied either into the body of a database page or into the new
  57547. ** pSpace buffer passed to the latter call to balance_nonroot().
  57548. */
  57549. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  57550. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
  57551. pCur->hints&BTREE_BULKLOAD);
  57552. if( pFree ){
  57553. /* If pFree is not NULL, it points to the pSpace buffer used
  57554. ** by a previous call to balance_nonroot(). Its contents are
  57555. ** now stored either on real database pages or within the
  57556. ** new pSpace buffer, so it may be safely freed here. */
  57557. sqlite3PageFree(pFree);
  57558. }
  57559. /* The pSpace buffer will be freed after the next call to
  57560. ** balance_nonroot(), or just before this function returns, whichever
  57561. ** comes first. */
  57562. pFree = pSpace;
  57563. }
  57564. }
  57565. pPage->nOverflow = 0;
  57566. /* The next iteration of the do-loop balances the parent page. */
  57567. releasePage(pPage);
  57568. pCur->iPage--;
  57569. assert( pCur->iPage>=0 );
  57570. }
  57571. }while( rc==SQLITE_OK );
  57572. if( pFree ){
  57573. sqlite3PageFree(pFree);
  57574. }
  57575. return rc;
  57576. }
  57577. /*
  57578. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  57579. ** and the data is given by (pData,nData). The cursor is used only to
  57580. ** define what table the record should be inserted into. The cursor
  57581. ** is left pointing at a random location.
  57582. **
  57583. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  57584. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  57585. **
  57586. ** If the seekResult parameter is non-zero, then a successful call to
  57587. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  57588. ** been performed. seekResult is the search result returned (a negative
  57589. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  57590. ** a positive value if pCur points at an entry that is larger than
  57591. ** (pKey, nKey)).
  57592. **
  57593. ** If the seekResult parameter is non-zero, then the caller guarantees that
  57594. ** cursor pCur is pointing at the existing copy of a row that is to be
  57595. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  57596. ** point to any entry or to no entry at all and so this function has to seek
  57597. ** the cursor before the new key can be inserted.
  57598. */
  57599. SQLITE_PRIVATE int sqlite3BtreeInsert(
  57600. BtCursor *pCur, /* Insert data into the table of this cursor */
  57601. const void *pKey, i64 nKey, /* The key of the new record */
  57602. const void *pData, int nData, /* The data of the new record */
  57603. int nZero, /* Number of extra 0 bytes to append to data */
  57604. int appendBias, /* True if this is likely an append */
  57605. int seekResult /* Result of prior MovetoUnpacked() call */
  57606. ){
  57607. int rc;
  57608. int loc = seekResult; /* -1: before desired location +1: after */
  57609. int szNew = 0;
  57610. int idx;
  57611. MemPage *pPage;
  57612. Btree *p = pCur->pBtree;
  57613. BtShared *pBt = p->pBt;
  57614. unsigned char *oldCell;
  57615. unsigned char *newCell = 0;
  57616. if( pCur->eState==CURSOR_FAULT ){
  57617. assert( pCur->skipNext!=SQLITE_OK );
  57618. return pCur->skipNext;
  57619. }
  57620. assert( cursorHoldsMutex(pCur) );
  57621. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  57622. && pBt->inTransaction==TRANS_WRITE
  57623. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  57624. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  57625. /* Assert that the caller has been consistent. If this cursor was opened
  57626. ** expecting an index b-tree, then the caller should be inserting blob
  57627. ** keys with no associated data. If the cursor was opened expecting an
  57628. ** intkey table, the caller should be inserting integer keys with a
  57629. ** blob of associated data. */
  57630. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  57631. /* Save the positions of any other cursors open on this table.
  57632. **
  57633. ** In some cases, the call to btreeMoveto() below is a no-op. For
  57634. ** example, when inserting data into a table with auto-generated integer
  57635. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  57636. ** integer key to use. It then calls this function to actually insert the
  57637. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  57638. ** that the cursor is already where it needs to be and returns without
  57639. ** doing any work. To avoid thwarting these optimizations, it is important
  57640. ** not to clear the cursor here.
  57641. */
  57642. if( pCur->curFlags & BTCF_Multiple ){
  57643. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  57644. if( rc ) return rc;
  57645. }
  57646. if( pCur->pKeyInfo==0 ){
  57647. assert( pKey==0 );
  57648. /* If this is an insert into a table b-tree, invalidate any incrblob
  57649. ** cursors open on the row being replaced */
  57650. invalidateIncrblobCursors(p, nKey, 0);
  57651. /* If the cursor is currently on the last row and we are appending a
  57652. ** new row onto the end, set the "loc" to avoid an unnecessary
  57653. ** btreeMoveto() call */
  57654. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
  57655. && pCur->info.nKey==nKey-1 ){
  57656. loc = -1;
  57657. }else if( loc==0 ){
  57658. rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc);
  57659. if( rc ) return rc;
  57660. }
  57661. }else if( loc==0 ){
  57662. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  57663. if( rc ) return rc;
  57664. }
  57665. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  57666. pPage = pCur->apPage[pCur->iPage];
  57667. assert( pPage->intKey || nKey>=0 );
  57668. assert( pPage->leaf || !pPage->intKey );
  57669. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  57670. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  57671. loc==0 ? "overwrite" : "new entry"));
  57672. assert( pPage->isInit );
  57673. newCell = pBt->pTmpSpace;
  57674. assert( newCell!=0 );
  57675. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  57676. if( rc ) goto end_insert;
  57677. assert( szNew==pPage->xCellSize(pPage, newCell) );
  57678. assert( szNew <= MX_CELL_SIZE(pBt) );
  57679. idx = pCur->aiIdx[pCur->iPage];
  57680. if( loc==0 ){
  57681. u16 szOld;
  57682. assert( idx<pPage->nCell );
  57683. rc = sqlite3PagerWrite(pPage->pDbPage);
  57684. if( rc ){
  57685. goto end_insert;
  57686. }
  57687. oldCell = findCell(pPage, idx);
  57688. if( !pPage->leaf ){
  57689. memcpy(newCell, oldCell, 4);
  57690. }
  57691. rc = clearCell(pPage, oldCell, &szOld);
  57692. dropCell(pPage, idx, szOld, &rc);
  57693. if( rc ) goto end_insert;
  57694. }else if( loc<0 && pPage->nCell>0 ){
  57695. assert( pPage->leaf );
  57696. idx = ++pCur->aiIdx[pCur->iPage];
  57697. }else{
  57698. assert( pPage->leaf );
  57699. }
  57700. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  57701. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  57702. /* If no error has occurred and pPage has an overflow cell, call balance()
  57703. ** to redistribute the cells within the tree. Since balance() may move
  57704. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  57705. ** variables.
  57706. **
  57707. ** Previous versions of SQLite called moveToRoot() to move the cursor
  57708. ** back to the root page as balance() used to invalidate the contents
  57709. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  57710. ** set the cursor state to "invalid". This makes common insert operations
  57711. ** slightly faster.
  57712. **
  57713. ** There is a subtle but important optimization here too. When inserting
  57714. ** multiple records into an intkey b-tree using a single cursor (as can
  57715. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  57716. ** is advantageous to leave the cursor pointing to the last entry in
  57717. ** the b-tree if possible. If the cursor is left pointing to the last
  57718. ** entry in the table, and the next row inserted has an integer key
  57719. ** larger than the largest existing key, it is possible to insert the
  57720. ** row without seeking the cursor. This can be a big performance boost.
  57721. */
  57722. pCur->info.nSize = 0;
  57723. if( rc==SQLITE_OK && pPage->nOverflow ){
  57724. pCur->curFlags &= ~(BTCF_ValidNKey);
  57725. rc = balance(pCur);
  57726. /* Must make sure nOverflow is reset to zero even if the balance()
  57727. ** fails. Internal data structure corruption will result otherwise.
  57728. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  57729. ** from trying to save the current position of the cursor. */
  57730. pCur->apPage[pCur->iPage]->nOverflow = 0;
  57731. pCur->eState = CURSOR_INVALID;
  57732. }
  57733. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  57734. end_insert:
  57735. return rc;
  57736. }
  57737. /*
  57738. ** Delete the entry that the cursor is pointing to. The cursor
  57739. ** is left pointing at an arbitrary location.
  57740. */
  57741. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  57742. Btree *p = pCur->pBtree;
  57743. BtShared *pBt = p->pBt;
  57744. int rc; /* Return code */
  57745. MemPage *pPage; /* Page to delete cell from */
  57746. unsigned char *pCell; /* Pointer to cell to delete */
  57747. int iCellIdx; /* Index of cell to delete */
  57748. int iCellDepth; /* Depth of node containing pCell */
  57749. u16 szCell; /* Size of the cell being deleted */
  57750. assert( cursorHoldsMutex(pCur) );
  57751. assert( pBt->inTransaction==TRANS_WRITE );
  57752. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  57753. assert( pCur->curFlags & BTCF_WriteFlag );
  57754. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  57755. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  57756. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  57757. assert( pCur->eState==CURSOR_VALID );
  57758. iCellDepth = pCur->iPage;
  57759. iCellIdx = pCur->aiIdx[iCellDepth];
  57760. pPage = pCur->apPage[iCellDepth];
  57761. pCell = findCell(pPage, iCellIdx);
  57762. /* If the page containing the entry to delete is not a leaf page, move
  57763. ** the cursor to the largest entry in the tree that is smaller than
  57764. ** the entry being deleted. This cell will replace the cell being deleted
  57765. ** from the internal node. The 'previous' entry is used for this instead
  57766. ** of the 'next' entry, as the previous entry is always a part of the
  57767. ** sub-tree headed by the child page of the cell being deleted. This makes
  57768. ** balancing the tree following the delete operation easier. */
  57769. if( !pPage->leaf ){
  57770. int notUsed = 0;
  57771. rc = sqlite3BtreePrevious(pCur, &notUsed);
  57772. if( rc ) return rc;
  57773. }
  57774. /* Save the positions of any other cursors open on this table before
  57775. ** making any modifications. Make the page containing the entry to be
  57776. ** deleted writable. Then free any overflow pages associated with the
  57777. ** entry and finally remove the cell itself from within the page.
  57778. */
  57779. if( pCur->curFlags & BTCF_Multiple ){
  57780. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  57781. if( rc ) return rc;
  57782. }
  57783. /* If this is a delete operation to remove a row from a table b-tree,
  57784. ** invalidate any incrblob cursors open on the row being deleted. */
  57785. if( pCur->pKeyInfo==0 ){
  57786. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  57787. }
  57788. rc = sqlite3PagerWrite(pPage->pDbPage);
  57789. if( rc ) return rc;
  57790. rc = clearCell(pPage, pCell, &szCell);
  57791. dropCell(pPage, iCellIdx, szCell, &rc);
  57792. if( rc ) return rc;
  57793. /* If the cell deleted was not located on a leaf page, then the cursor
  57794. ** is currently pointing to the largest entry in the sub-tree headed
  57795. ** by the child-page of the cell that was just deleted from an internal
  57796. ** node. The cell from the leaf node needs to be moved to the internal
  57797. ** node to replace the deleted cell. */
  57798. if( !pPage->leaf ){
  57799. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  57800. int nCell;
  57801. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  57802. unsigned char *pTmp;
  57803. pCell = findCell(pLeaf, pLeaf->nCell-1);
  57804. if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
  57805. nCell = pLeaf->xCellSize(pLeaf, pCell);
  57806. assert( MX_CELL_SIZE(pBt) >= nCell );
  57807. pTmp = pBt->pTmpSpace;
  57808. assert( pTmp!=0 );
  57809. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  57810. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  57811. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  57812. if( rc ) return rc;
  57813. }
  57814. /* Balance the tree. If the entry deleted was located on a leaf page,
  57815. ** then the cursor still points to that page. In this case the first
  57816. ** call to balance() repairs the tree, and the if(...) condition is
  57817. ** never true.
  57818. **
  57819. ** Otherwise, if the entry deleted was on an internal node page, then
  57820. ** pCur is pointing to the leaf page from which a cell was removed to
  57821. ** replace the cell deleted from the internal node. This is slightly
  57822. ** tricky as the leaf node may be underfull, and the internal node may
  57823. ** be either under or overfull. In this case run the balancing algorithm
  57824. ** on the leaf node first. If the balance proceeds far enough up the
  57825. ** tree that we can be sure that any problem in the internal node has
  57826. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  57827. ** walk the cursor up the tree to the internal node and balance it as
  57828. ** well. */
  57829. rc = balance(pCur);
  57830. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  57831. while( pCur->iPage>iCellDepth ){
  57832. releasePage(pCur->apPage[pCur->iPage--]);
  57833. }
  57834. rc = balance(pCur);
  57835. }
  57836. if( rc==SQLITE_OK ){
  57837. moveToRoot(pCur);
  57838. }
  57839. return rc;
  57840. }
  57841. /*
  57842. ** Create a new BTree table. Write into *piTable the page
  57843. ** number for the root page of the new table.
  57844. **
  57845. ** The type of type is determined by the flags parameter. Only the
  57846. ** following values of flags are currently in use. Other values for
  57847. ** flags might not work:
  57848. **
  57849. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  57850. ** BTREE_ZERODATA Used for SQL indices
  57851. */
  57852. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  57853. BtShared *pBt = p->pBt;
  57854. MemPage *pRoot;
  57855. Pgno pgnoRoot;
  57856. int rc;
  57857. int ptfFlags; /* Page-type flage for the root page of new table */
  57858. assert( sqlite3BtreeHoldsMutex(p) );
  57859. assert( pBt->inTransaction==TRANS_WRITE );
  57860. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  57861. #ifdef SQLITE_OMIT_AUTOVACUUM
  57862. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  57863. if( rc ){
  57864. return rc;
  57865. }
  57866. #else
  57867. if( pBt->autoVacuum ){
  57868. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  57869. MemPage *pPageMove; /* The page to move to. */
  57870. /* Creating a new table may probably require moving an existing database
  57871. ** to make room for the new tables root page. In case this page turns
  57872. ** out to be an overflow page, delete all overflow page-map caches
  57873. ** held by open cursors.
  57874. */
  57875. invalidateAllOverflowCache(pBt);
  57876. /* Read the value of meta[3] from the database to determine where the
  57877. ** root page of the new table should go. meta[3] is the largest root-page
  57878. ** created so far, so the new root-page is (meta[3]+1).
  57879. */
  57880. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  57881. pgnoRoot++;
  57882. /* The new root-page may not be allocated on a pointer-map page, or the
  57883. ** PENDING_BYTE page.
  57884. */
  57885. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  57886. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  57887. pgnoRoot++;
  57888. }
  57889. assert( pgnoRoot>=3 || CORRUPT_DB );
  57890. testcase( pgnoRoot<3 );
  57891. /* Allocate a page. The page that currently resides at pgnoRoot will
  57892. ** be moved to the allocated page (unless the allocated page happens
  57893. ** to reside at pgnoRoot).
  57894. */
  57895. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  57896. if( rc!=SQLITE_OK ){
  57897. return rc;
  57898. }
  57899. if( pgnoMove!=pgnoRoot ){
  57900. /* pgnoRoot is the page that will be used for the root-page of
  57901. ** the new table (assuming an error did not occur). But we were
  57902. ** allocated pgnoMove. If required (i.e. if it was not allocated
  57903. ** by extending the file), the current page at position pgnoMove
  57904. ** is already journaled.
  57905. */
  57906. u8 eType = 0;
  57907. Pgno iPtrPage = 0;
  57908. /* Save the positions of any open cursors. This is required in
  57909. ** case they are holding a reference to an xFetch reference
  57910. ** corresponding to page pgnoRoot. */
  57911. rc = saveAllCursors(pBt, 0, 0);
  57912. releasePage(pPageMove);
  57913. if( rc!=SQLITE_OK ){
  57914. return rc;
  57915. }
  57916. /* Move the page currently at pgnoRoot to pgnoMove. */
  57917. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  57918. if( rc!=SQLITE_OK ){
  57919. return rc;
  57920. }
  57921. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  57922. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  57923. rc = SQLITE_CORRUPT_BKPT;
  57924. }
  57925. if( rc!=SQLITE_OK ){
  57926. releasePage(pRoot);
  57927. return rc;
  57928. }
  57929. assert( eType!=PTRMAP_ROOTPAGE );
  57930. assert( eType!=PTRMAP_FREEPAGE );
  57931. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  57932. releasePage(pRoot);
  57933. /* Obtain the page at pgnoRoot */
  57934. if( rc!=SQLITE_OK ){
  57935. return rc;
  57936. }
  57937. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  57938. if( rc!=SQLITE_OK ){
  57939. return rc;
  57940. }
  57941. rc = sqlite3PagerWrite(pRoot->pDbPage);
  57942. if( rc!=SQLITE_OK ){
  57943. releasePage(pRoot);
  57944. return rc;
  57945. }
  57946. }else{
  57947. pRoot = pPageMove;
  57948. }
  57949. /* Update the pointer-map and meta-data with the new root-page number. */
  57950. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  57951. if( rc ){
  57952. releasePage(pRoot);
  57953. return rc;
  57954. }
  57955. /* When the new root page was allocated, page 1 was made writable in
  57956. ** order either to increase the database filesize, or to decrement the
  57957. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  57958. */
  57959. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  57960. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  57961. if( NEVER(rc) ){
  57962. releasePage(pRoot);
  57963. return rc;
  57964. }
  57965. }else{
  57966. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  57967. if( rc ) return rc;
  57968. }
  57969. #endif
  57970. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  57971. if( createTabFlags & BTREE_INTKEY ){
  57972. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  57973. }else{
  57974. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  57975. }
  57976. zeroPage(pRoot, ptfFlags);
  57977. sqlite3PagerUnref(pRoot->pDbPage);
  57978. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  57979. *piTable = (int)pgnoRoot;
  57980. return SQLITE_OK;
  57981. }
  57982. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  57983. int rc;
  57984. sqlite3BtreeEnter(p);
  57985. rc = btreeCreateTable(p, piTable, flags);
  57986. sqlite3BtreeLeave(p);
  57987. return rc;
  57988. }
  57989. /*
  57990. ** Erase the given database page and all its children. Return
  57991. ** the page to the freelist.
  57992. */
  57993. static int clearDatabasePage(
  57994. BtShared *pBt, /* The BTree that contains the table */
  57995. Pgno pgno, /* Page number to clear */
  57996. int freePageFlag, /* Deallocate page if true */
  57997. int *pnChange /* Add number of Cells freed to this counter */
  57998. ){
  57999. MemPage *pPage;
  58000. int rc;
  58001. unsigned char *pCell;
  58002. int i;
  58003. int hdr;
  58004. u16 szCell;
  58005. assert( sqlite3_mutex_held(pBt->mutex) );
  58006. if( pgno>btreePagecount(pBt) ){
  58007. return SQLITE_CORRUPT_BKPT;
  58008. }
  58009. rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
  58010. if( rc ) return rc;
  58011. if( pPage->bBusy ){
  58012. rc = SQLITE_CORRUPT_BKPT;
  58013. goto cleardatabasepage_out;
  58014. }
  58015. pPage->bBusy = 1;
  58016. hdr = pPage->hdrOffset;
  58017. for(i=0; i<pPage->nCell; i++){
  58018. pCell = findCell(pPage, i);
  58019. if( !pPage->leaf ){
  58020. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  58021. if( rc ) goto cleardatabasepage_out;
  58022. }
  58023. rc = clearCell(pPage, pCell, &szCell);
  58024. if( rc ) goto cleardatabasepage_out;
  58025. }
  58026. if( !pPage->leaf ){
  58027. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  58028. if( rc ) goto cleardatabasepage_out;
  58029. }else if( pnChange ){
  58030. assert( pPage->intKey || CORRUPT_DB );
  58031. testcase( !pPage->intKey );
  58032. *pnChange += pPage->nCell;
  58033. }
  58034. if( freePageFlag ){
  58035. freePage(pPage, &rc);
  58036. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  58037. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  58038. }
  58039. cleardatabasepage_out:
  58040. pPage->bBusy = 0;
  58041. releasePage(pPage);
  58042. return rc;
  58043. }
  58044. /*
  58045. ** Delete all information from a single table in the database. iTable is
  58046. ** the page number of the root of the table. After this routine returns,
  58047. ** the root page is empty, but still exists.
  58048. **
  58049. ** This routine will fail with SQLITE_LOCKED if there are any open
  58050. ** read cursors on the table. Open write cursors are moved to the
  58051. ** root of the table.
  58052. **
  58053. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  58054. ** integer value pointed to by pnChange is incremented by the number of
  58055. ** entries in the table.
  58056. */
  58057. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  58058. int rc;
  58059. BtShared *pBt = p->pBt;
  58060. sqlite3BtreeEnter(p);
  58061. assert( p->inTrans==TRANS_WRITE );
  58062. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  58063. if( SQLITE_OK==rc ){
  58064. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  58065. ** is the root of a table b-tree - if it is not, the following call is
  58066. ** a no-op). */
  58067. invalidateIncrblobCursors(p, 0, 1);
  58068. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  58069. }
  58070. sqlite3BtreeLeave(p);
  58071. return rc;
  58072. }
  58073. /*
  58074. ** Delete all information from the single table that pCur is open on.
  58075. **
  58076. ** This routine only work for pCur on an ephemeral table.
  58077. */
  58078. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  58079. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  58080. }
  58081. /*
  58082. ** Erase all information in a table and add the root of the table to
  58083. ** the freelist. Except, the root of the principle table (the one on
  58084. ** page 1) is never added to the freelist.
  58085. **
  58086. ** This routine will fail with SQLITE_LOCKED if there are any open
  58087. ** cursors on the table.
  58088. **
  58089. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  58090. ** root page in the database file, then the last root page
  58091. ** in the database file is moved into the slot formerly occupied by
  58092. ** iTable and that last slot formerly occupied by the last root page
  58093. ** is added to the freelist instead of iTable. In this say, all
  58094. ** root pages are kept at the beginning of the database file, which
  58095. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  58096. ** page number that used to be the last root page in the file before
  58097. ** the move. If no page gets moved, *piMoved is set to 0.
  58098. ** The last root page is recorded in meta[3] and the value of
  58099. ** meta[3] is updated by this procedure.
  58100. */
  58101. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  58102. int rc;
  58103. MemPage *pPage = 0;
  58104. BtShared *pBt = p->pBt;
  58105. assert( sqlite3BtreeHoldsMutex(p) );
  58106. assert( p->inTrans==TRANS_WRITE );
  58107. /* It is illegal to drop a table if any cursors are open on the
  58108. ** database. This is because in auto-vacuum mode the backend may
  58109. ** need to move another root-page to fill a gap left by the deleted
  58110. ** root page. If an open cursor was using this page a problem would
  58111. ** occur.
  58112. **
  58113. ** This error is caught long before control reaches this point.
  58114. */
  58115. if( NEVER(pBt->pCursor) ){
  58116. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  58117. return SQLITE_LOCKED_SHAREDCACHE;
  58118. }
  58119. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  58120. if( rc ) return rc;
  58121. rc = sqlite3BtreeClearTable(p, iTable, 0);
  58122. if( rc ){
  58123. releasePage(pPage);
  58124. return rc;
  58125. }
  58126. *piMoved = 0;
  58127. if( iTable>1 ){
  58128. #ifdef SQLITE_OMIT_AUTOVACUUM
  58129. freePage(pPage, &rc);
  58130. releasePage(pPage);
  58131. #else
  58132. if( pBt->autoVacuum ){
  58133. Pgno maxRootPgno;
  58134. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  58135. if( iTable==maxRootPgno ){
  58136. /* If the table being dropped is the table with the largest root-page
  58137. ** number in the database, put the root page on the free list.
  58138. */
  58139. freePage(pPage, &rc);
  58140. releasePage(pPage);
  58141. if( rc!=SQLITE_OK ){
  58142. return rc;
  58143. }
  58144. }else{
  58145. /* The table being dropped does not have the largest root-page
  58146. ** number in the database. So move the page that does into the
  58147. ** gap left by the deleted root-page.
  58148. */
  58149. MemPage *pMove;
  58150. releasePage(pPage);
  58151. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  58152. if( rc!=SQLITE_OK ){
  58153. return rc;
  58154. }
  58155. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  58156. releasePage(pMove);
  58157. if( rc!=SQLITE_OK ){
  58158. return rc;
  58159. }
  58160. pMove = 0;
  58161. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  58162. freePage(pMove, &rc);
  58163. releasePage(pMove);
  58164. if( rc!=SQLITE_OK ){
  58165. return rc;
  58166. }
  58167. *piMoved = maxRootPgno;
  58168. }
  58169. /* Set the new 'max-root-page' value in the database header. This
  58170. ** is the old value less one, less one more if that happens to
  58171. ** be a root-page number, less one again if that is the
  58172. ** PENDING_BYTE_PAGE.
  58173. */
  58174. maxRootPgno--;
  58175. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  58176. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  58177. maxRootPgno--;
  58178. }
  58179. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  58180. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  58181. }else{
  58182. freePage(pPage, &rc);
  58183. releasePage(pPage);
  58184. }
  58185. #endif
  58186. }else{
  58187. /* If sqlite3BtreeDropTable was called on page 1.
  58188. ** This really never should happen except in a corrupt
  58189. ** database.
  58190. */
  58191. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  58192. releasePage(pPage);
  58193. }
  58194. return rc;
  58195. }
  58196. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  58197. int rc;
  58198. sqlite3BtreeEnter(p);
  58199. rc = btreeDropTable(p, iTable, piMoved);
  58200. sqlite3BtreeLeave(p);
  58201. return rc;
  58202. }
  58203. /*
  58204. ** This function may only be called if the b-tree connection already
  58205. ** has a read or write transaction open on the database.
  58206. **
  58207. ** Read the meta-information out of a database file. Meta[0]
  58208. ** is the number of free pages currently in the database. Meta[1]
  58209. ** through meta[15] are available for use by higher layers. Meta[0]
  58210. ** is read-only, the others are read/write.
  58211. **
  58212. ** The schema layer numbers meta values differently. At the schema
  58213. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  58214. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  58215. **
  58216. ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
  58217. ** of reading the value out of the header, it instead loads the "DataVersion"
  58218. ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
  58219. ** database file. It is a number computed by the pager. But its access
  58220. ** pattern is the same as header meta values, and so it is convenient to
  58221. ** read it from this routine.
  58222. */
  58223. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  58224. BtShared *pBt = p->pBt;
  58225. sqlite3BtreeEnter(p);
  58226. assert( p->inTrans>TRANS_NONE );
  58227. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  58228. assert( pBt->pPage1 );
  58229. assert( idx>=0 && idx<=15 );
  58230. if( idx==BTREE_DATA_VERSION ){
  58231. *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
  58232. }else{
  58233. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  58234. }
  58235. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  58236. ** database, mark the database as read-only. */
  58237. #ifdef SQLITE_OMIT_AUTOVACUUM
  58238. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  58239. pBt->btsFlags |= BTS_READ_ONLY;
  58240. }
  58241. #endif
  58242. sqlite3BtreeLeave(p);
  58243. }
  58244. /*
  58245. ** Write meta-information back into the database. Meta[0] is
  58246. ** read-only and may not be written.
  58247. */
  58248. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  58249. BtShared *pBt = p->pBt;
  58250. unsigned char *pP1;
  58251. int rc;
  58252. assert( idx>=1 && idx<=15 );
  58253. sqlite3BtreeEnter(p);
  58254. assert( p->inTrans==TRANS_WRITE );
  58255. assert( pBt->pPage1!=0 );
  58256. pP1 = pBt->pPage1->aData;
  58257. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  58258. if( rc==SQLITE_OK ){
  58259. put4byte(&pP1[36 + idx*4], iMeta);
  58260. #ifndef SQLITE_OMIT_AUTOVACUUM
  58261. if( idx==BTREE_INCR_VACUUM ){
  58262. assert( pBt->autoVacuum || iMeta==0 );
  58263. assert( iMeta==0 || iMeta==1 );
  58264. pBt->incrVacuum = (u8)iMeta;
  58265. }
  58266. #endif
  58267. }
  58268. sqlite3BtreeLeave(p);
  58269. return rc;
  58270. }
  58271. #ifndef SQLITE_OMIT_BTREECOUNT
  58272. /*
  58273. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  58274. ** number of entries in the b-tree and write the result to *pnEntry.
  58275. **
  58276. ** SQLITE_OK is returned if the operation is successfully executed.
  58277. ** Otherwise, if an error is encountered (i.e. an IO error or database
  58278. ** corruption) an SQLite error code is returned.
  58279. */
  58280. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  58281. i64 nEntry = 0; /* Value to return in *pnEntry */
  58282. int rc; /* Return code */
  58283. if( pCur->pgnoRoot==0 ){
  58284. *pnEntry = 0;
  58285. return SQLITE_OK;
  58286. }
  58287. rc = moveToRoot(pCur);
  58288. /* Unless an error occurs, the following loop runs one iteration for each
  58289. ** page in the B-Tree structure (not including overflow pages).
  58290. */
  58291. while( rc==SQLITE_OK ){
  58292. int iIdx; /* Index of child node in parent */
  58293. MemPage *pPage; /* Current page of the b-tree */
  58294. /* If this is a leaf page or the tree is not an int-key tree, then
  58295. ** this page contains countable entries. Increment the entry counter
  58296. ** accordingly.
  58297. */
  58298. pPage = pCur->apPage[pCur->iPage];
  58299. if( pPage->leaf || !pPage->intKey ){
  58300. nEntry += pPage->nCell;
  58301. }
  58302. /* pPage is a leaf node. This loop navigates the cursor so that it
  58303. ** points to the first interior cell that it points to the parent of
  58304. ** the next page in the tree that has not yet been visited. The
  58305. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  58306. ** of the page, or to the number of cells in the page if the next page
  58307. ** to visit is the right-child of its parent.
  58308. **
  58309. ** If all pages in the tree have been visited, return SQLITE_OK to the
  58310. ** caller.
  58311. */
  58312. if( pPage->leaf ){
  58313. do {
  58314. if( pCur->iPage==0 ){
  58315. /* All pages of the b-tree have been visited. Return successfully. */
  58316. *pnEntry = nEntry;
  58317. return moveToRoot(pCur);
  58318. }
  58319. moveToParent(pCur);
  58320. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  58321. pCur->aiIdx[pCur->iPage]++;
  58322. pPage = pCur->apPage[pCur->iPage];
  58323. }
  58324. /* Descend to the child node of the cell that the cursor currently
  58325. ** points at. This is the right-child if (iIdx==pPage->nCell).
  58326. */
  58327. iIdx = pCur->aiIdx[pCur->iPage];
  58328. if( iIdx==pPage->nCell ){
  58329. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  58330. }else{
  58331. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  58332. }
  58333. }
  58334. /* An error has occurred. Return an error code. */
  58335. return rc;
  58336. }
  58337. #endif
  58338. /*
  58339. ** Return the pager associated with a BTree. This routine is used for
  58340. ** testing and debugging only.
  58341. */
  58342. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  58343. return p->pBt->pPager;
  58344. }
  58345. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  58346. /*
  58347. ** Append a message to the error message string.
  58348. */
  58349. static void checkAppendMsg(
  58350. IntegrityCk *pCheck,
  58351. const char *zFormat,
  58352. ...
  58353. ){
  58354. va_list ap;
  58355. char zBuf[200];
  58356. if( !pCheck->mxErr ) return;
  58357. pCheck->mxErr--;
  58358. pCheck->nErr++;
  58359. va_start(ap, zFormat);
  58360. if( pCheck->errMsg.nChar ){
  58361. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  58362. }
  58363. if( pCheck->zPfx ){
  58364. sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
  58365. sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
  58366. }
  58367. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  58368. va_end(ap);
  58369. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  58370. pCheck->mallocFailed = 1;
  58371. }
  58372. }
  58373. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  58374. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  58375. /*
  58376. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  58377. ** corresponds to page iPg is already set.
  58378. */
  58379. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  58380. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  58381. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  58382. }
  58383. /*
  58384. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  58385. */
  58386. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  58387. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  58388. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  58389. }
  58390. /*
  58391. ** Add 1 to the reference count for page iPage. If this is the second
  58392. ** reference to the page, add an error message to pCheck->zErrMsg.
  58393. ** Return 1 if there are 2 or more references to the page and 0 if
  58394. ** if this is the first reference to the page.
  58395. **
  58396. ** Also check that the page number is in bounds.
  58397. */
  58398. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  58399. if( iPage==0 ) return 1;
  58400. if( iPage>pCheck->nPage ){
  58401. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  58402. return 1;
  58403. }
  58404. if( getPageReferenced(pCheck, iPage) ){
  58405. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  58406. return 1;
  58407. }
  58408. setPageReferenced(pCheck, iPage);
  58409. return 0;
  58410. }
  58411. #ifndef SQLITE_OMIT_AUTOVACUUM
  58412. /*
  58413. ** Check that the entry in the pointer-map for page iChild maps to
  58414. ** page iParent, pointer type ptrType. If not, append an error message
  58415. ** to pCheck.
  58416. */
  58417. static void checkPtrmap(
  58418. IntegrityCk *pCheck, /* Integrity check context */
  58419. Pgno iChild, /* Child page number */
  58420. u8 eType, /* Expected pointer map type */
  58421. Pgno iParent /* Expected pointer map parent page number */
  58422. ){
  58423. int rc;
  58424. u8 ePtrmapType;
  58425. Pgno iPtrmapParent;
  58426. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  58427. if( rc!=SQLITE_OK ){
  58428. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  58429. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  58430. return;
  58431. }
  58432. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  58433. checkAppendMsg(pCheck,
  58434. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  58435. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  58436. }
  58437. }
  58438. #endif
  58439. /*
  58440. ** Check the integrity of the freelist or of an overflow page list.
  58441. ** Verify that the number of pages on the list is N.
  58442. */
  58443. static void checkList(
  58444. IntegrityCk *pCheck, /* Integrity checking context */
  58445. int isFreeList, /* True for a freelist. False for overflow page list */
  58446. int iPage, /* Page number for first page in the list */
  58447. int N /* Expected number of pages in the list */
  58448. ){
  58449. int i;
  58450. int expected = N;
  58451. int iFirst = iPage;
  58452. while( N-- > 0 && pCheck->mxErr ){
  58453. DbPage *pOvflPage;
  58454. unsigned char *pOvflData;
  58455. if( iPage<1 ){
  58456. checkAppendMsg(pCheck,
  58457. "%d of %d pages missing from overflow list starting at %d",
  58458. N+1, expected, iFirst);
  58459. break;
  58460. }
  58461. if( checkRef(pCheck, iPage) ) break;
  58462. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  58463. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  58464. break;
  58465. }
  58466. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  58467. if( isFreeList ){
  58468. int n = get4byte(&pOvflData[4]);
  58469. #ifndef SQLITE_OMIT_AUTOVACUUM
  58470. if( pCheck->pBt->autoVacuum ){
  58471. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  58472. }
  58473. #endif
  58474. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  58475. checkAppendMsg(pCheck,
  58476. "freelist leaf count too big on page %d", iPage);
  58477. N--;
  58478. }else{
  58479. for(i=0; i<n; i++){
  58480. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  58481. #ifndef SQLITE_OMIT_AUTOVACUUM
  58482. if( pCheck->pBt->autoVacuum ){
  58483. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  58484. }
  58485. #endif
  58486. checkRef(pCheck, iFreePage);
  58487. }
  58488. N -= n;
  58489. }
  58490. }
  58491. #ifndef SQLITE_OMIT_AUTOVACUUM
  58492. else{
  58493. /* If this database supports auto-vacuum and iPage is not the last
  58494. ** page in this overflow list, check that the pointer-map entry for
  58495. ** the following page matches iPage.
  58496. */
  58497. if( pCheck->pBt->autoVacuum && N>0 ){
  58498. i = get4byte(pOvflData);
  58499. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  58500. }
  58501. }
  58502. #endif
  58503. iPage = get4byte(pOvflData);
  58504. sqlite3PagerUnref(pOvflPage);
  58505. }
  58506. }
  58507. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  58508. /*
  58509. ** An implementation of a min-heap.
  58510. **
  58511. ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
  58512. ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
  58513. ** and aHeap[N*2+1].
  58514. **
  58515. ** The heap property is this: Every node is less than or equal to both
  58516. ** of its daughter nodes. A consequence of the heap property is that the
  58517. ** root node aHeap[1] is always the minimum value currently in the heap.
  58518. **
  58519. ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
  58520. ** the heap, preserving the heap property. The btreeHeapPull() routine
  58521. ** removes the root element from the heap (the minimum value in the heap)
  58522. ** and then moves other nodes around as necessary to preserve the heap
  58523. ** property.
  58524. **
  58525. ** This heap is used for cell overlap and coverage testing. Each u32
  58526. ** entry represents the span of a cell or freeblock on a btree page.
  58527. ** The upper 16 bits are the index of the first byte of a range and the
  58528. ** lower 16 bits are the index of the last byte of that range.
  58529. */
  58530. static void btreeHeapInsert(u32 *aHeap, u32 x){
  58531. u32 j, i = ++aHeap[0];
  58532. aHeap[i] = x;
  58533. while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
  58534. x = aHeap[j];
  58535. aHeap[j] = aHeap[i];
  58536. aHeap[i] = x;
  58537. i = j;
  58538. }
  58539. }
  58540. static int btreeHeapPull(u32 *aHeap, u32 *pOut){
  58541. u32 j, i, x;
  58542. if( (x = aHeap[0])==0 ) return 0;
  58543. *pOut = aHeap[1];
  58544. aHeap[1] = aHeap[x];
  58545. aHeap[x] = 0xffffffff;
  58546. aHeap[0]--;
  58547. i = 1;
  58548. while( (j = i*2)<=aHeap[0] ){
  58549. if( aHeap[j]>aHeap[j+1] ) j++;
  58550. if( aHeap[i]<aHeap[j] ) break;
  58551. x = aHeap[i];
  58552. aHeap[i] = aHeap[j];
  58553. aHeap[j] = x;
  58554. i = j;
  58555. }
  58556. return 1;
  58557. }
  58558. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  58559. /*
  58560. ** Do various sanity checks on a single page of a tree. Return
  58561. ** the tree depth. Root pages return 0. Parents of root pages
  58562. ** return 1, and so forth.
  58563. **
  58564. ** These checks are done:
  58565. **
  58566. ** 1. Make sure that cells and freeblocks do not overlap
  58567. ** but combine to completely cover the page.
  58568. ** 2. Make sure integer cell keys are in order.
  58569. ** 3. Check the integrity of overflow pages.
  58570. ** 4. Recursively call checkTreePage on all children.
  58571. ** 5. Verify that the depth of all children is the same.
  58572. */
  58573. static int checkTreePage(
  58574. IntegrityCk *pCheck, /* Context for the sanity check */
  58575. int iPage, /* Page number of the page to check */
  58576. i64 *piMinKey, /* Write minimum integer primary key here */
  58577. i64 maxKey /* Error if integer primary key greater than this */
  58578. ){
  58579. MemPage *pPage = 0; /* The page being analyzed */
  58580. int i; /* Loop counter */
  58581. int rc; /* Result code from subroutine call */
  58582. int depth = -1, d2; /* Depth of a subtree */
  58583. int pgno; /* Page number */
  58584. int nFrag; /* Number of fragmented bytes on the page */
  58585. int hdr; /* Offset to the page header */
  58586. int cellStart; /* Offset to the start of the cell pointer array */
  58587. int nCell; /* Number of cells */
  58588. int doCoverageCheck = 1; /* True if cell coverage checking should be done */
  58589. int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
  58590. ** False if IPK must be strictly less than maxKey */
  58591. u8 *data; /* Page content */
  58592. u8 *pCell; /* Cell content */
  58593. u8 *pCellIdx; /* Next element of the cell pointer array */
  58594. BtShared *pBt; /* The BtShared object that owns pPage */
  58595. u32 pc; /* Address of a cell */
  58596. u32 usableSize; /* Usable size of the page */
  58597. u32 contentOffset; /* Offset to the start of the cell content area */
  58598. u32 *heap = 0; /* Min-heap used for checking cell coverage */
  58599. u32 x, prev = 0; /* Next and previous entry on the min-heap */
  58600. const char *saved_zPfx = pCheck->zPfx;
  58601. int saved_v1 = pCheck->v1;
  58602. int saved_v2 = pCheck->v2;
  58603. u8 savedIsInit = 0;
  58604. /* Check that the page exists
  58605. */
  58606. pBt = pCheck->pBt;
  58607. usableSize = pBt->usableSize;
  58608. if( iPage==0 ) return 0;
  58609. if( checkRef(pCheck, iPage) ) return 0;
  58610. pCheck->zPfx = "Page %d: ";
  58611. pCheck->v1 = iPage;
  58612. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  58613. checkAppendMsg(pCheck,
  58614. "unable to get the page. error code=%d", rc);
  58615. goto end_of_check;
  58616. }
  58617. /* Clear MemPage.isInit to make sure the corruption detection code in
  58618. ** btreeInitPage() is executed. */
  58619. savedIsInit = pPage->isInit;
  58620. pPage->isInit = 0;
  58621. if( (rc = btreeInitPage(pPage))!=0 ){
  58622. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  58623. checkAppendMsg(pCheck,
  58624. "btreeInitPage() returns error code %d", rc);
  58625. goto end_of_check;
  58626. }
  58627. data = pPage->aData;
  58628. hdr = pPage->hdrOffset;
  58629. /* Set up for cell analysis */
  58630. pCheck->zPfx = "On tree page %d cell %d: ";
  58631. contentOffset = get2byteNotZero(&data[hdr+5]);
  58632. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  58633. /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
  58634. ** number of cells on the page. */
  58635. nCell = get2byte(&data[hdr+3]);
  58636. assert( pPage->nCell==nCell );
  58637. /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
  58638. ** immediately follows the b-tree page header. */
  58639. cellStart = hdr + 12 - 4*pPage->leaf;
  58640. assert( pPage->aCellIdx==&data[cellStart] );
  58641. pCellIdx = &data[cellStart + 2*(nCell-1)];
  58642. if( !pPage->leaf ){
  58643. /* Analyze the right-child page of internal pages */
  58644. pgno = get4byte(&data[hdr+8]);
  58645. #ifndef SQLITE_OMIT_AUTOVACUUM
  58646. if( pBt->autoVacuum ){
  58647. pCheck->zPfx = "On page %d at right child: ";
  58648. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  58649. }
  58650. #endif
  58651. depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  58652. keyCanBeEqual = 0;
  58653. }else{
  58654. /* For leaf pages, the coverage check will occur in the same loop
  58655. ** as the other cell checks, so initialize the heap. */
  58656. heap = pCheck->heap;
  58657. heap[0] = 0;
  58658. }
  58659. /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
  58660. ** integer offsets to the cell contents. */
  58661. for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
  58662. CellInfo info;
  58663. /* Check cell size */
  58664. pCheck->v2 = i;
  58665. assert( pCellIdx==&data[cellStart + i*2] );
  58666. pc = get2byteAligned(pCellIdx);
  58667. pCellIdx -= 2;
  58668. if( pc<contentOffset || pc>usableSize-4 ){
  58669. checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
  58670. pc, contentOffset, usableSize-4);
  58671. doCoverageCheck = 0;
  58672. continue;
  58673. }
  58674. pCell = &data[pc];
  58675. pPage->xParseCell(pPage, pCell, &info);
  58676. if( pc+info.nSize>usableSize ){
  58677. checkAppendMsg(pCheck, "Extends off end of page");
  58678. doCoverageCheck = 0;
  58679. continue;
  58680. }
  58681. /* Check for integer primary key out of range */
  58682. if( pPage->intKey ){
  58683. if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
  58684. checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
  58685. }
  58686. maxKey = info.nKey;
  58687. }
  58688. /* Check the content overflow list */
  58689. if( info.nPayload>info.nLocal ){
  58690. int nPage; /* Number of pages on the overflow chain */
  58691. Pgno pgnoOvfl; /* First page of the overflow chain */
  58692. assert( pc + info.iOverflow <= usableSize );
  58693. nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
  58694. pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  58695. #ifndef SQLITE_OMIT_AUTOVACUUM
  58696. if( pBt->autoVacuum ){
  58697. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  58698. }
  58699. #endif
  58700. checkList(pCheck, 0, pgnoOvfl, nPage);
  58701. }
  58702. if( !pPage->leaf ){
  58703. /* Check sanity of left child page for internal pages */
  58704. pgno = get4byte(pCell);
  58705. #ifndef SQLITE_OMIT_AUTOVACUUM
  58706. if( pBt->autoVacuum ){
  58707. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  58708. }
  58709. #endif
  58710. d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
  58711. keyCanBeEqual = 0;
  58712. if( d2!=depth ){
  58713. checkAppendMsg(pCheck, "Child page depth differs");
  58714. depth = d2;
  58715. }
  58716. }else{
  58717. /* Populate the coverage-checking heap for leaf pages */
  58718. btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
  58719. }
  58720. }
  58721. *piMinKey = maxKey;
  58722. /* Check for complete coverage of the page
  58723. */
  58724. pCheck->zPfx = 0;
  58725. if( doCoverageCheck && pCheck->mxErr>0 ){
  58726. /* For leaf pages, the min-heap has already been initialized and the
  58727. ** cells have already been inserted. But for internal pages, that has
  58728. ** not yet been done, so do it now */
  58729. if( !pPage->leaf ){
  58730. heap = pCheck->heap;
  58731. heap[0] = 0;
  58732. for(i=nCell-1; i>=0; i--){
  58733. u32 size;
  58734. pc = get2byteAligned(&data[cellStart+i*2]);
  58735. size = pPage->xCellSize(pPage, &data[pc]);
  58736. btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
  58737. }
  58738. }
  58739. /* Add the freeblocks to the min-heap
  58740. **
  58741. ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
  58742. ** is the offset of the first freeblock, or zero if there are no
  58743. ** freeblocks on the page.
  58744. */
  58745. i = get2byte(&data[hdr+1]);
  58746. while( i>0 ){
  58747. int size, j;
  58748. assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  58749. size = get2byte(&data[i+2]);
  58750. assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
  58751. btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
  58752. /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
  58753. ** big-endian integer which is the offset in the b-tree page of the next
  58754. ** freeblock in the chain, or zero if the freeblock is the last on the
  58755. ** chain. */
  58756. j = get2byte(&data[i]);
  58757. /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
  58758. ** increasing offset. */
  58759. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  58760. assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  58761. i = j;
  58762. }
  58763. /* Analyze the min-heap looking for overlap between cells and/or
  58764. ** freeblocks, and counting the number of untracked bytes in nFrag.
  58765. **
  58766. ** Each min-heap entry is of the form: (start_address<<16)|end_address.
  58767. ** There is an implied first entry the covers the page header, the cell
  58768. ** pointer index, and the gap between the cell pointer index and the start
  58769. ** of cell content.
  58770. **
  58771. ** The loop below pulls entries from the min-heap in order and compares
  58772. ** the start_address against the previous end_address. If there is an
  58773. ** overlap, that means bytes are used multiple times. If there is a gap,
  58774. ** that gap is added to the fragmentation count.
  58775. */
  58776. nFrag = 0;
  58777. prev = contentOffset - 1; /* Implied first min-heap entry */
  58778. while( btreeHeapPull(heap,&x) ){
  58779. if( (prev&0xffff)>=(x>>16) ){
  58780. checkAppendMsg(pCheck,
  58781. "Multiple uses for byte %u of page %d", x>>16, iPage);
  58782. break;
  58783. }else{
  58784. nFrag += (x>>16) - (prev&0xffff) - 1;
  58785. prev = x;
  58786. }
  58787. }
  58788. nFrag += usableSize - (prev&0xffff) - 1;
  58789. /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
  58790. ** is stored in the fifth field of the b-tree page header.
  58791. ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
  58792. ** number of fragmented free bytes within the cell content area.
  58793. */
  58794. if( heap[0]==0 && nFrag!=data[hdr+7] ){
  58795. checkAppendMsg(pCheck,
  58796. "Fragmentation of %d bytes reported as %d on page %d",
  58797. nFrag, data[hdr+7], iPage);
  58798. }
  58799. }
  58800. end_of_check:
  58801. if( !doCoverageCheck ) pPage->isInit = savedIsInit;
  58802. releasePage(pPage);
  58803. pCheck->zPfx = saved_zPfx;
  58804. pCheck->v1 = saved_v1;
  58805. pCheck->v2 = saved_v2;
  58806. return depth+1;
  58807. }
  58808. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  58809. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  58810. /*
  58811. ** This routine does a complete check of the given BTree file. aRoot[] is
  58812. ** an array of pages numbers were each page number is the root page of
  58813. ** a table. nRoot is the number of entries in aRoot.
  58814. **
  58815. ** A read-only or read-write transaction must be opened before calling
  58816. ** this function.
  58817. **
  58818. ** Write the number of error seen in *pnErr. Except for some memory
  58819. ** allocation errors, an error message held in memory obtained from
  58820. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  58821. ** returned. If a memory allocation error occurs, NULL is returned.
  58822. */
  58823. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  58824. Btree *p, /* The btree to be checked */
  58825. int *aRoot, /* An array of root pages numbers for individual trees */
  58826. int nRoot, /* Number of entries in aRoot[] */
  58827. int mxErr, /* Stop reporting errors after this many */
  58828. int *pnErr /* Write number of errors seen to this variable */
  58829. ){
  58830. Pgno i;
  58831. IntegrityCk sCheck;
  58832. BtShared *pBt = p->pBt;
  58833. int savedDbFlags = pBt->db->flags;
  58834. char zErr[100];
  58835. VVA_ONLY( int nRef );
  58836. sqlite3BtreeEnter(p);
  58837. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  58838. assert( (nRef = sqlite3PagerRefcount(pBt->pPager))>=0 );
  58839. sCheck.pBt = pBt;
  58840. sCheck.pPager = pBt->pPager;
  58841. sCheck.nPage = btreePagecount(sCheck.pBt);
  58842. sCheck.mxErr = mxErr;
  58843. sCheck.nErr = 0;
  58844. sCheck.mallocFailed = 0;
  58845. sCheck.zPfx = 0;
  58846. sCheck.v1 = 0;
  58847. sCheck.v2 = 0;
  58848. sCheck.aPgRef = 0;
  58849. sCheck.heap = 0;
  58850. sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  58851. if( sCheck.nPage==0 ){
  58852. goto integrity_ck_cleanup;
  58853. }
  58854. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  58855. if( !sCheck.aPgRef ){
  58856. sCheck.mallocFailed = 1;
  58857. goto integrity_ck_cleanup;
  58858. }
  58859. sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
  58860. if( sCheck.heap==0 ){
  58861. sCheck.mallocFailed = 1;
  58862. goto integrity_ck_cleanup;
  58863. }
  58864. i = PENDING_BYTE_PAGE(pBt);
  58865. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  58866. /* Check the integrity of the freelist
  58867. */
  58868. sCheck.zPfx = "Main freelist: ";
  58869. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  58870. get4byte(&pBt->pPage1->aData[36]));
  58871. sCheck.zPfx = 0;
  58872. /* Check all the tables.
  58873. */
  58874. testcase( pBt->db->flags & SQLITE_CellSizeCk );
  58875. pBt->db->flags &= ~SQLITE_CellSizeCk;
  58876. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  58877. i64 notUsed;
  58878. if( aRoot[i]==0 ) continue;
  58879. #ifndef SQLITE_OMIT_AUTOVACUUM
  58880. if( pBt->autoVacuum && aRoot[i]>1 ){
  58881. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  58882. }
  58883. #endif
  58884. checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
  58885. }
  58886. pBt->db->flags = savedDbFlags;
  58887. /* Make sure every page in the file is referenced
  58888. */
  58889. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  58890. #ifdef SQLITE_OMIT_AUTOVACUUM
  58891. if( getPageReferenced(&sCheck, i)==0 ){
  58892. checkAppendMsg(&sCheck, "Page %d is never used", i);
  58893. }
  58894. #else
  58895. /* If the database supports auto-vacuum, make sure no tables contain
  58896. ** references to pointer-map pages.
  58897. */
  58898. if( getPageReferenced(&sCheck, i)==0 &&
  58899. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  58900. checkAppendMsg(&sCheck, "Page %d is never used", i);
  58901. }
  58902. if( getPageReferenced(&sCheck, i)!=0 &&
  58903. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  58904. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  58905. }
  58906. #endif
  58907. }
  58908. /* Clean up and report errors.
  58909. */
  58910. integrity_ck_cleanup:
  58911. sqlite3PageFree(sCheck.heap);
  58912. sqlite3_free(sCheck.aPgRef);
  58913. if( sCheck.mallocFailed ){
  58914. sqlite3StrAccumReset(&sCheck.errMsg);
  58915. sCheck.nErr++;
  58916. }
  58917. *pnErr = sCheck.nErr;
  58918. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  58919. /* Make sure this analysis did not leave any unref() pages. */
  58920. assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
  58921. sqlite3BtreeLeave(p);
  58922. return sqlite3StrAccumFinish(&sCheck.errMsg);
  58923. }
  58924. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  58925. /*
  58926. ** Return the full pathname of the underlying database file. Return
  58927. ** an empty string if the database is in-memory or a TEMP database.
  58928. **
  58929. ** The pager filename is invariant as long as the pager is
  58930. ** open so it is safe to access without the BtShared mutex.
  58931. */
  58932. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  58933. assert( p->pBt->pPager!=0 );
  58934. return sqlite3PagerFilename(p->pBt->pPager, 1);
  58935. }
  58936. /*
  58937. ** Return the pathname of the journal file for this database. The return
  58938. ** value of this routine is the same regardless of whether the journal file
  58939. ** has been created or not.
  58940. **
  58941. ** The pager journal filename is invariant as long as the pager is
  58942. ** open so it is safe to access without the BtShared mutex.
  58943. */
  58944. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  58945. assert( p->pBt->pPager!=0 );
  58946. return sqlite3PagerJournalname(p->pBt->pPager);
  58947. }
  58948. /*
  58949. ** Return non-zero if a transaction is active.
  58950. */
  58951. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  58952. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  58953. return (p && (p->inTrans==TRANS_WRITE));
  58954. }
  58955. #ifndef SQLITE_OMIT_WAL
  58956. /*
  58957. ** Run a checkpoint on the Btree passed as the first argument.
  58958. **
  58959. ** Return SQLITE_LOCKED if this or any other connection has an open
  58960. ** transaction on the shared-cache the argument Btree is connected to.
  58961. **
  58962. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  58963. */
  58964. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  58965. int rc = SQLITE_OK;
  58966. if( p ){
  58967. BtShared *pBt = p->pBt;
  58968. sqlite3BtreeEnter(p);
  58969. if( pBt->inTransaction!=TRANS_NONE ){
  58970. rc = SQLITE_LOCKED;
  58971. }else{
  58972. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  58973. }
  58974. sqlite3BtreeLeave(p);
  58975. }
  58976. return rc;
  58977. }
  58978. #endif
  58979. /*
  58980. ** Return non-zero if a read (or write) transaction is active.
  58981. */
  58982. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  58983. assert( p );
  58984. assert( sqlite3_mutex_held(p->db->mutex) );
  58985. return p->inTrans!=TRANS_NONE;
  58986. }
  58987. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  58988. assert( p );
  58989. assert( sqlite3_mutex_held(p->db->mutex) );
  58990. return p->nBackup!=0;
  58991. }
  58992. /*
  58993. ** This function returns a pointer to a blob of memory associated with
  58994. ** a single shared-btree. The memory is used by client code for its own
  58995. ** purposes (for example, to store a high-level schema associated with
  58996. ** the shared-btree). The btree layer manages reference counting issues.
  58997. **
  58998. ** The first time this is called on a shared-btree, nBytes bytes of memory
  58999. ** are allocated, zeroed, and returned to the caller. For each subsequent
  59000. ** call the nBytes parameter is ignored and a pointer to the same blob
  59001. ** of memory returned.
  59002. **
  59003. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  59004. ** allocated, a null pointer is returned. If the blob has already been
  59005. ** allocated, it is returned as normal.
  59006. **
  59007. ** Just before the shared-btree is closed, the function passed as the
  59008. ** xFree argument when the memory allocation was made is invoked on the
  59009. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  59010. ** on the memory, the btree layer does that.
  59011. */
  59012. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  59013. BtShared *pBt = p->pBt;
  59014. sqlite3BtreeEnter(p);
  59015. if( !pBt->pSchema && nBytes ){
  59016. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  59017. pBt->xFreeSchema = xFree;
  59018. }
  59019. sqlite3BtreeLeave(p);
  59020. return pBt->pSchema;
  59021. }
  59022. /*
  59023. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  59024. ** btree as the argument handle holds an exclusive lock on the
  59025. ** sqlite_master table. Otherwise SQLITE_OK.
  59026. */
  59027. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  59028. int rc;
  59029. assert( sqlite3_mutex_held(p->db->mutex) );
  59030. sqlite3BtreeEnter(p);
  59031. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  59032. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  59033. sqlite3BtreeLeave(p);
  59034. return rc;
  59035. }
  59036. #ifndef SQLITE_OMIT_SHARED_CACHE
  59037. /*
  59038. ** Obtain a lock on the table whose root page is iTab. The
  59039. ** lock is a write lock if isWritelock is true or a read lock
  59040. ** if it is false.
  59041. */
  59042. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  59043. int rc = SQLITE_OK;
  59044. assert( p->inTrans!=TRANS_NONE );
  59045. if( p->sharable ){
  59046. u8 lockType = READ_LOCK + isWriteLock;
  59047. assert( READ_LOCK+1==WRITE_LOCK );
  59048. assert( isWriteLock==0 || isWriteLock==1 );
  59049. sqlite3BtreeEnter(p);
  59050. rc = querySharedCacheTableLock(p, iTab, lockType);
  59051. if( rc==SQLITE_OK ){
  59052. rc = setSharedCacheTableLock(p, iTab, lockType);
  59053. }
  59054. sqlite3BtreeLeave(p);
  59055. }
  59056. return rc;
  59057. }
  59058. #endif
  59059. #ifndef SQLITE_OMIT_INCRBLOB
  59060. /*
  59061. ** Argument pCsr must be a cursor opened for writing on an
  59062. ** INTKEY table currently pointing at a valid table entry.
  59063. ** This function modifies the data stored as part of that entry.
  59064. **
  59065. ** Only the data content may only be modified, it is not possible to
  59066. ** change the length of the data stored. If this function is called with
  59067. ** parameters that attempt to write past the end of the existing data,
  59068. ** no modifications are made and SQLITE_CORRUPT is returned.
  59069. */
  59070. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  59071. int rc;
  59072. assert( cursorHoldsMutex(pCsr) );
  59073. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  59074. assert( pCsr->curFlags & BTCF_Incrblob );
  59075. rc = restoreCursorPosition(pCsr);
  59076. if( rc!=SQLITE_OK ){
  59077. return rc;
  59078. }
  59079. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  59080. if( pCsr->eState!=CURSOR_VALID ){
  59081. return SQLITE_ABORT;
  59082. }
  59083. /* Save the positions of all other cursors open on this table. This is
  59084. ** required in case any of them are holding references to an xFetch
  59085. ** version of the b-tree page modified by the accessPayload call below.
  59086. **
  59087. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  59088. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  59089. ** saveAllCursors can only return SQLITE_OK.
  59090. */
  59091. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  59092. assert( rc==SQLITE_OK );
  59093. /* Check some assumptions:
  59094. ** (a) the cursor is open for writing,
  59095. ** (b) there is a read/write transaction open,
  59096. ** (c) the connection holds a write-lock on the table (if required),
  59097. ** (d) there are no conflicting read-locks, and
  59098. ** (e) the cursor points at a valid row of an intKey table.
  59099. */
  59100. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  59101. return SQLITE_READONLY;
  59102. }
  59103. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  59104. && pCsr->pBt->inTransaction==TRANS_WRITE );
  59105. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  59106. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  59107. assert( pCsr->apPage[pCsr->iPage]->intKey );
  59108. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  59109. }
  59110. /*
  59111. ** Mark this cursor as an incremental blob cursor.
  59112. */
  59113. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  59114. pCur->curFlags |= BTCF_Incrblob;
  59115. pCur->pBtree->hasIncrblobCur = 1;
  59116. }
  59117. #endif
  59118. /*
  59119. ** Set both the "read version" (single byte at byte offset 18) and
  59120. ** "write version" (single byte at byte offset 19) fields in the database
  59121. ** header to iVersion.
  59122. */
  59123. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  59124. BtShared *pBt = pBtree->pBt;
  59125. int rc; /* Return code */
  59126. assert( iVersion==1 || iVersion==2 );
  59127. /* If setting the version fields to 1, do not automatically open the
  59128. ** WAL connection, even if the version fields are currently set to 2.
  59129. */
  59130. pBt->btsFlags &= ~BTS_NO_WAL;
  59131. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  59132. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  59133. if( rc==SQLITE_OK ){
  59134. u8 *aData = pBt->pPage1->aData;
  59135. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  59136. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  59137. if( rc==SQLITE_OK ){
  59138. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  59139. if( rc==SQLITE_OK ){
  59140. aData[18] = (u8)iVersion;
  59141. aData[19] = (u8)iVersion;
  59142. }
  59143. }
  59144. }
  59145. }
  59146. pBt->btsFlags &= ~BTS_NO_WAL;
  59147. return rc;
  59148. }
  59149. /*
  59150. ** set the mask of hint flags for cursor pCsr.
  59151. */
  59152. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  59153. assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
  59154. pCsr->hints = mask;
  59155. }
  59156. #ifdef SQLITE_DEBUG
  59157. /*
  59158. ** Return true if the cursor has a hint specified. This routine is
  59159. ** only used from within assert() statements
  59160. */
  59161. SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
  59162. return (pCsr->hints & mask)!=0;
  59163. }
  59164. #endif
  59165. /*
  59166. ** Return true if the given Btree is read-only.
  59167. */
  59168. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  59169. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  59170. }
  59171. /*
  59172. ** Return the size of the header added to each page by this module.
  59173. */
  59174. SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
  59175. /************** End of btree.c ***********************************************/
  59176. /************** Begin file backup.c ******************************************/
  59177. /*
  59178. ** 2009 January 28
  59179. **
  59180. ** The author disclaims copyright to this source code. In place of
  59181. ** a legal notice, here is a blessing:
  59182. **
  59183. ** May you do good and not evil.
  59184. ** May you find forgiveness for yourself and forgive others.
  59185. ** May you share freely, never taking more than you give.
  59186. **
  59187. *************************************************************************
  59188. ** This file contains the implementation of the sqlite3_backup_XXX()
  59189. ** API functions and the related features.
  59190. */
  59191. /* #include "sqliteInt.h" */
  59192. /* #include "btreeInt.h" */
  59193. /*
  59194. ** Structure allocated for each backup operation.
  59195. */
  59196. struct sqlite3_backup {
  59197. sqlite3* pDestDb; /* Destination database handle */
  59198. Btree *pDest; /* Destination b-tree file */
  59199. u32 iDestSchema; /* Original schema cookie in destination */
  59200. int bDestLocked; /* True once a write-transaction is open on pDest */
  59201. Pgno iNext; /* Page number of the next source page to copy */
  59202. sqlite3* pSrcDb; /* Source database handle */
  59203. Btree *pSrc; /* Source b-tree file */
  59204. int rc; /* Backup process error code */
  59205. /* These two variables are set by every call to backup_step(). They are
  59206. ** read by calls to backup_remaining() and backup_pagecount().
  59207. */
  59208. Pgno nRemaining; /* Number of pages left to copy */
  59209. Pgno nPagecount; /* Total number of pages to copy */
  59210. int isAttached; /* True once backup has been registered with pager */
  59211. sqlite3_backup *pNext; /* Next backup associated with source pager */
  59212. };
  59213. /*
  59214. ** THREAD SAFETY NOTES:
  59215. **
  59216. ** Once it has been created using backup_init(), a single sqlite3_backup
  59217. ** structure may be accessed via two groups of thread-safe entry points:
  59218. **
  59219. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  59220. ** backup_finish(). Both these functions obtain the source database
  59221. ** handle mutex and the mutex associated with the source BtShared
  59222. ** structure, in that order.
  59223. **
  59224. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  59225. ** invoked by the pager layer to report various state changes in
  59226. ** the page cache associated with the source database. The mutex
  59227. ** associated with the source database BtShared structure will always
  59228. ** be held when either of these functions are invoked.
  59229. **
  59230. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  59231. ** backup_pagecount() are not thread-safe functions. If they are called
  59232. ** while some other thread is calling backup_step() or backup_finish(),
  59233. ** the values returned may be invalid. There is no way for a call to
  59234. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  59235. ** or backup_pagecount().
  59236. **
  59237. ** Depending on the SQLite configuration, the database handles and/or
  59238. ** the Btree objects may have their own mutexes that require locking.
  59239. ** Non-sharable Btrees (in-memory databases for example), do not have
  59240. ** associated mutexes.
  59241. */
  59242. /*
  59243. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  59244. ** in connection handle pDb. If such a database cannot be found, return
  59245. ** a NULL pointer and write an error message to pErrorDb.
  59246. **
  59247. ** If the "temp" database is requested, it may need to be opened by this
  59248. ** function. If an error occurs while doing so, return 0 and write an
  59249. ** error message to pErrorDb.
  59250. */
  59251. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  59252. int i = sqlite3FindDbName(pDb, zDb);
  59253. if( i==1 ){
  59254. Parse *pParse;
  59255. int rc = 0;
  59256. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  59257. if( pParse==0 ){
  59258. sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
  59259. rc = SQLITE_NOMEM;
  59260. }else{
  59261. pParse->db = pDb;
  59262. if( sqlite3OpenTempDatabase(pParse) ){
  59263. sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  59264. rc = SQLITE_ERROR;
  59265. }
  59266. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  59267. sqlite3ParserReset(pParse);
  59268. sqlite3StackFree(pErrorDb, pParse);
  59269. }
  59270. if( rc ){
  59271. return 0;
  59272. }
  59273. }
  59274. if( i<0 ){
  59275. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  59276. return 0;
  59277. }
  59278. return pDb->aDb[i].pBt;
  59279. }
  59280. /*
  59281. ** Attempt to set the page size of the destination to match the page size
  59282. ** of the source.
  59283. */
  59284. static int setDestPgsz(sqlite3_backup *p){
  59285. int rc;
  59286. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  59287. return rc;
  59288. }
  59289. /*
  59290. ** Check that there is no open read-transaction on the b-tree passed as the
  59291. ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
  59292. ** is an open read-transaction, return SQLITE_ERROR and leave an error
  59293. ** message in database handle db.
  59294. */
  59295. static int checkReadTransaction(sqlite3 *db, Btree *p){
  59296. if( sqlite3BtreeIsInReadTrans(p) ){
  59297. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
  59298. return SQLITE_ERROR;
  59299. }
  59300. return SQLITE_OK;
  59301. }
  59302. /*
  59303. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  59304. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  59305. ** a pointer to the new sqlite3_backup object.
  59306. **
  59307. ** If an error occurs, NULL is returned and an error code and error message
  59308. ** stored in database handle pDestDb.
  59309. */
  59310. SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
  59311. sqlite3* pDestDb, /* Database to write to */
  59312. const char *zDestDb, /* Name of database within pDestDb */
  59313. sqlite3* pSrcDb, /* Database connection to read from */
  59314. const char *zSrcDb /* Name of database within pSrcDb */
  59315. ){
  59316. sqlite3_backup *p; /* Value to return */
  59317. #ifdef SQLITE_ENABLE_API_ARMOR
  59318. if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
  59319. (void)SQLITE_MISUSE_BKPT;
  59320. return 0;
  59321. }
  59322. #endif
  59323. /* Lock the source database handle. The destination database
  59324. ** handle is not locked in this routine, but it is locked in
  59325. ** sqlite3_backup_step(). The user is required to ensure that no
  59326. ** other thread accesses the destination handle for the duration
  59327. ** of the backup operation. Any attempt to use the destination
  59328. ** database connection while a backup is in progress may cause
  59329. ** a malfunction or a deadlock.
  59330. */
  59331. sqlite3_mutex_enter(pSrcDb->mutex);
  59332. sqlite3_mutex_enter(pDestDb->mutex);
  59333. if( pSrcDb==pDestDb ){
  59334. sqlite3ErrorWithMsg(
  59335. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  59336. );
  59337. p = 0;
  59338. }else {
  59339. /* Allocate space for a new sqlite3_backup object...
  59340. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  59341. ** call to sqlite3_backup_init() and is destroyed by a call to
  59342. ** sqlite3_backup_finish(). */
  59343. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  59344. if( !p ){
  59345. sqlite3Error(pDestDb, SQLITE_NOMEM);
  59346. }
  59347. }
  59348. /* If the allocation succeeded, populate the new object. */
  59349. if( p ){
  59350. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  59351. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  59352. p->pDestDb = pDestDb;
  59353. p->pSrcDb = pSrcDb;
  59354. p->iNext = 1;
  59355. p->isAttached = 0;
  59356. if( 0==p->pSrc || 0==p->pDest
  59357. || setDestPgsz(p)==SQLITE_NOMEM
  59358. || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
  59359. ){
  59360. /* One (or both) of the named databases did not exist or an OOM
  59361. ** error was hit. Or there is a transaction open on the destination
  59362. ** database. The error has already been written into the pDestDb
  59363. ** handle. All that is left to do here is free the sqlite3_backup
  59364. ** structure. */
  59365. sqlite3_free(p);
  59366. p = 0;
  59367. }
  59368. }
  59369. if( p ){
  59370. p->pSrc->nBackup++;
  59371. }
  59372. sqlite3_mutex_leave(pDestDb->mutex);
  59373. sqlite3_mutex_leave(pSrcDb->mutex);
  59374. return p;
  59375. }
  59376. /*
  59377. ** Argument rc is an SQLite error code. Return true if this error is
  59378. ** considered fatal if encountered during a backup operation. All errors
  59379. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  59380. */
  59381. static int isFatalError(int rc){
  59382. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  59383. }
  59384. /*
  59385. ** Parameter zSrcData points to a buffer containing the data for
  59386. ** page iSrcPg from the source database. Copy this data into the
  59387. ** destination database.
  59388. */
  59389. static int backupOnePage(
  59390. sqlite3_backup *p, /* Backup handle */
  59391. Pgno iSrcPg, /* Source database page to backup */
  59392. const u8 *zSrcData, /* Source database page data */
  59393. int bUpdate /* True for an update, false otherwise */
  59394. ){
  59395. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  59396. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  59397. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  59398. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  59399. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  59400. #ifdef SQLITE_HAS_CODEC
  59401. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  59402. ** guaranteed that the shared-mutex is held by this thread, handle
  59403. ** p->pSrc may not actually be the owner. */
  59404. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  59405. int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
  59406. #endif
  59407. int rc = SQLITE_OK;
  59408. i64 iOff;
  59409. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  59410. assert( p->bDestLocked );
  59411. assert( !isFatalError(p->rc) );
  59412. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  59413. assert( zSrcData );
  59414. /* Catch the case where the destination is an in-memory database and the
  59415. ** page sizes of the source and destination differ.
  59416. */
  59417. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  59418. rc = SQLITE_READONLY;
  59419. }
  59420. #ifdef SQLITE_HAS_CODEC
  59421. /* Backup is not possible if the page size of the destination is changing
  59422. ** and a codec is in use.
  59423. */
  59424. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  59425. rc = SQLITE_READONLY;
  59426. }
  59427. /* Backup is not possible if the number of bytes of reserve space differ
  59428. ** between source and destination. If there is a difference, try to
  59429. ** fix the destination to agree with the source. If that is not possible,
  59430. ** then the backup cannot proceed.
  59431. */
  59432. if( nSrcReserve!=nDestReserve ){
  59433. u32 newPgsz = nSrcPgsz;
  59434. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  59435. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  59436. }
  59437. #endif
  59438. /* This loop runs once for each destination page spanned by the source
  59439. ** page. For each iteration, variable iOff is set to the byte offset
  59440. ** of the destination page.
  59441. */
  59442. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  59443. DbPage *pDestPg = 0;
  59444. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  59445. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  59446. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  59447. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  59448. ){
  59449. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  59450. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  59451. u8 *zOut = &zDestData[iOff%nDestPgsz];
  59452. /* Copy the data from the source page into the destination page.
  59453. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  59454. ** and the pager code use this trick (clearing the first byte
  59455. ** of the page 'extra' space to invalidate the Btree layers
  59456. ** cached parse of the page). MemPage.isInit is marked
  59457. ** "MUST BE FIRST" for this purpose.
  59458. */
  59459. memcpy(zOut, zIn, nCopy);
  59460. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  59461. if( iOff==0 && bUpdate==0 ){
  59462. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  59463. }
  59464. }
  59465. sqlite3PagerUnref(pDestPg);
  59466. }
  59467. return rc;
  59468. }
  59469. /*
  59470. ** If pFile is currently larger than iSize bytes, then truncate it to
  59471. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  59472. ** this function is a no-op.
  59473. **
  59474. ** Return SQLITE_OK if everything is successful, or an SQLite error
  59475. ** code if an error occurs.
  59476. */
  59477. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  59478. i64 iCurrent;
  59479. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  59480. if( rc==SQLITE_OK && iCurrent>iSize ){
  59481. rc = sqlite3OsTruncate(pFile, iSize);
  59482. }
  59483. return rc;
  59484. }
  59485. /*
  59486. ** Register this backup object with the associated source pager for
  59487. ** callbacks when pages are changed or the cache invalidated.
  59488. */
  59489. static void attachBackupObject(sqlite3_backup *p){
  59490. sqlite3_backup **pp;
  59491. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  59492. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  59493. p->pNext = *pp;
  59494. *pp = p;
  59495. p->isAttached = 1;
  59496. }
  59497. /*
  59498. ** Copy nPage pages from the source b-tree to the destination.
  59499. */
  59500. SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
  59501. int rc;
  59502. int destMode; /* Destination journal mode */
  59503. int pgszSrc = 0; /* Source page size */
  59504. int pgszDest = 0; /* Destination page size */
  59505. #ifdef SQLITE_ENABLE_API_ARMOR
  59506. if( p==0 ) return SQLITE_MISUSE_BKPT;
  59507. #endif
  59508. sqlite3_mutex_enter(p->pSrcDb->mutex);
  59509. sqlite3BtreeEnter(p->pSrc);
  59510. if( p->pDestDb ){
  59511. sqlite3_mutex_enter(p->pDestDb->mutex);
  59512. }
  59513. rc = p->rc;
  59514. if( !isFatalError(rc) ){
  59515. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  59516. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  59517. int ii; /* Iterator variable */
  59518. int nSrcPage = -1; /* Size of source db in pages */
  59519. int bCloseTrans = 0; /* True if src db requires unlocking */
  59520. /* If the source pager is currently in a write-transaction, return
  59521. ** SQLITE_BUSY immediately.
  59522. */
  59523. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  59524. rc = SQLITE_BUSY;
  59525. }else{
  59526. rc = SQLITE_OK;
  59527. }
  59528. /* Lock the destination database, if it is not locked already. */
  59529. if( SQLITE_OK==rc && p->bDestLocked==0
  59530. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  59531. ){
  59532. p->bDestLocked = 1;
  59533. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  59534. }
  59535. /* If there is no open read-transaction on the source database, open
  59536. ** one now. If a transaction is opened here, then it will be closed
  59537. ** before this function exits.
  59538. */
  59539. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  59540. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  59541. bCloseTrans = 1;
  59542. }
  59543. /* Do not allow backup if the destination database is in WAL mode
  59544. ** and the page sizes are different between source and destination */
  59545. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  59546. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  59547. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  59548. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  59549. rc = SQLITE_READONLY;
  59550. }
  59551. /* Now that there is a read-lock on the source database, query the
  59552. ** source pager for the number of pages in the database.
  59553. */
  59554. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  59555. assert( nSrcPage>=0 );
  59556. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  59557. const Pgno iSrcPg = p->iNext; /* Source page number */
  59558. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  59559. DbPage *pSrcPg; /* Source page object */
  59560. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  59561. PAGER_GET_READONLY);
  59562. if( rc==SQLITE_OK ){
  59563. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  59564. sqlite3PagerUnref(pSrcPg);
  59565. }
  59566. }
  59567. p->iNext++;
  59568. }
  59569. if( rc==SQLITE_OK ){
  59570. p->nPagecount = nSrcPage;
  59571. p->nRemaining = nSrcPage+1-p->iNext;
  59572. if( p->iNext>(Pgno)nSrcPage ){
  59573. rc = SQLITE_DONE;
  59574. }else if( !p->isAttached ){
  59575. attachBackupObject(p);
  59576. }
  59577. }
  59578. /* Update the schema version field in the destination database. This
  59579. ** is to make sure that the schema-version really does change in
  59580. ** the case where the source and destination databases have the
  59581. ** same schema version.
  59582. */
  59583. if( rc==SQLITE_DONE ){
  59584. if( nSrcPage==0 ){
  59585. rc = sqlite3BtreeNewDb(p->pDest);
  59586. nSrcPage = 1;
  59587. }
  59588. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  59589. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  59590. }
  59591. if( rc==SQLITE_OK ){
  59592. if( p->pDestDb ){
  59593. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  59594. }
  59595. if( destMode==PAGER_JOURNALMODE_WAL ){
  59596. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  59597. }
  59598. }
  59599. if( rc==SQLITE_OK ){
  59600. int nDestTruncate;
  59601. /* Set nDestTruncate to the final number of pages in the destination
  59602. ** database. The complication here is that the destination page
  59603. ** size may be different to the source page size.
  59604. **
  59605. ** If the source page size is smaller than the destination page size,
  59606. ** round up. In this case the call to sqlite3OsTruncate() below will
  59607. ** fix the size of the file. However it is important to call
  59608. ** sqlite3PagerTruncateImage() here so that any pages in the
  59609. ** destination file that lie beyond the nDestTruncate page mark are
  59610. ** journalled by PagerCommitPhaseOne() before they are destroyed
  59611. ** by the file truncation.
  59612. */
  59613. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  59614. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  59615. if( pgszSrc<pgszDest ){
  59616. int ratio = pgszDest/pgszSrc;
  59617. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  59618. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  59619. nDestTruncate--;
  59620. }
  59621. }else{
  59622. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  59623. }
  59624. assert( nDestTruncate>0 );
  59625. if( pgszSrc<pgszDest ){
  59626. /* If the source page-size is smaller than the destination page-size,
  59627. ** two extra things may need to happen:
  59628. **
  59629. ** * The destination may need to be truncated, and
  59630. **
  59631. ** * Data stored on the pages immediately following the
  59632. ** pending-byte page in the source database may need to be
  59633. ** copied into the destination database.
  59634. */
  59635. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  59636. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  59637. Pgno iPg;
  59638. int nDstPage;
  59639. i64 iOff;
  59640. i64 iEnd;
  59641. assert( pFile );
  59642. assert( nDestTruncate==0
  59643. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  59644. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  59645. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  59646. ));
  59647. /* This block ensures that all data required to recreate the original
  59648. ** database has been stored in the journal for pDestPager and the
  59649. ** journal synced to disk. So at this point we may safely modify
  59650. ** the database file in any way, knowing that if a power failure
  59651. ** occurs, the original database will be reconstructed from the
  59652. ** journal file. */
  59653. sqlite3PagerPagecount(pDestPager, &nDstPage);
  59654. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  59655. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  59656. DbPage *pPg;
  59657. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  59658. if( rc==SQLITE_OK ){
  59659. rc = sqlite3PagerWrite(pPg);
  59660. sqlite3PagerUnref(pPg);
  59661. }
  59662. }
  59663. }
  59664. if( rc==SQLITE_OK ){
  59665. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  59666. }
  59667. /* Write the extra pages and truncate the database file as required */
  59668. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  59669. for(
  59670. iOff=PENDING_BYTE+pgszSrc;
  59671. rc==SQLITE_OK && iOff<iEnd;
  59672. iOff+=pgszSrc
  59673. ){
  59674. PgHdr *pSrcPg = 0;
  59675. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  59676. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  59677. if( rc==SQLITE_OK ){
  59678. u8 *zData = sqlite3PagerGetData(pSrcPg);
  59679. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  59680. }
  59681. sqlite3PagerUnref(pSrcPg);
  59682. }
  59683. if( rc==SQLITE_OK ){
  59684. rc = backupTruncateFile(pFile, iSize);
  59685. }
  59686. /* Sync the database file to disk. */
  59687. if( rc==SQLITE_OK ){
  59688. rc = sqlite3PagerSync(pDestPager, 0);
  59689. }
  59690. }else{
  59691. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  59692. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  59693. }
  59694. /* Finish committing the transaction to the destination database. */
  59695. if( SQLITE_OK==rc
  59696. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  59697. ){
  59698. rc = SQLITE_DONE;
  59699. }
  59700. }
  59701. }
  59702. /* If bCloseTrans is true, then this function opened a read transaction
  59703. ** on the source database. Close the read transaction here. There is
  59704. ** no need to check the return values of the btree methods here, as
  59705. ** "committing" a read-only transaction cannot fail.
  59706. */
  59707. if( bCloseTrans ){
  59708. TESTONLY( int rc2 );
  59709. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  59710. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  59711. assert( rc2==SQLITE_OK );
  59712. }
  59713. if( rc==SQLITE_IOERR_NOMEM ){
  59714. rc = SQLITE_NOMEM;
  59715. }
  59716. p->rc = rc;
  59717. }
  59718. if( p->pDestDb ){
  59719. sqlite3_mutex_leave(p->pDestDb->mutex);
  59720. }
  59721. sqlite3BtreeLeave(p->pSrc);
  59722. sqlite3_mutex_leave(p->pSrcDb->mutex);
  59723. return rc;
  59724. }
  59725. /*
  59726. ** Release all resources associated with an sqlite3_backup* handle.
  59727. */
  59728. SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
  59729. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  59730. sqlite3 *pSrcDb; /* Source database connection */
  59731. int rc; /* Value to return */
  59732. /* Enter the mutexes */
  59733. if( p==0 ) return SQLITE_OK;
  59734. pSrcDb = p->pSrcDb;
  59735. sqlite3_mutex_enter(pSrcDb->mutex);
  59736. sqlite3BtreeEnter(p->pSrc);
  59737. if( p->pDestDb ){
  59738. sqlite3_mutex_enter(p->pDestDb->mutex);
  59739. }
  59740. /* Detach this backup from the source pager. */
  59741. if( p->pDestDb ){
  59742. p->pSrc->nBackup--;
  59743. }
  59744. if( p->isAttached ){
  59745. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  59746. while( *pp!=p ){
  59747. pp = &(*pp)->pNext;
  59748. }
  59749. *pp = p->pNext;
  59750. }
  59751. /* If a transaction is still open on the Btree, roll it back. */
  59752. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  59753. /* Set the error code of the destination database handle. */
  59754. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  59755. if( p->pDestDb ){
  59756. sqlite3Error(p->pDestDb, rc);
  59757. /* Exit the mutexes and free the backup context structure. */
  59758. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  59759. }
  59760. sqlite3BtreeLeave(p->pSrc);
  59761. if( p->pDestDb ){
  59762. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  59763. ** call to sqlite3_backup_init() and is destroyed by a call to
  59764. ** sqlite3_backup_finish(). */
  59765. sqlite3_free(p);
  59766. }
  59767. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  59768. return rc;
  59769. }
  59770. /*
  59771. ** Return the number of pages still to be backed up as of the most recent
  59772. ** call to sqlite3_backup_step().
  59773. */
  59774. SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
  59775. #ifdef SQLITE_ENABLE_API_ARMOR
  59776. if( p==0 ){
  59777. (void)SQLITE_MISUSE_BKPT;
  59778. return 0;
  59779. }
  59780. #endif
  59781. return p->nRemaining;
  59782. }
  59783. /*
  59784. ** Return the total number of pages in the source database as of the most
  59785. ** recent call to sqlite3_backup_step().
  59786. */
  59787. SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
  59788. #ifdef SQLITE_ENABLE_API_ARMOR
  59789. if( p==0 ){
  59790. (void)SQLITE_MISUSE_BKPT;
  59791. return 0;
  59792. }
  59793. #endif
  59794. return p->nPagecount;
  59795. }
  59796. /*
  59797. ** This function is called after the contents of page iPage of the
  59798. ** source database have been modified. If page iPage has already been
  59799. ** copied into the destination database, then the data written to the
  59800. ** destination is now invalidated. The destination copy of iPage needs
  59801. ** to be updated with the new data before the backup operation is
  59802. ** complete.
  59803. **
  59804. ** It is assumed that the mutex associated with the BtShared object
  59805. ** corresponding to the source database is held when this function is
  59806. ** called.
  59807. */
  59808. static SQLITE_NOINLINE void backupUpdate(
  59809. sqlite3_backup *p,
  59810. Pgno iPage,
  59811. const u8 *aData
  59812. ){
  59813. assert( p!=0 );
  59814. do{
  59815. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  59816. if( !isFatalError(p->rc) && iPage<p->iNext ){
  59817. /* The backup process p has already copied page iPage. But now it
  59818. ** has been modified by a transaction on the source pager. Copy
  59819. ** the new data into the backup.
  59820. */
  59821. int rc;
  59822. assert( p->pDestDb );
  59823. sqlite3_mutex_enter(p->pDestDb->mutex);
  59824. rc = backupOnePage(p, iPage, aData, 1);
  59825. sqlite3_mutex_leave(p->pDestDb->mutex);
  59826. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  59827. if( rc!=SQLITE_OK ){
  59828. p->rc = rc;
  59829. }
  59830. }
  59831. }while( (p = p->pNext)!=0 );
  59832. }
  59833. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  59834. if( pBackup ) backupUpdate(pBackup, iPage, aData);
  59835. }
  59836. /*
  59837. ** Restart the backup process. This is called when the pager layer
  59838. ** detects that the database has been modified by an external database
  59839. ** connection. In this case there is no way of knowing which of the
  59840. ** pages that have been copied into the destination database are still
  59841. ** valid and which are not, so the entire process needs to be restarted.
  59842. **
  59843. ** It is assumed that the mutex associated with the BtShared object
  59844. ** corresponding to the source database is held when this function is
  59845. ** called.
  59846. */
  59847. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  59848. sqlite3_backup *p; /* Iterator variable */
  59849. for(p=pBackup; p; p=p->pNext){
  59850. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  59851. p->iNext = 1;
  59852. }
  59853. }
  59854. #ifndef SQLITE_OMIT_VACUUM
  59855. /*
  59856. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  59857. ** must be active for both files.
  59858. **
  59859. ** The size of file pTo may be reduced by this operation. If anything
  59860. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  59861. ** transaction is committed before returning.
  59862. */
  59863. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  59864. int rc;
  59865. sqlite3_file *pFd; /* File descriptor for database pTo */
  59866. sqlite3_backup b;
  59867. sqlite3BtreeEnter(pTo);
  59868. sqlite3BtreeEnter(pFrom);
  59869. assert( sqlite3BtreeIsInTrans(pTo) );
  59870. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  59871. if( pFd->pMethods ){
  59872. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  59873. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  59874. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  59875. if( rc ) goto copy_finished;
  59876. }
  59877. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  59878. ** to 0. This is used by the implementations of sqlite3_backup_step()
  59879. ** and sqlite3_backup_finish() to detect that they are being called
  59880. ** from this function, not directly by the user.
  59881. */
  59882. memset(&b, 0, sizeof(b));
  59883. b.pSrcDb = pFrom->db;
  59884. b.pSrc = pFrom;
  59885. b.pDest = pTo;
  59886. b.iNext = 1;
  59887. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  59888. ** file. By passing this as the number of pages to copy to
  59889. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  59890. ** within a single call (unless an error occurs). The assert() statement
  59891. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  59892. ** or an error code.
  59893. */
  59894. sqlite3_backup_step(&b, 0x7FFFFFFF);
  59895. assert( b.rc!=SQLITE_OK );
  59896. rc = sqlite3_backup_finish(&b);
  59897. if( rc==SQLITE_OK ){
  59898. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  59899. }else{
  59900. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  59901. }
  59902. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  59903. copy_finished:
  59904. sqlite3BtreeLeave(pFrom);
  59905. sqlite3BtreeLeave(pTo);
  59906. return rc;
  59907. }
  59908. #endif /* SQLITE_OMIT_VACUUM */
  59909. /************** End of backup.c **********************************************/
  59910. /************** Begin file vdbemem.c *****************************************/
  59911. /*
  59912. ** 2004 May 26
  59913. **
  59914. ** The author disclaims copyright to this source code. In place of
  59915. ** a legal notice, here is a blessing:
  59916. **
  59917. ** May you do good and not evil.
  59918. ** May you find forgiveness for yourself and forgive others.
  59919. ** May you share freely, never taking more than you give.
  59920. **
  59921. *************************************************************************
  59922. **
  59923. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  59924. ** stores a single value in the VDBE. Mem is an opaque structure visible
  59925. ** only within the VDBE. Interface routines refer to a Mem using the
  59926. ** name sqlite_value
  59927. */
  59928. /* #include "sqliteInt.h" */
  59929. /* #include "vdbeInt.h" */
  59930. #ifdef SQLITE_DEBUG
  59931. /*
  59932. ** Check invariants on a Mem object.
  59933. **
  59934. ** This routine is intended for use inside of assert() statements, like
  59935. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  59936. */
  59937. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  59938. /* If MEM_Dyn is set then Mem.xDel!=0.
  59939. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  59940. */
  59941. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  59942. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  59943. ** ensure that if Mem.szMalloc>0 then it is safe to do
  59944. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  59945. ** That saves a few cycles in inner loops. */
  59946. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  59947. /* Cannot be both MEM_Int and MEM_Real at the same time */
  59948. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  59949. /* The szMalloc field holds the correct memory allocation size */
  59950. assert( p->szMalloc==0
  59951. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  59952. /* If p holds a string or blob, the Mem.z must point to exactly
  59953. ** one of the following:
  59954. **
  59955. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  59956. ** (2) Memory to be freed using Mem.xDel
  59957. ** (3) An ephemeral string or blob
  59958. ** (4) A static string or blob
  59959. */
  59960. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  59961. assert(
  59962. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  59963. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  59964. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  59965. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  59966. );
  59967. }
  59968. return 1;
  59969. }
  59970. #endif
  59971. /*
  59972. ** If pMem is an object with a valid string representation, this routine
  59973. ** ensures the internal encoding for the string representation is
  59974. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  59975. **
  59976. ** If pMem is not a string object, or the encoding of the string
  59977. ** representation is already stored using the requested encoding, then this
  59978. ** routine is a no-op.
  59979. **
  59980. ** SQLITE_OK is returned if the conversion is successful (or not required).
  59981. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  59982. ** between formats.
  59983. */
  59984. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  59985. #ifndef SQLITE_OMIT_UTF16
  59986. int rc;
  59987. #endif
  59988. assert( (pMem->flags&MEM_RowSet)==0 );
  59989. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  59990. || desiredEnc==SQLITE_UTF16BE );
  59991. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  59992. return SQLITE_OK;
  59993. }
  59994. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  59995. #ifdef SQLITE_OMIT_UTF16
  59996. return SQLITE_ERROR;
  59997. #else
  59998. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  59999. ** then the encoding of the value may not have changed.
  60000. */
  60001. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  60002. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  60003. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  60004. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  60005. return rc;
  60006. #endif
  60007. }
  60008. /*
  60009. ** Make sure pMem->z points to a writable allocation of at least
  60010. ** min(n,32) bytes.
  60011. **
  60012. ** If the bPreserve argument is true, then copy of the content of
  60013. ** pMem->z into the new allocation. pMem must be either a string or
  60014. ** blob if bPreserve is true. If bPreserve is false, any prior content
  60015. ** in pMem->z is discarded.
  60016. */
  60017. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  60018. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  60019. assert( (pMem->flags&MEM_RowSet)==0 );
  60020. /* If the bPreserve flag is set to true, then the memory cell must already
  60021. ** contain a valid string or blob value. */
  60022. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  60023. testcase( bPreserve && pMem->z==0 );
  60024. assert( pMem->szMalloc==0
  60025. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  60026. if( pMem->szMalloc<n ){
  60027. if( n<32 ) n = 32;
  60028. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  60029. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  60030. bPreserve = 0;
  60031. }else{
  60032. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  60033. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  60034. }
  60035. if( pMem->zMalloc==0 ){
  60036. sqlite3VdbeMemSetNull(pMem);
  60037. pMem->z = 0;
  60038. pMem->szMalloc = 0;
  60039. return SQLITE_NOMEM;
  60040. }else{
  60041. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  60042. }
  60043. }
  60044. if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
  60045. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  60046. }
  60047. if( (pMem->flags&MEM_Dyn)!=0 ){
  60048. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  60049. pMem->xDel((void *)(pMem->z));
  60050. }
  60051. pMem->z = pMem->zMalloc;
  60052. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  60053. return SQLITE_OK;
  60054. }
  60055. /*
  60056. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  60057. ** If pMem->zMalloc already meets or exceeds the requested size, this
  60058. ** routine is a no-op.
  60059. **
  60060. ** Any prior string or blob content in the pMem object may be discarded.
  60061. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  60062. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  60063. ** values are preserved.
  60064. **
  60065. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  60066. ** if unable to complete the resizing.
  60067. */
  60068. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  60069. assert( szNew>0 );
  60070. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  60071. if( pMem->szMalloc<szNew ){
  60072. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  60073. }
  60074. assert( (pMem->flags & MEM_Dyn)==0 );
  60075. pMem->z = pMem->zMalloc;
  60076. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  60077. return SQLITE_OK;
  60078. }
  60079. /*
  60080. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  60081. ** MEM.zMalloc, where it can be safely written.
  60082. **
  60083. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  60084. */
  60085. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  60086. int f;
  60087. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60088. assert( (pMem->flags&MEM_RowSet)==0 );
  60089. ExpandBlob(pMem);
  60090. f = pMem->flags;
  60091. if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
  60092. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  60093. return SQLITE_NOMEM;
  60094. }
  60095. pMem->z[pMem->n] = 0;
  60096. pMem->z[pMem->n+1] = 0;
  60097. pMem->flags |= MEM_Term;
  60098. }
  60099. pMem->flags &= ~MEM_Ephem;
  60100. #ifdef SQLITE_DEBUG
  60101. pMem->pScopyFrom = 0;
  60102. #endif
  60103. return SQLITE_OK;
  60104. }
  60105. /*
  60106. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  60107. ** blob stored in dynamically allocated space.
  60108. */
  60109. #ifndef SQLITE_OMIT_INCRBLOB
  60110. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  60111. if( pMem->flags & MEM_Zero ){
  60112. int nByte;
  60113. assert( pMem->flags&MEM_Blob );
  60114. assert( (pMem->flags&MEM_RowSet)==0 );
  60115. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60116. /* Set nByte to the number of bytes required to store the expanded blob. */
  60117. nByte = pMem->n + pMem->u.nZero;
  60118. if( nByte<=0 ){
  60119. nByte = 1;
  60120. }
  60121. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  60122. return SQLITE_NOMEM;
  60123. }
  60124. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  60125. pMem->n += pMem->u.nZero;
  60126. pMem->flags &= ~(MEM_Zero|MEM_Term);
  60127. }
  60128. return SQLITE_OK;
  60129. }
  60130. #endif
  60131. /*
  60132. ** It is already known that pMem contains an unterminated string.
  60133. ** Add the zero terminator.
  60134. */
  60135. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  60136. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  60137. return SQLITE_NOMEM;
  60138. }
  60139. pMem->z[pMem->n] = 0;
  60140. pMem->z[pMem->n+1] = 0;
  60141. pMem->flags |= MEM_Term;
  60142. return SQLITE_OK;
  60143. }
  60144. /*
  60145. ** Make sure the given Mem is \u0000 terminated.
  60146. */
  60147. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  60148. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60149. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  60150. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  60151. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  60152. return SQLITE_OK; /* Nothing to do */
  60153. }else{
  60154. return vdbeMemAddTerminator(pMem);
  60155. }
  60156. }
  60157. /*
  60158. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  60159. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  60160. ** is a no-op.
  60161. **
  60162. ** Existing representations MEM_Int and MEM_Real are invalidated if
  60163. ** bForce is true but are retained if bForce is false.
  60164. **
  60165. ** A MEM_Null value will never be passed to this function. This function is
  60166. ** used for converting values to text for returning to the user (i.e. via
  60167. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  60168. ** keys are strings. In the former case a NULL pointer is returned the
  60169. ** user and the latter is an internal programming error.
  60170. */
  60171. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  60172. int fg = pMem->flags;
  60173. const int nByte = 32;
  60174. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60175. assert( !(fg&MEM_Zero) );
  60176. assert( !(fg&(MEM_Str|MEM_Blob)) );
  60177. assert( fg&(MEM_Int|MEM_Real) );
  60178. assert( (pMem->flags&MEM_RowSet)==0 );
  60179. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  60180. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  60181. return SQLITE_NOMEM;
  60182. }
  60183. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  60184. ** string representation of the value. Then, if the required encoding
  60185. ** is UTF-16le or UTF-16be do a translation.
  60186. **
  60187. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  60188. */
  60189. if( fg & MEM_Int ){
  60190. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  60191. }else{
  60192. assert( fg & MEM_Real );
  60193. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  60194. }
  60195. pMem->n = sqlite3Strlen30(pMem->z);
  60196. pMem->enc = SQLITE_UTF8;
  60197. pMem->flags |= MEM_Str|MEM_Term;
  60198. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  60199. sqlite3VdbeChangeEncoding(pMem, enc);
  60200. return SQLITE_OK;
  60201. }
  60202. /*
  60203. ** Memory cell pMem contains the context of an aggregate function.
  60204. ** This routine calls the finalize method for that function. The
  60205. ** result of the aggregate is stored back into pMem.
  60206. **
  60207. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  60208. ** otherwise.
  60209. */
  60210. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  60211. int rc = SQLITE_OK;
  60212. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  60213. sqlite3_context ctx;
  60214. Mem t;
  60215. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  60216. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60217. memset(&ctx, 0, sizeof(ctx));
  60218. memset(&t, 0, sizeof(t));
  60219. t.flags = MEM_Null;
  60220. t.db = pMem->db;
  60221. ctx.pOut = &t;
  60222. ctx.pMem = pMem;
  60223. ctx.pFunc = pFunc;
  60224. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  60225. assert( (pMem->flags & MEM_Dyn)==0 );
  60226. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  60227. memcpy(pMem, &t, sizeof(t));
  60228. rc = ctx.isError;
  60229. }
  60230. return rc;
  60231. }
  60232. /*
  60233. ** If the memory cell contains a value that must be freed by
  60234. ** invoking the external callback in Mem.xDel, then this routine
  60235. ** will free that value. It also sets Mem.flags to MEM_Null.
  60236. **
  60237. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  60238. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  60239. ** entry point for releasing Mem resources.
  60240. */
  60241. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  60242. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  60243. assert( VdbeMemDynamic(p) );
  60244. if( p->flags&MEM_Agg ){
  60245. sqlite3VdbeMemFinalize(p, p->u.pDef);
  60246. assert( (p->flags & MEM_Agg)==0 );
  60247. testcase( p->flags & MEM_Dyn );
  60248. }
  60249. if( p->flags&MEM_Dyn ){
  60250. assert( (p->flags&MEM_RowSet)==0 );
  60251. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  60252. p->xDel((void *)p->z);
  60253. }else if( p->flags&MEM_RowSet ){
  60254. sqlite3RowSetClear(p->u.pRowSet);
  60255. }else if( p->flags&MEM_Frame ){
  60256. VdbeFrame *pFrame = p->u.pFrame;
  60257. pFrame->pParent = pFrame->v->pDelFrame;
  60258. pFrame->v->pDelFrame = pFrame;
  60259. }
  60260. p->flags = MEM_Null;
  60261. }
  60262. /*
  60263. ** Release memory held by the Mem p, both external memory cleared
  60264. ** by p->xDel and memory in p->zMalloc.
  60265. **
  60266. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  60267. ** the unusual case where there really is memory in p that needs
  60268. ** to be freed.
  60269. */
  60270. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  60271. if( VdbeMemDynamic(p) ){
  60272. vdbeMemClearExternAndSetNull(p);
  60273. }
  60274. if( p->szMalloc ){
  60275. sqlite3DbFree(p->db, p->zMalloc);
  60276. p->szMalloc = 0;
  60277. }
  60278. p->z = 0;
  60279. }
  60280. /*
  60281. ** Release any memory resources held by the Mem. Both the memory that is
  60282. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  60283. **
  60284. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  60285. ** reset a Mem back to its minimum memory utilization.
  60286. **
  60287. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  60288. ** prior to inserting new content into the Mem.
  60289. */
  60290. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  60291. assert( sqlite3VdbeCheckMemInvariants(p) );
  60292. if( VdbeMemDynamic(p) || p->szMalloc ){
  60293. vdbeMemClear(p);
  60294. }
  60295. }
  60296. /*
  60297. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  60298. ** If the double is out of range of a 64-bit signed integer then
  60299. ** return the closest available 64-bit signed integer.
  60300. */
  60301. static i64 doubleToInt64(double r){
  60302. #ifdef SQLITE_OMIT_FLOATING_POINT
  60303. /* When floating-point is omitted, double and int64 are the same thing */
  60304. return r;
  60305. #else
  60306. /*
  60307. ** Many compilers we encounter do not define constants for the
  60308. ** minimum and maximum 64-bit integers, or they define them
  60309. ** inconsistently. And many do not understand the "LL" notation.
  60310. ** So we define our own static constants here using nothing
  60311. ** larger than a 32-bit integer constant.
  60312. */
  60313. static const i64 maxInt = LARGEST_INT64;
  60314. static const i64 minInt = SMALLEST_INT64;
  60315. if( r<=(double)minInt ){
  60316. return minInt;
  60317. }else if( r>=(double)maxInt ){
  60318. return maxInt;
  60319. }else{
  60320. return (i64)r;
  60321. }
  60322. #endif
  60323. }
  60324. /*
  60325. ** Return some kind of integer value which is the best we can do
  60326. ** at representing the value that *pMem describes as an integer.
  60327. ** If pMem is an integer, then the value is exact. If pMem is
  60328. ** a floating-point then the value returned is the integer part.
  60329. ** If pMem is a string or blob, then we make an attempt to convert
  60330. ** it into an integer and return that. If pMem represents an
  60331. ** an SQL-NULL value, return 0.
  60332. **
  60333. ** If pMem represents a string value, its encoding might be changed.
  60334. */
  60335. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  60336. int flags;
  60337. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60338. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  60339. flags = pMem->flags;
  60340. if( flags & MEM_Int ){
  60341. return pMem->u.i;
  60342. }else if( flags & MEM_Real ){
  60343. return doubleToInt64(pMem->u.r);
  60344. }else if( flags & (MEM_Str|MEM_Blob) ){
  60345. i64 value = 0;
  60346. assert( pMem->z || pMem->n==0 );
  60347. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  60348. return value;
  60349. }else{
  60350. return 0;
  60351. }
  60352. }
  60353. /*
  60354. ** Return the best representation of pMem that we can get into a
  60355. ** double. If pMem is already a double or an integer, return its
  60356. ** value. If it is a string or blob, try to convert it to a double.
  60357. ** If it is a NULL, return 0.0.
  60358. */
  60359. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  60360. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60361. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  60362. if( pMem->flags & MEM_Real ){
  60363. return pMem->u.r;
  60364. }else if( pMem->flags & MEM_Int ){
  60365. return (double)pMem->u.i;
  60366. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  60367. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  60368. double val = (double)0;
  60369. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  60370. return val;
  60371. }else{
  60372. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  60373. return (double)0;
  60374. }
  60375. }
  60376. /*
  60377. ** The MEM structure is already a MEM_Real. Try to also make it a
  60378. ** MEM_Int if we can.
  60379. */
  60380. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  60381. i64 ix;
  60382. assert( pMem->flags & MEM_Real );
  60383. assert( (pMem->flags & MEM_RowSet)==0 );
  60384. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60385. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  60386. ix = doubleToInt64(pMem->u.r);
  60387. /* Only mark the value as an integer if
  60388. **
  60389. ** (1) the round-trip conversion real->int->real is a no-op, and
  60390. ** (2) The integer is neither the largest nor the smallest
  60391. ** possible integer (ticket #3922)
  60392. **
  60393. ** The second and third terms in the following conditional enforces
  60394. ** the second condition under the assumption that addition overflow causes
  60395. ** values to wrap around.
  60396. */
  60397. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  60398. pMem->u.i = ix;
  60399. MemSetTypeFlag(pMem, MEM_Int);
  60400. }
  60401. }
  60402. /*
  60403. ** Convert pMem to type integer. Invalidate any prior representations.
  60404. */
  60405. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  60406. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60407. assert( (pMem->flags & MEM_RowSet)==0 );
  60408. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  60409. pMem->u.i = sqlite3VdbeIntValue(pMem);
  60410. MemSetTypeFlag(pMem, MEM_Int);
  60411. return SQLITE_OK;
  60412. }
  60413. /*
  60414. ** Convert pMem so that it is of type MEM_Real.
  60415. ** Invalidate any prior representations.
  60416. */
  60417. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  60418. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60419. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  60420. pMem->u.r = sqlite3VdbeRealValue(pMem);
  60421. MemSetTypeFlag(pMem, MEM_Real);
  60422. return SQLITE_OK;
  60423. }
  60424. /*
  60425. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  60426. ** Invalidate any prior representations.
  60427. **
  60428. ** Every effort is made to force the conversion, even if the input
  60429. ** is a string that does not look completely like a number. Convert
  60430. ** as much of the string as we can and ignore the rest.
  60431. */
  60432. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  60433. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  60434. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  60435. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60436. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  60437. MemSetTypeFlag(pMem, MEM_Int);
  60438. }else{
  60439. pMem->u.r = sqlite3VdbeRealValue(pMem);
  60440. MemSetTypeFlag(pMem, MEM_Real);
  60441. sqlite3VdbeIntegerAffinity(pMem);
  60442. }
  60443. }
  60444. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  60445. pMem->flags &= ~(MEM_Str|MEM_Blob);
  60446. return SQLITE_OK;
  60447. }
  60448. /*
  60449. ** Cast the datatype of the value in pMem according to the affinity
  60450. ** "aff". Casting is different from applying affinity in that a cast
  60451. ** is forced. In other words, the value is converted into the desired
  60452. ** affinity even if that results in loss of data. This routine is
  60453. ** used (for example) to implement the SQL "cast()" operator.
  60454. */
  60455. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  60456. if( pMem->flags & MEM_Null ) return;
  60457. switch( aff ){
  60458. case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
  60459. if( (pMem->flags & MEM_Blob)==0 ){
  60460. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  60461. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  60462. MemSetTypeFlag(pMem, MEM_Blob);
  60463. }else{
  60464. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  60465. }
  60466. break;
  60467. }
  60468. case SQLITE_AFF_NUMERIC: {
  60469. sqlite3VdbeMemNumerify(pMem);
  60470. break;
  60471. }
  60472. case SQLITE_AFF_INTEGER: {
  60473. sqlite3VdbeMemIntegerify(pMem);
  60474. break;
  60475. }
  60476. case SQLITE_AFF_REAL: {
  60477. sqlite3VdbeMemRealify(pMem);
  60478. break;
  60479. }
  60480. default: {
  60481. assert( aff==SQLITE_AFF_TEXT );
  60482. assert( MEM_Str==(MEM_Blob>>3) );
  60483. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  60484. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  60485. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  60486. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  60487. break;
  60488. }
  60489. }
  60490. }
  60491. /*
  60492. ** Initialize bulk memory to be a consistent Mem object.
  60493. **
  60494. ** The minimum amount of initialization feasible is performed.
  60495. */
  60496. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  60497. assert( (flags & ~MEM_TypeMask)==0 );
  60498. pMem->flags = flags;
  60499. pMem->db = db;
  60500. pMem->szMalloc = 0;
  60501. }
  60502. /*
  60503. ** Delete any previous value and set the value stored in *pMem to NULL.
  60504. **
  60505. ** This routine calls the Mem.xDel destructor to dispose of values that
  60506. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  60507. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  60508. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  60509. **
  60510. ** Use this routine to reset the Mem prior to insert a new value.
  60511. **
  60512. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  60513. */
  60514. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  60515. if( VdbeMemDynamic(pMem) ){
  60516. vdbeMemClearExternAndSetNull(pMem);
  60517. }else{
  60518. pMem->flags = MEM_Null;
  60519. }
  60520. }
  60521. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  60522. sqlite3VdbeMemSetNull((Mem*)p);
  60523. }
  60524. /*
  60525. ** Delete any previous value and set the value to be a BLOB of length
  60526. ** n containing all zeros.
  60527. */
  60528. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  60529. sqlite3VdbeMemRelease(pMem);
  60530. pMem->flags = MEM_Blob|MEM_Zero;
  60531. pMem->n = 0;
  60532. if( n<0 ) n = 0;
  60533. pMem->u.nZero = n;
  60534. pMem->enc = SQLITE_UTF8;
  60535. pMem->z = 0;
  60536. }
  60537. /*
  60538. ** The pMem is known to contain content that needs to be destroyed prior
  60539. ** to a value change. So invoke the destructor, then set the value to
  60540. ** a 64-bit integer.
  60541. */
  60542. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  60543. sqlite3VdbeMemSetNull(pMem);
  60544. pMem->u.i = val;
  60545. pMem->flags = MEM_Int;
  60546. }
  60547. /*
  60548. ** Delete any previous value and set the value stored in *pMem to val,
  60549. ** manifest type INTEGER.
  60550. */
  60551. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  60552. if( VdbeMemDynamic(pMem) ){
  60553. vdbeReleaseAndSetInt64(pMem, val);
  60554. }else{
  60555. pMem->u.i = val;
  60556. pMem->flags = MEM_Int;
  60557. }
  60558. }
  60559. #ifndef SQLITE_OMIT_FLOATING_POINT
  60560. /*
  60561. ** Delete any previous value and set the value stored in *pMem to val,
  60562. ** manifest type REAL.
  60563. */
  60564. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  60565. sqlite3VdbeMemSetNull(pMem);
  60566. if( !sqlite3IsNaN(val) ){
  60567. pMem->u.r = val;
  60568. pMem->flags = MEM_Real;
  60569. }
  60570. }
  60571. #endif
  60572. /*
  60573. ** Delete any previous value and set the value of pMem to be an
  60574. ** empty boolean index.
  60575. */
  60576. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  60577. sqlite3 *db = pMem->db;
  60578. assert( db!=0 );
  60579. assert( (pMem->flags & MEM_RowSet)==0 );
  60580. sqlite3VdbeMemRelease(pMem);
  60581. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  60582. if( db->mallocFailed ){
  60583. pMem->flags = MEM_Null;
  60584. pMem->szMalloc = 0;
  60585. }else{
  60586. assert( pMem->zMalloc );
  60587. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  60588. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  60589. assert( pMem->u.pRowSet!=0 );
  60590. pMem->flags = MEM_RowSet;
  60591. }
  60592. }
  60593. /*
  60594. ** Return true if the Mem object contains a TEXT or BLOB that is
  60595. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  60596. */
  60597. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  60598. assert( p->db!=0 );
  60599. if( p->flags & (MEM_Str|MEM_Blob) ){
  60600. int n = p->n;
  60601. if( p->flags & MEM_Zero ){
  60602. n += p->u.nZero;
  60603. }
  60604. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  60605. }
  60606. return 0;
  60607. }
  60608. #ifdef SQLITE_DEBUG
  60609. /*
  60610. ** This routine prepares a memory cell for modification by breaking
  60611. ** its link to a shallow copy and by marking any current shallow
  60612. ** copies of this cell as invalid.
  60613. **
  60614. ** This is used for testing and debugging only - to make sure shallow
  60615. ** copies are not misused.
  60616. */
  60617. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  60618. int i;
  60619. Mem *pX;
  60620. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  60621. if( pX->pScopyFrom==pMem ){
  60622. pX->flags |= MEM_Undefined;
  60623. pX->pScopyFrom = 0;
  60624. }
  60625. }
  60626. pMem->pScopyFrom = 0;
  60627. }
  60628. #endif /* SQLITE_DEBUG */
  60629. /*
  60630. ** Make an shallow copy of pFrom into pTo. Prior contents of
  60631. ** pTo are freed. The pFrom->z field is not duplicated. If
  60632. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  60633. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  60634. */
  60635. static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
  60636. vdbeMemClearExternAndSetNull(pTo);
  60637. assert( !VdbeMemDynamic(pTo) );
  60638. sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
  60639. }
  60640. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  60641. assert( (pFrom->flags & MEM_RowSet)==0 );
  60642. assert( pTo->db==pFrom->db );
  60643. if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
  60644. memcpy(pTo, pFrom, MEMCELLSIZE);
  60645. if( (pFrom->flags&MEM_Static)==0 ){
  60646. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  60647. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  60648. pTo->flags |= srcType;
  60649. }
  60650. }
  60651. /*
  60652. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  60653. ** freed before the copy is made.
  60654. */
  60655. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  60656. int rc = SQLITE_OK;
  60657. /* The pFrom==0 case in the following assert() is when an sqlite3_value
  60658. ** from sqlite3_value_dup() is used as the argument
  60659. ** to sqlite3_result_value(). */
  60660. assert( pTo->db==pFrom->db || pFrom->db==0 );
  60661. assert( (pFrom->flags & MEM_RowSet)==0 );
  60662. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  60663. memcpy(pTo, pFrom, MEMCELLSIZE);
  60664. pTo->flags &= ~MEM_Dyn;
  60665. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  60666. if( 0==(pFrom->flags&MEM_Static) ){
  60667. pTo->flags |= MEM_Ephem;
  60668. rc = sqlite3VdbeMemMakeWriteable(pTo);
  60669. }
  60670. }
  60671. return rc;
  60672. }
  60673. /*
  60674. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  60675. ** freed. If pFrom contains ephemeral data, a copy is made.
  60676. **
  60677. ** pFrom contains an SQL NULL when this routine returns.
  60678. */
  60679. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  60680. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  60681. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  60682. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  60683. sqlite3VdbeMemRelease(pTo);
  60684. memcpy(pTo, pFrom, sizeof(Mem));
  60685. pFrom->flags = MEM_Null;
  60686. pFrom->szMalloc = 0;
  60687. }
  60688. /*
  60689. ** Change the value of a Mem to be a string or a BLOB.
  60690. **
  60691. ** The memory management strategy depends on the value of the xDel
  60692. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  60693. ** string is copied into a (possibly existing) buffer managed by the
  60694. ** Mem structure. Otherwise, any existing buffer is freed and the
  60695. ** pointer copied.
  60696. **
  60697. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  60698. ** size limit) then no memory allocation occurs. If the string can be
  60699. ** stored without allocating memory, then it is. If a memory allocation
  60700. ** is required to store the string, then value of pMem is unchanged. In
  60701. ** either case, SQLITE_TOOBIG is returned.
  60702. */
  60703. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  60704. Mem *pMem, /* Memory cell to set to string value */
  60705. const char *z, /* String pointer */
  60706. int n, /* Bytes in string, or negative */
  60707. u8 enc, /* Encoding of z. 0 for BLOBs */
  60708. void (*xDel)(void*) /* Destructor function */
  60709. ){
  60710. int nByte = n; /* New value for pMem->n */
  60711. int iLimit; /* Maximum allowed string or blob size */
  60712. u16 flags = 0; /* New value for pMem->flags */
  60713. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  60714. assert( (pMem->flags & MEM_RowSet)==0 );
  60715. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  60716. if( !z ){
  60717. sqlite3VdbeMemSetNull(pMem);
  60718. return SQLITE_OK;
  60719. }
  60720. if( pMem->db ){
  60721. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  60722. }else{
  60723. iLimit = SQLITE_MAX_LENGTH;
  60724. }
  60725. flags = (enc==0?MEM_Blob:MEM_Str);
  60726. if( nByte<0 ){
  60727. assert( enc!=0 );
  60728. if( enc==SQLITE_UTF8 ){
  60729. nByte = sqlite3Strlen30(z);
  60730. if( nByte>iLimit ) nByte = iLimit+1;
  60731. }else{
  60732. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  60733. }
  60734. flags |= MEM_Term;
  60735. }
  60736. /* The following block sets the new values of Mem.z and Mem.xDel. It
  60737. ** also sets a flag in local variable "flags" to indicate the memory
  60738. ** management (one of MEM_Dyn or MEM_Static).
  60739. */
  60740. if( xDel==SQLITE_TRANSIENT ){
  60741. int nAlloc = nByte;
  60742. if( flags&MEM_Term ){
  60743. nAlloc += (enc==SQLITE_UTF8?1:2);
  60744. }
  60745. if( nByte>iLimit ){
  60746. return SQLITE_TOOBIG;
  60747. }
  60748. testcase( nAlloc==0 );
  60749. testcase( nAlloc==31 );
  60750. testcase( nAlloc==32 );
  60751. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  60752. return SQLITE_NOMEM;
  60753. }
  60754. memcpy(pMem->z, z, nAlloc);
  60755. }else if( xDel==SQLITE_DYNAMIC ){
  60756. sqlite3VdbeMemRelease(pMem);
  60757. pMem->zMalloc = pMem->z = (char *)z;
  60758. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  60759. }else{
  60760. sqlite3VdbeMemRelease(pMem);
  60761. pMem->z = (char *)z;
  60762. pMem->xDel = xDel;
  60763. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  60764. }
  60765. pMem->n = nByte;
  60766. pMem->flags = flags;
  60767. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  60768. #ifndef SQLITE_OMIT_UTF16
  60769. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  60770. return SQLITE_NOMEM;
  60771. }
  60772. #endif
  60773. if( nByte>iLimit ){
  60774. return SQLITE_TOOBIG;
  60775. }
  60776. return SQLITE_OK;
  60777. }
  60778. /*
  60779. ** Move data out of a btree key or data field and into a Mem structure.
  60780. ** The data or key is taken from the entry that pCur is currently pointing
  60781. ** to. offset and amt determine what portion of the data or key to retrieve.
  60782. ** key is true to get the key or false to get data. The result is written
  60783. ** into the pMem element.
  60784. **
  60785. ** The pMem object must have been initialized. This routine will use
  60786. ** pMem->zMalloc to hold the content from the btree, if possible. New
  60787. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  60788. ** is responsible for making sure that the pMem object is eventually
  60789. ** destroyed.
  60790. **
  60791. ** If this routine fails for any reason (malloc returns NULL or unable
  60792. ** to read from the disk) then the pMem is left in an inconsistent state.
  60793. */
  60794. static SQLITE_NOINLINE int vdbeMemFromBtreeResize(
  60795. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  60796. u32 offset, /* Offset from the start of data to return bytes from. */
  60797. u32 amt, /* Number of bytes to return. */
  60798. int key, /* If true, retrieve from the btree key, not data. */
  60799. Mem *pMem /* OUT: Return data in this Mem structure. */
  60800. ){
  60801. int rc;
  60802. pMem->flags = MEM_Null;
  60803. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  60804. if( key ){
  60805. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  60806. }else{
  60807. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  60808. }
  60809. if( rc==SQLITE_OK ){
  60810. pMem->z[amt] = 0;
  60811. pMem->z[amt+1] = 0;
  60812. pMem->flags = MEM_Blob|MEM_Term;
  60813. pMem->n = (int)amt;
  60814. }else{
  60815. sqlite3VdbeMemRelease(pMem);
  60816. }
  60817. }
  60818. return rc;
  60819. }
  60820. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  60821. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  60822. u32 offset, /* Offset from the start of data to return bytes from. */
  60823. u32 amt, /* Number of bytes to return. */
  60824. int key, /* If true, retrieve from the btree key, not data. */
  60825. Mem *pMem /* OUT: Return data in this Mem structure. */
  60826. ){
  60827. char *zData; /* Data from the btree layer */
  60828. u32 available = 0; /* Number of bytes available on the local btree page */
  60829. int rc = SQLITE_OK; /* Return code */
  60830. assert( sqlite3BtreeCursorIsValid(pCur) );
  60831. assert( !VdbeMemDynamic(pMem) );
  60832. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  60833. ** that both the BtShared and database handle mutexes are held. */
  60834. assert( (pMem->flags & MEM_RowSet)==0 );
  60835. if( key ){
  60836. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  60837. }else{
  60838. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  60839. }
  60840. assert( zData!=0 );
  60841. if( offset+amt<=available ){
  60842. pMem->z = &zData[offset];
  60843. pMem->flags = MEM_Blob|MEM_Ephem;
  60844. pMem->n = (int)amt;
  60845. }else{
  60846. rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
  60847. }
  60848. return rc;
  60849. }
  60850. /*
  60851. ** The pVal argument is known to be a value other than NULL.
  60852. ** Convert it into a string with encoding enc and return a pointer
  60853. ** to a zero-terminated version of that string.
  60854. */
  60855. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  60856. assert( pVal!=0 );
  60857. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  60858. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  60859. assert( (pVal->flags & MEM_RowSet)==0 );
  60860. assert( (pVal->flags & (MEM_Null))==0 );
  60861. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  60862. pVal->flags |= MEM_Str;
  60863. if( pVal->flags & MEM_Zero ){
  60864. sqlite3VdbeMemExpandBlob(pVal);
  60865. }
  60866. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  60867. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  60868. }
  60869. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  60870. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  60871. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  60872. return 0;
  60873. }
  60874. }
  60875. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  60876. }else{
  60877. sqlite3VdbeMemStringify(pVal, enc, 0);
  60878. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  60879. }
  60880. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  60881. || pVal->db->mallocFailed );
  60882. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  60883. return pVal->z;
  60884. }else{
  60885. return 0;
  60886. }
  60887. }
  60888. /* This function is only available internally, it is not part of the
  60889. ** external API. It works in a similar way to sqlite3_value_text(),
  60890. ** except the data returned is in the encoding specified by the second
  60891. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  60892. ** SQLITE_UTF8.
  60893. **
  60894. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  60895. ** If that is the case, then the result must be aligned on an even byte
  60896. ** boundary.
  60897. */
  60898. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  60899. if( !pVal ) return 0;
  60900. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  60901. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  60902. assert( (pVal->flags & MEM_RowSet)==0 );
  60903. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  60904. return pVal->z;
  60905. }
  60906. if( pVal->flags&MEM_Null ){
  60907. return 0;
  60908. }
  60909. return valueToText(pVal, enc);
  60910. }
  60911. /*
  60912. ** Create a new sqlite3_value object.
  60913. */
  60914. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  60915. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  60916. if( p ){
  60917. p->flags = MEM_Null;
  60918. p->db = db;
  60919. }
  60920. return p;
  60921. }
  60922. /*
  60923. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  60924. ** valueNew(). See comments above valueNew() for details.
  60925. */
  60926. struct ValueNewStat4Ctx {
  60927. Parse *pParse;
  60928. Index *pIdx;
  60929. UnpackedRecord **ppRec;
  60930. int iVal;
  60931. };
  60932. /*
  60933. ** Allocate and return a pointer to a new sqlite3_value object. If
  60934. ** the second argument to this function is NULL, the object is allocated
  60935. ** by calling sqlite3ValueNew().
  60936. **
  60937. ** Otherwise, if the second argument is non-zero, then this function is
  60938. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  60939. ** already been allocated, allocate the UnpackedRecord structure that
  60940. ** that function will return to its caller here. Then return a pointer to
  60941. ** an sqlite3_value within the UnpackedRecord.a[] array.
  60942. */
  60943. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  60944. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  60945. if( p ){
  60946. UnpackedRecord *pRec = p->ppRec[0];
  60947. if( pRec==0 ){
  60948. Index *pIdx = p->pIdx; /* Index being probed */
  60949. int nByte; /* Bytes of space to allocate */
  60950. int i; /* Counter variable */
  60951. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  60952. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  60953. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  60954. if( pRec ){
  60955. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  60956. if( pRec->pKeyInfo ){
  60957. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  60958. assert( pRec->pKeyInfo->enc==ENC(db) );
  60959. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  60960. for(i=0; i<nCol; i++){
  60961. pRec->aMem[i].flags = MEM_Null;
  60962. pRec->aMem[i].db = db;
  60963. }
  60964. }else{
  60965. sqlite3DbFree(db, pRec);
  60966. pRec = 0;
  60967. }
  60968. }
  60969. if( pRec==0 ) return 0;
  60970. p->ppRec[0] = pRec;
  60971. }
  60972. pRec->nField = p->iVal+1;
  60973. return &pRec->aMem[p->iVal];
  60974. }
  60975. #else
  60976. UNUSED_PARAMETER(p);
  60977. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  60978. return sqlite3ValueNew(db);
  60979. }
  60980. /*
  60981. ** The expression object indicated by the second argument is guaranteed
  60982. ** to be a scalar SQL function. If
  60983. **
  60984. ** * all function arguments are SQL literals,
  60985. ** * the SQLITE_FUNC_CONSTANT function flag is set, and
  60986. ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
  60987. **
  60988. ** then this routine attempts to invoke the SQL function. Assuming no
  60989. ** error occurs, output parameter (*ppVal) is set to point to a value
  60990. ** object containing the result before returning SQLITE_OK.
  60991. **
  60992. ** Affinity aff is applied to the result of the function before returning.
  60993. ** If the result is a text value, the sqlite3_value object uses encoding
  60994. ** enc.
  60995. **
  60996. ** If the conditions above are not met, this function returns SQLITE_OK
  60997. ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
  60998. ** NULL and an SQLite error code returned.
  60999. */
  61000. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61001. static int valueFromFunction(
  61002. sqlite3 *db, /* The database connection */
  61003. Expr *p, /* The expression to evaluate */
  61004. u8 enc, /* Encoding to use */
  61005. u8 aff, /* Affinity to use */
  61006. sqlite3_value **ppVal, /* Write the new value here */
  61007. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  61008. ){
  61009. sqlite3_context ctx; /* Context object for function invocation */
  61010. sqlite3_value **apVal = 0; /* Function arguments */
  61011. int nVal = 0; /* Size of apVal[] array */
  61012. FuncDef *pFunc = 0; /* Function definition */
  61013. sqlite3_value *pVal = 0; /* New value */
  61014. int rc = SQLITE_OK; /* Return code */
  61015. int nName; /* Size of function name in bytes */
  61016. ExprList *pList = 0; /* Function arguments */
  61017. int i; /* Iterator variable */
  61018. assert( pCtx!=0 );
  61019. assert( (p->flags & EP_TokenOnly)==0 );
  61020. pList = p->x.pList;
  61021. if( pList ) nVal = pList->nExpr;
  61022. nName = sqlite3Strlen30(p->u.zToken);
  61023. pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
  61024. assert( pFunc );
  61025. if( (pFunc->funcFlags & SQLITE_FUNC_CONSTANT)==0
  61026. || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
  61027. ){
  61028. return SQLITE_OK;
  61029. }
  61030. if( pList ){
  61031. apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
  61032. if( apVal==0 ){
  61033. rc = SQLITE_NOMEM;
  61034. goto value_from_function_out;
  61035. }
  61036. for(i=0; i<nVal; i++){
  61037. rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
  61038. if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
  61039. }
  61040. }
  61041. pVal = valueNew(db, pCtx);
  61042. if( pVal==0 ){
  61043. rc = SQLITE_NOMEM;
  61044. goto value_from_function_out;
  61045. }
  61046. assert( pCtx->pParse->rc==SQLITE_OK );
  61047. memset(&ctx, 0, sizeof(ctx));
  61048. ctx.pOut = pVal;
  61049. ctx.pFunc = pFunc;
  61050. pFunc->xFunc(&ctx, nVal, apVal);
  61051. if( ctx.isError ){
  61052. rc = ctx.isError;
  61053. sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
  61054. }else{
  61055. sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
  61056. assert( rc==SQLITE_OK );
  61057. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  61058. if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
  61059. rc = SQLITE_TOOBIG;
  61060. pCtx->pParse->nErr++;
  61061. }
  61062. }
  61063. pCtx->pParse->rc = rc;
  61064. value_from_function_out:
  61065. if( rc!=SQLITE_OK ){
  61066. pVal = 0;
  61067. }
  61068. if( apVal ){
  61069. for(i=0; i<nVal; i++){
  61070. sqlite3ValueFree(apVal[i]);
  61071. }
  61072. sqlite3DbFree(db, apVal);
  61073. }
  61074. *ppVal = pVal;
  61075. return rc;
  61076. }
  61077. #else
  61078. # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
  61079. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  61080. /*
  61081. ** Extract a value from the supplied expression in the manner described
  61082. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  61083. ** using valueNew().
  61084. **
  61085. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  61086. ** has been allocated, it is freed before returning. Or, if pCtx is not
  61087. ** NULL, it is assumed that the caller will free any allocated object
  61088. ** in all cases.
  61089. */
  61090. static int valueFromExpr(
  61091. sqlite3 *db, /* The database connection */
  61092. Expr *pExpr, /* The expression to evaluate */
  61093. u8 enc, /* Encoding to use */
  61094. u8 affinity, /* Affinity to use */
  61095. sqlite3_value **ppVal, /* Write the new value here */
  61096. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  61097. ){
  61098. int op;
  61099. char *zVal = 0;
  61100. sqlite3_value *pVal = 0;
  61101. int negInt = 1;
  61102. const char *zNeg = "";
  61103. int rc = SQLITE_OK;
  61104. if( !pExpr ){
  61105. *ppVal = 0;
  61106. return SQLITE_OK;
  61107. }
  61108. while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
  61109. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  61110. /* Compressed expressions only appear when parsing the DEFAULT clause
  61111. ** on a table column definition, and hence only when pCtx==0. This
  61112. ** check ensures that an EP_TokenOnly expression is never passed down
  61113. ** into valueFromFunction(). */
  61114. assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
  61115. if( op==TK_CAST ){
  61116. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  61117. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  61118. testcase( rc!=SQLITE_OK );
  61119. if( *ppVal ){
  61120. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  61121. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  61122. }
  61123. return rc;
  61124. }
  61125. /* Handle negative integers in a single step. This is needed in the
  61126. ** case when the value is -9223372036854775808.
  61127. */
  61128. if( op==TK_UMINUS
  61129. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  61130. pExpr = pExpr->pLeft;
  61131. op = pExpr->op;
  61132. negInt = -1;
  61133. zNeg = "-";
  61134. }
  61135. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  61136. pVal = valueNew(db, pCtx);
  61137. if( pVal==0 ) goto no_mem;
  61138. if( ExprHasProperty(pExpr, EP_IntValue) ){
  61139. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  61140. }else{
  61141. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  61142. if( zVal==0 ) goto no_mem;
  61143. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  61144. }
  61145. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
  61146. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  61147. }else{
  61148. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  61149. }
  61150. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  61151. if( enc!=SQLITE_UTF8 ){
  61152. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  61153. }
  61154. }else if( op==TK_UMINUS ) {
  61155. /* This branch happens for multiple negative signs. Ex: -(-5) */
  61156. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  61157. && pVal!=0
  61158. ){
  61159. sqlite3VdbeMemNumerify(pVal);
  61160. if( pVal->flags & MEM_Real ){
  61161. pVal->u.r = -pVal->u.r;
  61162. }else if( pVal->u.i==SMALLEST_INT64 ){
  61163. pVal->u.r = -(double)SMALLEST_INT64;
  61164. MemSetTypeFlag(pVal, MEM_Real);
  61165. }else{
  61166. pVal->u.i = -pVal->u.i;
  61167. }
  61168. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  61169. }
  61170. }else if( op==TK_NULL ){
  61171. pVal = valueNew(db, pCtx);
  61172. if( pVal==0 ) goto no_mem;
  61173. }
  61174. #ifndef SQLITE_OMIT_BLOB_LITERAL
  61175. else if( op==TK_BLOB ){
  61176. int nVal;
  61177. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  61178. assert( pExpr->u.zToken[1]=='\'' );
  61179. pVal = valueNew(db, pCtx);
  61180. if( !pVal ) goto no_mem;
  61181. zVal = &pExpr->u.zToken[2];
  61182. nVal = sqlite3Strlen30(zVal)-1;
  61183. assert( zVal[nVal]=='\'' );
  61184. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  61185. 0, SQLITE_DYNAMIC);
  61186. }
  61187. #endif
  61188. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61189. else if( op==TK_FUNCTION && pCtx!=0 ){
  61190. rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
  61191. }
  61192. #endif
  61193. *ppVal = pVal;
  61194. return rc;
  61195. no_mem:
  61196. db->mallocFailed = 1;
  61197. sqlite3DbFree(db, zVal);
  61198. assert( *ppVal==0 );
  61199. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61200. if( pCtx==0 ) sqlite3ValueFree(pVal);
  61201. #else
  61202. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  61203. #endif
  61204. return SQLITE_NOMEM;
  61205. }
  61206. /*
  61207. ** Create a new sqlite3_value object, containing the value of pExpr.
  61208. **
  61209. ** This only works for very simple expressions that consist of one constant
  61210. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  61211. ** be converted directly into a value, then the value is allocated and
  61212. ** a pointer written to *ppVal. The caller is responsible for deallocating
  61213. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  61214. ** cannot be converted to a value, then *ppVal is set to NULL.
  61215. */
  61216. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  61217. sqlite3 *db, /* The database connection */
  61218. Expr *pExpr, /* The expression to evaluate */
  61219. u8 enc, /* Encoding to use */
  61220. u8 affinity, /* Affinity to use */
  61221. sqlite3_value **ppVal /* Write the new value here */
  61222. ){
  61223. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  61224. }
  61225. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  61226. /*
  61227. ** The implementation of the sqlite_record() function. This function accepts
  61228. ** a single argument of any type. The return value is a formatted database
  61229. ** record (a blob) containing the argument value.
  61230. **
  61231. ** This is used to convert the value stored in the 'sample' column of the
  61232. ** sqlite_stat3 table to the record format SQLite uses internally.
  61233. */
  61234. static void recordFunc(
  61235. sqlite3_context *context,
  61236. int argc,
  61237. sqlite3_value **argv
  61238. ){
  61239. const int file_format = 1;
  61240. int iSerial; /* Serial type */
  61241. int nSerial; /* Bytes of space for iSerial as varint */
  61242. int nVal; /* Bytes of space required for argv[0] */
  61243. int nRet;
  61244. sqlite3 *db;
  61245. u8 *aRet;
  61246. UNUSED_PARAMETER( argc );
  61247. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  61248. nSerial = sqlite3VarintLen(iSerial);
  61249. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  61250. db = sqlite3_context_db_handle(context);
  61251. nRet = 1 + nSerial + nVal;
  61252. aRet = sqlite3DbMallocRaw(db, nRet);
  61253. if( aRet==0 ){
  61254. sqlite3_result_error_nomem(context);
  61255. }else{
  61256. aRet[0] = nSerial+1;
  61257. putVarint32(&aRet[1], iSerial);
  61258. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  61259. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  61260. sqlite3DbFree(db, aRet);
  61261. }
  61262. }
  61263. /*
  61264. ** Register built-in functions used to help read ANALYZE data.
  61265. */
  61266. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  61267. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  61268. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  61269. };
  61270. int i;
  61271. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  61272. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  61273. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  61274. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  61275. }
  61276. }
  61277. /*
  61278. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  61279. **
  61280. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  61281. ** pAlloc if one does not exist and the new value is added to the
  61282. ** UnpackedRecord object.
  61283. **
  61284. ** A value is extracted in the following cases:
  61285. **
  61286. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  61287. **
  61288. ** * The expression is a bound variable, and this is a reprepare, or
  61289. **
  61290. ** * The expression is a literal value.
  61291. **
  61292. ** On success, *ppVal is made to point to the extracted value. The caller
  61293. ** is responsible for ensuring that the value is eventually freed.
  61294. */
  61295. static int stat4ValueFromExpr(
  61296. Parse *pParse, /* Parse context */
  61297. Expr *pExpr, /* The expression to extract a value from */
  61298. u8 affinity, /* Affinity to use */
  61299. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  61300. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  61301. ){
  61302. int rc = SQLITE_OK;
  61303. sqlite3_value *pVal = 0;
  61304. sqlite3 *db = pParse->db;
  61305. /* Skip over any TK_COLLATE nodes */
  61306. pExpr = sqlite3ExprSkipCollate(pExpr);
  61307. if( !pExpr ){
  61308. pVal = valueNew(db, pAlloc);
  61309. if( pVal ){
  61310. sqlite3VdbeMemSetNull((Mem*)pVal);
  61311. }
  61312. }else if( pExpr->op==TK_VARIABLE
  61313. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  61314. ){
  61315. Vdbe *v;
  61316. int iBindVar = pExpr->iColumn;
  61317. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  61318. if( (v = pParse->pReprepare)!=0 ){
  61319. pVal = valueNew(db, pAlloc);
  61320. if( pVal ){
  61321. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  61322. if( rc==SQLITE_OK ){
  61323. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  61324. }
  61325. pVal->db = pParse->db;
  61326. }
  61327. }
  61328. }else{
  61329. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  61330. }
  61331. assert( pVal==0 || pVal->db==db );
  61332. *ppVal = pVal;
  61333. return rc;
  61334. }
  61335. /*
  61336. ** This function is used to allocate and populate UnpackedRecord
  61337. ** structures intended to be compared against sample index keys stored
  61338. ** in the sqlite_stat4 table.
  61339. **
  61340. ** A single call to this function attempts to populates field iVal (leftmost
  61341. ** is 0 etc.) of the unpacked record with a value extracted from expression
  61342. ** pExpr. Extraction of values is possible if:
  61343. **
  61344. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  61345. **
  61346. ** * The expression is a bound variable, and this is a reprepare, or
  61347. **
  61348. ** * The sqlite3ValueFromExpr() function is able to extract a value
  61349. ** from the expression (i.e. the expression is a literal value).
  61350. **
  61351. ** If a value can be extracted, the affinity passed as the 5th argument
  61352. ** is applied to it before it is copied into the UnpackedRecord. Output
  61353. ** parameter *pbOk is set to true if a value is extracted, or false
  61354. ** otherwise.
  61355. **
  61356. ** When this function is called, *ppRec must either point to an object
  61357. ** allocated by an earlier call to this function, or must be NULL. If it
  61358. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  61359. ** is allocated (and *ppRec set to point to it) before returning.
  61360. **
  61361. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  61362. ** error if a value cannot be extracted from pExpr. If an error does
  61363. ** occur, an SQLite error code is returned.
  61364. */
  61365. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  61366. Parse *pParse, /* Parse context */
  61367. Index *pIdx, /* Index being probed */
  61368. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  61369. Expr *pExpr, /* The expression to extract a value from */
  61370. u8 affinity, /* Affinity to use */
  61371. int iVal, /* Array element to populate */
  61372. int *pbOk /* OUT: True if value was extracted */
  61373. ){
  61374. int rc;
  61375. sqlite3_value *pVal = 0;
  61376. struct ValueNewStat4Ctx alloc;
  61377. alloc.pParse = pParse;
  61378. alloc.pIdx = pIdx;
  61379. alloc.ppRec = ppRec;
  61380. alloc.iVal = iVal;
  61381. rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
  61382. assert( pVal==0 || pVal->db==pParse->db );
  61383. *pbOk = (pVal!=0);
  61384. return rc;
  61385. }
  61386. /*
  61387. ** Attempt to extract a value from expression pExpr using the methods
  61388. ** as described for sqlite3Stat4ProbeSetValue() above.
  61389. **
  61390. ** If successful, set *ppVal to point to a new value object and return
  61391. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  61392. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  61393. ** does occur, return an SQLite error code. The final value of *ppVal
  61394. ** is undefined in this case.
  61395. */
  61396. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  61397. Parse *pParse, /* Parse context */
  61398. Expr *pExpr, /* The expression to extract a value from */
  61399. u8 affinity, /* Affinity to use */
  61400. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  61401. ){
  61402. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  61403. }
  61404. /*
  61405. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  61406. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  61407. ** sqlite3_value object is allocated.
  61408. **
  61409. ** If *ppVal is initially NULL then the caller is responsible for
  61410. ** ensuring that the value written into *ppVal is eventually freed.
  61411. */
  61412. SQLITE_PRIVATE int sqlite3Stat4Column(
  61413. sqlite3 *db, /* Database handle */
  61414. const void *pRec, /* Pointer to buffer containing record */
  61415. int nRec, /* Size of buffer pRec in bytes */
  61416. int iCol, /* Column to extract */
  61417. sqlite3_value **ppVal /* OUT: Extracted value */
  61418. ){
  61419. u32 t; /* a column type code */
  61420. int nHdr; /* Size of the header in the record */
  61421. int iHdr; /* Next unread header byte */
  61422. int iField; /* Next unread data byte */
  61423. int szField; /* Size of the current data field */
  61424. int i; /* Column index */
  61425. u8 *a = (u8*)pRec; /* Typecast byte array */
  61426. Mem *pMem = *ppVal; /* Write result into this Mem object */
  61427. assert( iCol>0 );
  61428. iHdr = getVarint32(a, nHdr);
  61429. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  61430. iField = nHdr;
  61431. for(i=0; i<=iCol; i++){
  61432. iHdr += getVarint32(&a[iHdr], t);
  61433. testcase( iHdr==nHdr );
  61434. testcase( iHdr==nHdr+1 );
  61435. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  61436. szField = sqlite3VdbeSerialTypeLen(t);
  61437. iField += szField;
  61438. }
  61439. testcase( iField==nRec );
  61440. testcase( iField==nRec+1 );
  61441. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  61442. if( pMem==0 ){
  61443. pMem = *ppVal = sqlite3ValueNew(db);
  61444. if( pMem==0 ) return SQLITE_NOMEM;
  61445. }
  61446. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  61447. pMem->enc = ENC(db);
  61448. return SQLITE_OK;
  61449. }
  61450. /*
  61451. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  61452. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  61453. ** the object.
  61454. */
  61455. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  61456. if( pRec ){
  61457. int i;
  61458. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  61459. Mem *aMem = pRec->aMem;
  61460. sqlite3 *db = aMem[0].db;
  61461. for(i=0; i<nCol; i++){
  61462. sqlite3VdbeMemRelease(&aMem[i]);
  61463. }
  61464. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  61465. sqlite3DbFree(db, pRec);
  61466. }
  61467. }
  61468. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  61469. /*
  61470. ** Change the string value of an sqlite3_value object
  61471. */
  61472. SQLITE_PRIVATE void sqlite3ValueSetStr(
  61473. sqlite3_value *v, /* Value to be set */
  61474. int n, /* Length of string z */
  61475. const void *z, /* Text of the new string */
  61476. u8 enc, /* Encoding to use */
  61477. void (*xDel)(void*) /* Destructor for the string */
  61478. ){
  61479. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  61480. }
  61481. /*
  61482. ** Free an sqlite3_value object
  61483. */
  61484. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  61485. if( !v ) return;
  61486. sqlite3VdbeMemRelease((Mem *)v);
  61487. sqlite3DbFree(((Mem*)v)->db, v);
  61488. }
  61489. /*
  61490. ** The sqlite3ValueBytes() routine returns the number of bytes in the
  61491. ** sqlite3_value object assuming that it uses the encoding "enc".
  61492. ** The valueBytes() routine is a helper function.
  61493. */
  61494. static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
  61495. return valueToText(pVal, enc)!=0 ? pVal->n : 0;
  61496. }
  61497. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  61498. Mem *p = (Mem*)pVal;
  61499. assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
  61500. if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
  61501. return p->n;
  61502. }
  61503. if( (p->flags & MEM_Blob)!=0 ){
  61504. if( p->flags & MEM_Zero ){
  61505. return p->n + p->u.nZero;
  61506. }else{
  61507. return p->n;
  61508. }
  61509. }
  61510. if( p->flags & MEM_Null ) return 0;
  61511. return valueBytes(pVal, enc);
  61512. }
  61513. /************** End of vdbemem.c *********************************************/
  61514. /************** Begin file vdbeaux.c *****************************************/
  61515. /*
  61516. ** 2003 September 6
  61517. **
  61518. ** The author disclaims copyright to this source code. In place of
  61519. ** a legal notice, here is a blessing:
  61520. **
  61521. ** May you do good and not evil.
  61522. ** May you find forgiveness for yourself and forgive others.
  61523. ** May you share freely, never taking more than you give.
  61524. **
  61525. *************************************************************************
  61526. ** This file contains code used for creating, destroying, and populating
  61527. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  61528. */
  61529. /* #include "sqliteInt.h" */
  61530. /* #include "vdbeInt.h" */
  61531. /*
  61532. ** Create a new virtual database engine.
  61533. */
  61534. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  61535. sqlite3 *db = pParse->db;
  61536. Vdbe *p;
  61537. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  61538. if( p==0 ) return 0;
  61539. p->db = db;
  61540. if( db->pVdbe ){
  61541. db->pVdbe->pPrev = p;
  61542. }
  61543. p->pNext = db->pVdbe;
  61544. p->pPrev = 0;
  61545. db->pVdbe = p;
  61546. p->magic = VDBE_MAGIC_INIT;
  61547. p->pParse = pParse;
  61548. assert( pParse->aLabel==0 );
  61549. assert( pParse->nLabel==0 );
  61550. assert( pParse->nOpAlloc==0 );
  61551. return p;
  61552. }
  61553. /*
  61554. ** Change the error string stored in Vdbe.zErrMsg
  61555. */
  61556. SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
  61557. va_list ap;
  61558. sqlite3DbFree(p->db, p->zErrMsg);
  61559. va_start(ap, zFormat);
  61560. p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
  61561. va_end(ap);
  61562. }
  61563. /*
  61564. ** Remember the SQL string for a prepared statement.
  61565. */
  61566. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  61567. assert( isPrepareV2==1 || isPrepareV2==0 );
  61568. if( p==0 ) return;
  61569. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  61570. if( !isPrepareV2 ) return;
  61571. #endif
  61572. assert( p->zSql==0 );
  61573. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  61574. p->isPrepareV2 = (u8)isPrepareV2;
  61575. }
  61576. /*
  61577. ** Return the SQL associated with a prepared statement
  61578. */
  61579. SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
  61580. Vdbe *p = (Vdbe *)pStmt;
  61581. return (p && p->isPrepareV2) ? p->zSql : 0;
  61582. }
  61583. /*
  61584. ** Swap all content between two VDBE structures.
  61585. */
  61586. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  61587. Vdbe tmp, *pTmp;
  61588. char *zTmp;
  61589. tmp = *pA;
  61590. *pA = *pB;
  61591. *pB = tmp;
  61592. pTmp = pA->pNext;
  61593. pA->pNext = pB->pNext;
  61594. pB->pNext = pTmp;
  61595. pTmp = pA->pPrev;
  61596. pA->pPrev = pB->pPrev;
  61597. pB->pPrev = pTmp;
  61598. zTmp = pA->zSql;
  61599. pA->zSql = pB->zSql;
  61600. pB->zSql = zTmp;
  61601. pB->isPrepareV2 = pA->isPrepareV2;
  61602. }
  61603. /*
  61604. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  61605. ** than its current size. nOp is guaranteed to be less than or equal
  61606. ** to 1024/sizeof(Op).
  61607. **
  61608. ** If an out-of-memory error occurs while resizing the array, return
  61609. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  61610. ** unchanged (this is so that any opcodes already allocated can be
  61611. ** correctly deallocated along with the rest of the Vdbe).
  61612. */
  61613. static int growOpArray(Vdbe *v, int nOp){
  61614. VdbeOp *pNew;
  61615. Parse *p = v->pParse;
  61616. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  61617. ** more frequent reallocs and hence provide more opportunities for
  61618. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  61619. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  61620. ** by the minimum* amount required until the size reaches 512. Normal
  61621. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  61622. ** size of the op array or add 1KB of space, whichever is smaller. */
  61623. #ifdef SQLITE_TEST_REALLOC_STRESS
  61624. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  61625. #else
  61626. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  61627. UNUSED_PARAMETER(nOp);
  61628. #endif
  61629. assert( nOp<=(1024/sizeof(Op)) );
  61630. assert( nNew>=(p->nOpAlloc+nOp) );
  61631. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  61632. if( pNew ){
  61633. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  61634. v->aOp = pNew;
  61635. }
  61636. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  61637. }
  61638. #ifdef SQLITE_DEBUG
  61639. /* This routine is just a convenient place to set a breakpoint that will
  61640. ** fire after each opcode is inserted and displayed using
  61641. ** "PRAGMA vdbe_addoptrace=on".
  61642. */
  61643. static void test_addop_breakpoint(void){
  61644. static int n = 0;
  61645. n++;
  61646. }
  61647. #endif
  61648. /*
  61649. ** Add a new instruction to the list of instructions current in the
  61650. ** VDBE. Return the address of the new instruction.
  61651. **
  61652. ** Parameters:
  61653. **
  61654. ** p Pointer to the VDBE
  61655. **
  61656. ** op The opcode for this instruction
  61657. **
  61658. ** p1, p2, p3 Operands
  61659. **
  61660. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  61661. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  61662. ** operand.
  61663. */
  61664. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  61665. int i;
  61666. VdbeOp *pOp;
  61667. i = p->nOp;
  61668. assert( p->magic==VDBE_MAGIC_INIT );
  61669. assert( op>0 && op<0xff );
  61670. if( p->pParse->nOpAlloc<=i ){
  61671. if( growOpArray(p, 1) ){
  61672. return 1;
  61673. }
  61674. }
  61675. p->nOp++;
  61676. pOp = &p->aOp[i];
  61677. pOp->opcode = (u8)op;
  61678. pOp->p5 = 0;
  61679. pOp->p1 = p1;
  61680. pOp->p2 = p2;
  61681. pOp->p3 = p3;
  61682. pOp->p4.p = 0;
  61683. pOp->p4type = P4_NOTUSED;
  61684. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  61685. pOp->zComment = 0;
  61686. #endif
  61687. #ifdef SQLITE_DEBUG
  61688. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  61689. int jj, kk;
  61690. Parse *pParse = p->pParse;
  61691. for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
  61692. struct yColCache *x = pParse->aColCache + jj;
  61693. if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
  61694. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  61695. kk++;
  61696. }
  61697. if( kk ) printf("\n");
  61698. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  61699. test_addop_breakpoint();
  61700. }
  61701. #endif
  61702. #ifdef VDBE_PROFILE
  61703. pOp->cycles = 0;
  61704. pOp->cnt = 0;
  61705. #endif
  61706. #ifdef SQLITE_VDBE_COVERAGE
  61707. pOp->iSrcLine = 0;
  61708. #endif
  61709. return i;
  61710. }
  61711. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  61712. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  61713. }
  61714. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  61715. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  61716. }
  61717. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  61718. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  61719. }
  61720. /*
  61721. ** Add an opcode that includes the p4 value as a pointer.
  61722. */
  61723. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  61724. Vdbe *p, /* Add the opcode to this VM */
  61725. int op, /* The new opcode */
  61726. int p1, /* The P1 operand */
  61727. int p2, /* The P2 operand */
  61728. int p3, /* The P3 operand */
  61729. const char *zP4, /* The P4 operand */
  61730. int p4type /* P4 operand type */
  61731. ){
  61732. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  61733. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  61734. return addr;
  61735. }
  61736. /*
  61737. ** Add an opcode that includes the p4 value with a P4_INT64 type.
  61738. */
  61739. SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(
  61740. Vdbe *p, /* Add the opcode to this VM */
  61741. int op, /* The new opcode */
  61742. int p1, /* The P1 operand */
  61743. int p2, /* The P2 operand */
  61744. int p3, /* The P3 operand */
  61745. const u8 *zP4, /* The P4 operand */
  61746. int p4type /* P4 operand type */
  61747. ){
  61748. char *p4copy = sqlite3DbMallocRaw(sqlite3VdbeDb(p), 8);
  61749. if( p4copy ) memcpy(p4copy, zP4, 8);
  61750. return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
  61751. }
  61752. /*
  61753. ** Add an OP_ParseSchema opcode. This routine is broken out from
  61754. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  61755. ** as having been used.
  61756. **
  61757. ** The zWhere string must have been obtained from sqlite3_malloc().
  61758. ** This routine will take ownership of the allocated memory.
  61759. */
  61760. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  61761. int j;
  61762. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  61763. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  61764. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  61765. }
  61766. /*
  61767. ** Add an opcode that includes the p4 value as an integer.
  61768. */
  61769. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  61770. Vdbe *p, /* Add the opcode to this VM */
  61771. int op, /* The new opcode */
  61772. int p1, /* The P1 operand */
  61773. int p2, /* The P2 operand */
  61774. int p3, /* The P3 operand */
  61775. int p4 /* The P4 operand as an integer */
  61776. ){
  61777. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  61778. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  61779. return addr;
  61780. }
  61781. /*
  61782. ** Create a new symbolic label for an instruction that has yet to be
  61783. ** coded. The symbolic label is really just a negative number. The
  61784. ** label can be used as the P2 value of an operation. Later, when
  61785. ** the label is resolved to a specific address, the VDBE will scan
  61786. ** through its operation list and change all values of P2 which match
  61787. ** the label into the resolved address.
  61788. **
  61789. ** The VDBE knows that a P2 value is a label because labels are
  61790. ** always negative and P2 values are suppose to be non-negative.
  61791. ** Hence, a negative P2 value is a label that has yet to be resolved.
  61792. **
  61793. ** Zero is returned if a malloc() fails.
  61794. */
  61795. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  61796. Parse *p = v->pParse;
  61797. int i = p->nLabel++;
  61798. assert( v->magic==VDBE_MAGIC_INIT );
  61799. if( (i & (i-1))==0 ){
  61800. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  61801. (i*2+1)*sizeof(p->aLabel[0]));
  61802. }
  61803. if( p->aLabel ){
  61804. p->aLabel[i] = -1;
  61805. }
  61806. return -1-i;
  61807. }
  61808. /*
  61809. ** Resolve label "x" to be the address of the next instruction to
  61810. ** be inserted. The parameter "x" must have been obtained from
  61811. ** a prior call to sqlite3VdbeMakeLabel().
  61812. */
  61813. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  61814. Parse *p = v->pParse;
  61815. int j = -1-x;
  61816. assert( v->magic==VDBE_MAGIC_INIT );
  61817. assert( j<p->nLabel );
  61818. if( ALWAYS(j>=0) && p->aLabel ){
  61819. p->aLabel[j] = v->nOp;
  61820. }
  61821. p->iFixedOp = v->nOp - 1;
  61822. }
  61823. /*
  61824. ** Mark the VDBE as one that can only be run one time.
  61825. */
  61826. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  61827. p->runOnlyOnce = 1;
  61828. }
  61829. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  61830. /*
  61831. ** The following type and function are used to iterate through all opcodes
  61832. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  61833. ** invoke directly or indirectly. It should be used as follows:
  61834. **
  61835. ** Op *pOp;
  61836. ** VdbeOpIter sIter;
  61837. **
  61838. ** memset(&sIter, 0, sizeof(sIter));
  61839. ** sIter.v = v; // v is of type Vdbe*
  61840. ** while( (pOp = opIterNext(&sIter)) ){
  61841. ** // Do something with pOp
  61842. ** }
  61843. ** sqlite3DbFree(v->db, sIter.apSub);
  61844. **
  61845. */
  61846. typedef struct VdbeOpIter VdbeOpIter;
  61847. struct VdbeOpIter {
  61848. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  61849. SubProgram **apSub; /* Array of subprograms */
  61850. int nSub; /* Number of entries in apSub */
  61851. int iAddr; /* Address of next instruction to return */
  61852. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  61853. };
  61854. static Op *opIterNext(VdbeOpIter *p){
  61855. Vdbe *v = p->v;
  61856. Op *pRet = 0;
  61857. Op *aOp;
  61858. int nOp;
  61859. if( p->iSub<=p->nSub ){
  61860. if( p->iSub==0 ){
  61861. aOp = v->aOp;
  61862. nOp = v->nOp;
  61863. }else{
  61864. aOp = p->apSub[p->iSub-1]->aOp;
  61865. nOp = p->apSub[p->iSub-1]->nOp;
  61866. }
  61867. assert( p->iAddr<nOp );
  61868. pRet = &aOp[p->iAddr];
  61869. p->iAddr++;
  61870. if( p->iAddr==nOp ){
  61871. p->iSub++;
  61872. p->iAddr = 0;
  61873. }
  61874. if( pRet->p4type==P4_SUBPROGRAM ){
  61875. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  61876. int j;
  61877. for(j=0; j<p->nSub; j++){
  61878. if( p->apSub[j]==pRet->p4.pProgram ) break;
  61879. }
  61880. if( j==p->nSub ){
  61881. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  61882. if( !p->apSub ){
  61883. pRet = 0;
  61884. }else{
  61885. p->apSub[p->nSub++] = pRet->p4.pProgram;
  61886. }
  61887. }
  61888. }
  61889. }
  61890. return pRet;
  61891. }
  61892. /*
  61893. ** Check if the program stored in the VM associated with pParse may
  61894. ** throw an ABORT exception (causing the statement, but not entire transaction
  61895. ** to be rolled back). This condition is true if the main program or any
  61896. ** sub-programs contains any of the following:
  61897. **
  61898. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  61899. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  61900. ** * OP_Destroy
  61901. ** * OP_VUpdate
  61902. ** * OP_VRename
  61903. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  61904. ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
  61905. **
  61906. ** Then check that the value of Parse.mayAbort is true if an
  61907. ** ABORT may be thrown, or false otherwise. Return true if it does
  61908. ** match, or false otherwise. This function is intended to be used as
  61909. ** part of an assert statement in the compiler. Similar to:
  61910. **
  61911. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  61912. */
  61913. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  61914. int hasAbort = 0;
  61915. int hasFkCounter = 0;
  61916. int hasCreateTable = 0;
  61917. int hasInitCoroutine = 0;
  61918. Op *pOp;
  61919. VdbeOpIter sIter;
  61920. memset(&sIter, 0, sizeof(sIter));
  61921. sIter.v = v;
  61922. while( (pOp = opIterNext(&sIter))!=0 ){
  61923. int opcode = pOp->opcode;
  61924. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  61925. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  61926. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  61927. ){
  61928. hasAbort = 1;
  61929. break;
  61930. }
  61931. if( opcode==OP_CreateTable ) hasCreateTable = 1;
  61932. if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
  61933. #ifndef SQLITE_OMIT_FOREIGN_KEY
  61934. if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
  61935. hasFkCounter = 1;
  61936. }
  61937. #endif
  61938. }
  61939. sqlite3DbFree(v->db, sIter.apSub);
  61940. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  61941. ** If malloc failed, then the while() loop above may not have iterated
  61942. ** through all opcodes and hasAbort may be set incorrectly. Return
  61943. ** true for this case to prevent the assert() in the callers frame
  61944. ** from failing. */
  61945. return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
  61946. || (hasCreateTable && hasInitCoroutine) );
  61947. }
  61948. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  61949. /*
  61950. ** Loop through the program looking for P2 values that are negative
  61951. ** on jump instructions. Each such value is a label. Resolve the
  61952. ** label by setting the P2 value to its correct non-zero value.
  61953. **
  61954. ** This routine is called once after all opcodes have been inserted.
  61955. **
  61956. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  61957. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  61958. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  61959. **
  61960. ** The Op.opflags field is set on all opcodes.
  61961. */
  61962. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  61963. int i;
  61964. int nMaxArgs = *pMaxFuncArgs;
  61965. Op *pOp;
  61966. Parse *pParse = p->pParse;
  61967. int *aLabel = pParse->aLabel;
  61968. p->readOnly = 1;
  61969. p->bIsReader = 0;
  61970. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  61971. u8 opcode = pOp->opcode;
  61972. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  61973. ** cases from this switch! */
  61974. switch( opcode ){
  61975. case OP_Transaction: {
  61976. if( pOp->p2!=0 ) p->readOnly = 0;
  61977. /* fall thru */
  61978. }
  61979. case OP_AutoCommit:
  61980. case OP_Savepoint: {
  61981. p->bIsReader = 1;
  61982. break;
  61983. }
  61984. #ifndef SQLITE_OMIT_WAL
  61985. case OP_Checkpoint:
  61986. #endif
  61987. case OP_Vacuum:
  61988. case OP_JournalMode: {
  61989. p->readOnly = 0;
  61990. p->bIsReader = 1;
  61991. break;
  61992. }
  61993. #ifndef SQLITE_OMIT_VIRTUALTABLE
  61994. case OP_VUpdate: {
  61995. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  61996. break;
  61997. }
  61998. case OP_VFilter: {
  61999. int n;
  62000. assert( p->nOp - i >= 3 );
  62001. assert( pOp[-1].opcode==OP_Integer );
  62002. n = pOp[-1].p1;
  62003. if( n>nMaxArgs ) nMaxArgs = n;
  62004. break;
  62005. }
  62006. #endif
  62007. case OP_Next:
  62008. case OP_NextIfOpen:
  62009. case OP_SorterNext: {
  62010. pOp->p4.xAdvance = sqlite3BtreeNext;
  62011. pOp->p4type = P4_ADVANCE;
  62012. break;
  62013. }
  62014. case OP_Prev:
  62015. case OP_PrevIfOpen: {
  62016. pOp->p4.xAdvance = sqlite3BtreePrevious;
  62017. pOp->p4type = P4_ADVANCE;
  62018. break;
  62019. }
  62020. }
  62021. pOp->opflags = sqlite3OpcodeProperty[opcode];
  62022. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  62023. assert( -1-pOp->p2<pParse->nLabel );
  62024. pOp->p2 = aLabel[-1-pOp->p2];
  62025. }
  62026. }
  62027. sqlite3DbFree(p->db, pParse->aLabel);
  62028. pParse->aLabel = 0;
  62029. pParse->nLabel = 0;
  62030. *pMaxFuncArgs = nMaxArgs;
  62031. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  62032. }
  62033. /*
  62034. ** Return the address of the next instruction to be inserted.
  62035. */
  62036. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  62037. assert( p->magic==VDBE_MAGIC_INIT );
  62038. return p->nOp;
  62039. }
  62040. /*
  62041. ** This function returns a pointer to the array of opcodes associated with
  62042. ** the Vdbe passed as the first argument. It is the callers responsibility
  62043. ** to arrange for the returned array to be eventually freed using the
  62044. ** vdbeFreeOpArray() function.
  62045. **
  62046. ** Before returning, *pnOp is set to the number of entries in the returned
  62047. ** array. Also, *pnMaxArg is set to the larger of its current value and
  62048. ** the number of entries in the Vdbe.apArg[] array required to execute the
  62049. ** returned program.
  62050. */
  62051. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  62052. VdbeOp *aOp = p->aOp;
  62053. assert( aOp && !p->db->mallocFailed );
  62054. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  62055. assert( DbMaskAllZero(p->btreeMask) );
  62056. resolveP2Values(p, pnMaxArg);
  62057. *pnOp = p->nOp;
  62058. p->aOp = 0;
  62059. return aOp;
  62060. }
  62061. /*
  62062. ** Add a whole list of operations to the operation stack. Return the
  62063. ** address of the first operation added.
  62064. */
  62065. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
  62066. int addr;
  62067. assert( p->magic==VDBE_MAGIC_INIT );
  62068. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  62069. return 0;
  62070. }
  62071. addr = p->nOp;
  62072. if( ALWAYS(nOp>0) ){
  62073. int i;
  62074. VdbeOpList const *pIn = aOp;
  62075. for(i=0; i<nOp; i++, pIn++){
  62076. int p2 = pIn->p2;
  62077. VdbeOp *pOut = &p->aOp[i+addr];
  62078. pOut->opcode = pIn->opcode;
  62079. pOut->p1 = pIn->p1;
  62080. if( p2<0 ){
  62081. assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
  62082. pOut->p2 = addr + ADDR(p2);
  62083. }else{
  62084. pOut->p2 = p2;
  62085. }
  62086. pOut->p3 = pIn->p3;
  62087. pOut->p4type = P4_NOTUSED;
  62088. pOut->p4.p = 0;
  62089. pOut->p5 = 0;
  62090. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  62091. pOut->zComment = 0;
  62092. #endif
  62093. #ifdef SQLITE_VDBE_COVERAGE
  62094. pOut->iSrcLine = iLineno+i;
  62095. #else
  62096. (void)iLineno;
  62097. #endif
  62098. #ifdef SQLITE_DEBUG
  62099. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  62100. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  62101. }
  62102. #endif
  62103. }
  62104. p->nOp += nOp;
  62105. }
  62106. return addr;
  62107. }
  62108. #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  62109. /*
  62110. ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
  62111. */
  62112. SQLITE_PRIVATE void sqlite3VdbeScanStatus(
  62113. Vdbe *p, /* VM to add scanstatus() to */
  62114. int addrExplain, /* Address of OP_Explain (or 0) */
  62115. int addrLoop, /* Address of loop counter */
  62116. int addrVisit, /* Address of rows visited counter */
  62117. LogEst nEst, /* Estimated number of output rows */
  62118. const char *zName /* Name of table or index being scanned */
  62119. ){
  62120. int nByte = (p->nScan+1) * sizeof(ScanStatus);
  62121. ScanStatus *aNew;
  62122. aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
  62123. if( aNew ){
  62124. ScanStatus *pNew = &aNew[p->nScan++];
  62125. pNew->addrExplain = addrExplain;
  62126. pNew->addrLoop = addrLoop;
  62127. pNew->addrVisit = addrVisit;
  62128. pNew->nEst = nEst;
  62129. pNew->zName = sqlite3DbStrDup(p->db, zName);
  62130. p->aScan = aNew;
  62131. }
  62132. }
  62133. #endif
  62134. /*
  62135. ** Change the value of the P1 operand for a specific instruction.
  62136. ** This routine is useful when a large program is loaded from a
  62137. ** static array using sqlite3VdbeAddOpList but we want to make a
  62138. ** few minor changes to the program.
  62139. */
  62140. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  62141. assert( p!=0 );
  62142. if( ((u32)p->nOp)>addr ){
  62143. p->aOp[addr].p1 = val;
  62144. }
  62145. }
  62146. /*
  62147. ** Change the value of the P2 operand for a specific instruction.
  62148. ** This routine is useful for setting a jump destination.
  62149. */
  62150. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  62151. assert( p!=0 );
  62152. if( ((u32)p->nOp)>addr ){
  62153. p->aOp[addr].p2 = val;
  62154. }
  62155. }
  62156. /*
  62157. ** Change the value of the P3 operand for a specific instruction.
  62158. */
  62159. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  62160. assert( p!=0 );
  62161. if( ((u32)p->nOp)>addr ){
  62162. p->aOp[addr].p3 = val;
  62163. }
  62164. }
  62165. /*
  62166. ** Change the value of the P5 operand for the most recently
  62167. ** added operation.
  62168. */
  62169. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  62170. assert( p!=0 );
  62171. if( p->aOp ){
  62172. assert( p->nOp>0 );
  62173. p->aOp[p->nOp-1].p5 = val;
  62174. }
  62175. }
  62176. /*
  62177. ** Change the P2 operand of instruction addr so that it points to
  62178. ** the address of the next instruction to be coded.
  62179. */
  62180. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  62181. sqlite3VdbeChangeP2(p, addr, p->nOp);
  62182. p->pParse->iFixedOp = p->nOp - 1;
  62183. }
  62184. /*
  62185. ** If the input FuncDef structure is ephemeral, then free it. If
  62186. ** the FuncDef is not ephermal, then do nothing.
  62187. */
  62188. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  62189. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  62190. sqlite3DbFree(db, pDef);
  62191. }
  62192. }
  62193. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  62194. /*
  62195. ** Delete a P4 value if necessary.
  62196. */
  62197. static void freeP4(sqlite3 *db, int p4type, void *p4){
  62198. if( p4 ){
  62199. assert( db );
  62200. switch( p4type ){
  62201. case P4_FUNCCTX: {
  62202. freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
  62203. /* Fall through into the next case */
  62204. }
  62205. case P4_REAL:
  62206. case P4_INT64:
  62207. case P4_DYNAMIC:
  62208. case P4_INTARRAY: {
  62209. sqlite3DbFree(db, p4);
  62210. break;
  62211. }
  62212. case P4_KEYINFO: {
  62213. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  62214. break;
  62215. }
  62216. case P4_MPRINTF: {
  62217. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  62218. break;
  62219. }
  62220. case P4_FUNCDEF: {
  62221. freeEphemeralFunction(db, (FuncDef*)p4);
  62222. break;
  62223. }
  62224. case P4_MEM: {
  62225. if( db->pnBytesFreed==0 ){
  62226. sqlite3ValueFree((sqlite3_value*)p4);
  62227. }else{
  62228. Mem *p = (Mem*)p4;
  62229. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  62230. sqlite3DbFree(db, p);
  62231. }
  62232. break;
  62233. }
  62234. case P4_VTAB : {
  62235. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  62236. break;
  62237. }
  62238. }
  62239. }
  62240. }
  62241. /*
  62242. ** Free the space allocated for aOp and any p4 values allocated for the
  62243. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  62244. ** nOp entries.
  62245. */
  62246. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  62247. if( aOp ){
  62248. Op *pOp;
  62249. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  62250. freeP4(db, pOp->p4type, pOp->p4.p);
  62251. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  62252. sqlite3DbFree(db, pOp->zComment);
  62253. #endif
  62254. }
  62255. }
  62256. sqlite3DbFree(db, aOp);
  62257. }
  62258. /*
  62259. ** Link the SubProgram object passed as the second argument into the linked
  62260. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  62261. ** objects when the VM is no longer required.
  62262. */
  62263. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  62264. p->pNext = pVdbe->pProgram;
  62265. pVdbe->pProgram = p;
  62266. }
  62267. /*
  62268. ** Change the opcode at addr into OP_Noop
  62269. */
  62270. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  62271. if( addr<p->nOp ){
  62272. VdbeOp *pOp = &p->aOp[addr];
  62273. sqlite3 *db = p->db;
  62274. freeP4(db, pOp->p4type, pOp->p4.p);
  62275. memset(pOp, 0, sizeof(pOp[0]));
  62276. pOp->opcode = OP_Noop;
  62277. if( addr==p->nOp-1 ) p->nOp--;
  62278. }
  62279. }
  62280. /*
  62281. ** If the last opcode is "op" and it is not a jump destination,
  62282. ** then remove it. Return true if and only if an opcode was removed.
  62283. */
  62284. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  62285. if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
  62286. sqlite3VdbeChangeToNoop(p, p->nOp-1);
  62287. return 1;
  62288. }else{
  62289. return 0;
  62290. }
  62291. }
  62292. /*
  62293. ** Change the value of the P4 operand for a specific instruction.
  62294. ** This routine is useful when a large program is loaded from a
  62295. ** static array using sqlite3VdbeAddOpList but we want to make a
  62296. ** few minor changes to the program.
  62297. **
  62298. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  62299. ** the string is made into memory obtained from sqlite3_malloc().
  62300. ** A value of n==0 means copy bytes of zP4 up to and including the
  62301. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  62302. **
  62303. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  62304. ** to a string or structure that is guaranteed to exist for the lifetime of
  62305. ** the Vdbe. In these cases we can just copy the pointer.
  62306. **
  62307. ** If addr<0 then change P4 on the most recently inserted instruction.
  62308. */
  62309. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  62310. Op *pOp;
  62311. sqlite3 *db;
  62312. assert( p!=0 );
  62313. db = p->db;
  62314. assert( p->magic==VDBE_MAGIC_INIT );
  62315. if( p->aOp==0 || db->mallocFailed ){
  62316. if( n!=P4_VTAB ){
  62317. freeP4(db, n, (void*)*(char**)&zP4);
  62318. }
  62319. return;
  62320. }
  62321. assert( p->nOp>0 );
  62322. assert( addr<p->nOp );
  62323. if( addr<0 ){
  62324. addr = p->nOp - 1;
  62325. }
  62326. pOp = &p->aOp[addr];
  62327. assert( pOp->p4type==P4_NOTUSED
  62328. || pOp->p4type==P4_INT32
  62329. || pOp->p4type==P4_KEYINFO );
  62330. freeP4(db, pOp->p4type, pOp->p4.p);
  62331. pOp->p4.p = 0;
  62332. if( n==P4_INT32 ){
  62333. /* Note: this cast is safe, because the origin data point was an int
  62334. ** that was cast to a (const char *). */
  62335. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  62336. pOp->p4type = P4_INT32;
  62337. }else if( zP4==0 ){
  62338. pOp->p4.p = 0;
  62339. pOp->p4type = P4_NOTUSED;
  62340. }else if( n==P4_KEYINFO ){
  62341. pOp->p4.p = (void*)zP4;
  62342. pOp->p4type = P4_KEYINFO;
  62343. }else if( n==P4_VTAB ){
  62344. pOp->p4.p = (void*)zP4;
  62345. pOp->p4type = P4_VTAB;
  62346. sqlite3VtabLock((VTable *)zP4);
  62347. assert( ((VTable *)zP4)->db==p->db );
  62348. }else if( n<0 ){
  62349. pOp->p4.p = (void*)zP4;
  62350. pOp->p4type = (signed char)n;
  62351. }else{
  62352. if( n==0 ) n = sqlite3Strlen30(zP4);
  62353. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  62354. pOp->p4type = P4_DYNAMIC;
  62355. }
  62356. }
  62357. /*
  62358. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  62359. ** index given.
  62360. */
  62361. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  62362. Vdbe *v = pParse->pVdbe;
  62363. assert( v!=0 );
  62364. assert( pIdx!=0 );
  62365. sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
  62366. P4_KEYINFO);
  62367. }
  62368. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  62369. /*
  62370. ** Change the comment on the most recently coded instruction. Or
  62371. ** insert a No-op and add the comment to that new instruction. This
  62372. ** makes the code easier to read during debugging. None of this happens
  62373. ** in a production build.
  62374. */
  62375. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  62376. assert( p->nOp>0 || p->aOp==0 );
  62377. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  62378. if( p->nOp ){
  62379. assert( p->aOp );
  62380. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  62381. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  62382. }
  62383. }
  62384. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  62385. va_list ap;
  62386. if( p ){
  62387. va_start(ap, zFormat);
  62388. vdbeVComment(p, zFormat, ap);
  62389. va_end(ap);
  62390. }
  62391. }
  62392. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  62393. va_list ap;
  62394. if( p ){
  62395. sqlite3VdbeAddOp0(p, OP_Noop);
  62396. va_start(ap, zFormat);
  62397. vdbeVComment(p, zFormat, ap);
  62398. va_end(ap);
  62399. }
  62400. }
  62401. #endif /* NDEBUG */
  62402. #ifdef SQLITE_VDBE_COVERAGE
  62403. /*
  62404. ** Set the value if the iSrcLine field for the previously coded instruction.
  62405. */
  62406. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  62407. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  62408. }
  62409. #endif /* SQLITE_VDBE_COVERAGE */
  62410. /*
  62411. ** Return the opcode for a given address. If the address is -1, then
  62412. ** return the most recently inserted opcode.
  62413. **
  62414. ** If a memory allocation error has occurred prior to the calling of this
  62415. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  62416. ** is readable but not writable, though it is cast to a writable value.
  62417. ** The return of a dummy opcode allows the call to continue functioning
  62418. ** after an OOM fault without having to check to see if the return from
  62419. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  62420. ** dummy will never be written to. This is verified by code inspection and
  62421. ** by running with Valgrind.
  62422. */
  62423. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  62424. /* C89 specifies that the constant "dummy" will be initialized to all
  62425. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  62426. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  62427. assert( p->magic==VDBE_MAGIC_INIT );
  62428. if( addr<0 ){
  62429. addr = p->nOp - 1;
  62430. }
  62431. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  62432. if( p->db->mallocFailed ){
  62433. return (VdbeOp*)&dummy;
  62434. }else{
  62435. return &p->aOp[addr];
  62436. }
  62437. }
  62438. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  62439. /*
  62440. ** Return an integer value for one of the parameters to the opcode pOp
  62441. ** determined by character c.
  62442. */
  62443. static int translateP(char c, const Op *pOp){
  62444. if( c=='1' ) return pOp->p1;
  62445. if( c=='2' ) return pOp->p2;
  62446. if( c=='3' ) return pOp->p3;
  62447. if( c=='4' ) return pOp->p4.i;
  62448. return pOp->p5;
  62449. }
  62450. /*
  62451. ** Compute a string for the "comment" field of a VDBE opcode listing.
  62452. **
  62453. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  62454. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  62455. ** absence of other comments, this synopsis becomes the comment on the opcode.
  62456. ** Some translation occurs:
  62457. **
  62458. ** "PX" -> "r[X]"
  62459. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  62460. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  62461. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  62462. */
  62463. static int displayComment(
  62464. const Op *pOp, /* The opcode to be commented */
  62465. const char *zP4, /* Previously obtained value for P4 */
  62466. char *zTemp, /* Write result here */
  62467. int nTemp /* Space available in zTemp[] */
  62468. ){
  62469. const char *zOpName;
  62470. const char *zSynopsis;
  62471. int nOpName;
  62472. int ii, jj;
  62473. zOpName = sqlite3OpcodeName(pOp->opcode);
  62474. nOpName = sqlite3Strlen30(zOpName);
  62475. if( zOpName[nOpName+1] ){
  62476. int seenCom = 0;
  62477. char c;
  62478. zSynopsis = zOpName += nOpName + 1;
  62479. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  62480. if( c=='P' ){
  62481. c = zSynopsis[++ii];
  62482. if( c=='4' ){
  62483. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  62484. }else if( c=='X' ){
  62485. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  62486. seenCom = 1;
  62487. }else{
  62488. int v1 = translateP(c, pOp);
  62489. int v2;
  62490. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  62491. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  62492. ii += 3;
  62493. jj += sqlite3Strlen30(zTemp+jj);
  62494. v2 = translateP(zSynopsis[ii], pOp);
  62495. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  62496. ii += 2;
  62497. v2++;
  62498. }
  62499. if( v2>1 ){
  62500. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  62501. }
  62502. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  62503. ii += 4;
  62504. }
  62505. }
  62506. jj += sqlite3Strlen30(zTemp+jj);
  62507. }else{
  62508. zTemp[jj++] = c;
  62509. }
  62510. }
  62511. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  62512. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  62513. jj += sqlite3Strlen30(zTemp+jj);
  62514. }
  62515. if( jj<nTemp ) zTemp[jj] = 0;
  62516. }else if( pOp->zComment ){
  62517. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  62518. jj = sqlite3Strlen30(zTemp);
  62519. }else{
  62520. zTemp[0] = 0;
  62521. jj = 0;
  62522. }
  62523. return jj;
  62524. }
  62525. #endif /* SQLITE_DEBUG */
  62526. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  62527. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  62528. /*
  62529. ** Compute a string that describes the P4 parameter for an opcode.
  62530. ** Use zTemp for any required temporary buffer space.
  62531. */
  62532. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  62533. char *zP4 = zTemp;
  62534. assert( nTemp>=20 );
  62535. switch( pOp->p4type ){
  62536. case P4_KEYINFO: {
  62537. int i, j;
  62538. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  62539. assert( pKeyInfo->aSortOrder!=0 );
  62540. sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
  62541. i = sqlite3Strlen30(zTemp);
  62542. for(j=0; j<pKeyInfo->nField; j++){
  62543. CollSeq *pColl = pKeyInfo->aColl[j];
  62544. const char *zColl = pColl ? pColl->zName : "nil";
  62545. int n = sqlite3Strlen30(zColl);
  62546. if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
  62547. zColl = "B";
  62548. n = 1;
  62549. }
  62550. if( i+n>nTemp-6 ){
  62551. memcpy(&zTemp[i],",...",4);
  62552. break;
  62553. }
  62554. zTemp[i++] = ',';
  62555. if( pKeyInfo->aSortOrder[j] ){
  62556. zTemp[i++] = '-';
  62557. }
  62558. memcpy(&zTemp[i], zColl, n+1);
  62559. i += n;
  62560. }
  62561. zTemp[i++] = ')';
  62562. zTemp[i] = 0;
  62563. assert( i<nTemp );
  62564. break;
  62565. }
  62566. case P4_COLLSEQ: {
  62567. CollSeq *pColl = pOp->p4.pColl;
  62568. sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
  62569. break;
  62570. }
  62571. case P4_FUNCDEF: {
  62572. FuncDef *pDef = pOp->p4.pFunc;
  62573. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  62574. break;
  62575. }
  62576. #ifdef SQLITE_DEBUG
  62577. case P4_FUNCCTX: {
  62578. FuncDef *pDef = pOp->p4.pCtx->pFunc;
  62579. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  62580. break;
  62581. }
  62582. #endif
  62583. case P4_INT64: {
  62584. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  62585. break;
  62586. }
  62587. case P4_INT32: {
  62588. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  62589. break;
  62590. }
  62591. case P4_REAL: {
  62592. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  62593. break;
  62594. }
  62595. case P4_MEM: {
  62596. Mem *pMem = pOp->p4.pMem;
  62597. if( pMem->flags & MEM_Str ){
  62598. zP4 = pMem->z;
  62599. }else if( pMem->flags & MEM_Int ){
  62600. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  62601. }else if( pMem->flags & MEM_Real ){
  62602. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
  62603. }else if( pMem->flags & MEM_Null ){
  62604. sqlite3_snprintf(nTemp, zTemp, "NULL");
  62605. }else{
  62606. assert( pMem->flags & MEM_Blob );
  62607. zP4 = "(blob)";
  62608. }
  62609. break;
  62610. }
  62611. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62612. case P4_VTAB: {
  62613. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  62614. sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
  62615. break;
  62616. }
  62617. #endif
  62618. case P4_INTARRAY: {
  62619. sqlite3_snprintf(nTemp, zTemp, "intarray");
  62620. break;
  62621. }
  62622. case P4_SUBPROGRAM: {
  62623. sqlite3_snprintf(nTemp, zTemp, "program");
  62624. break;
  62625. }
  62626. case P4_ADVANCE: {
  62627. zTemp[0] = 0;
  62628. break;
  62629. }
  62630. default: {
  62631. zP4 = pOp->p4.z;
  62632. if( zP4==0 ){
  62633. zP4 = zTemp;
  62634. zTemp[0] = 0;
  62635. }
  62636. }
  62637. }
  62638. assert( zP4!=0 );
  62639. return zP4;
  62640. }
  62641. #endif
  62642. /*
  62643. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  62644. **
  62645. ** The prepared statements need to know in advance the complete set of
  62646. ** attached databases that will be use. A mask of these databases
  62647. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  62648. ** p->btreeMask of databases that will require a lock.
  62649. */
  62650. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  62651. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  62652. assert( i<(int)sizeof(p->btreeMask)*8 );
  62653. DbMaskSet(p->btreeMask, i);
  62654. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  62655. DbMaskSet(p->lockMask, i);
  62656. }
  62657. }
  62658. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  62659. /*
  62660. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  62661. ** this routine obtains the mutex associated with each BtShared structure
  62662. ** that may be accessed by the VM passed as an argument. In doing so it also
  62663. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  62664. ** that the correct busy-handler callback is invoked if required.
  62665. **
  62666. ** If SQLite is not threadsafe but does support shared-cache mode, then
  62667. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  62668. ** of all of BtShared structures accessible via the database handle
  62669. ** associated with the VM.
  62670. **
  62671. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  62672. ** function is a no-op.
  62673. **
  62674. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  62675. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  62676. ** corresponding to btrees that use shared cache. Then the runtime of
  62677. ** this routine is N*N. But as N is rarely more than 1, this should not
  62678. ** be a problem.
  62679. */
  62680. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  62681. int i;
  62682. sqlite3 *db;
  62683. Db *aDb;
  62684. int nDb;
  62685. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  62686. db = p->db;
  62687. aDb = db->aDb;
  62688. nDb = db->nDb;
  62689. for(i=0; i<nDb; i++){
  62690. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  62691. sqlite3BtreeEnter(aDb[i].pBt);
  62692. }
  62693. }
  62694. }
  62695. #endif
  62696. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  62697. /*
  62698. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  62699. */
  62700. static SQLITE_NOINLINE void vdbeLeave(Vdbe *p){
  62701. int i;
  62702. sqlite3 *db;
  62703. Db *aDb;
  62704. int nDb;
  62705. db = p->db;
  62706. aDb = db->aDb;
  62707. nDb = db->nDb;
  62708. for(i=0; i<nDb; i++){
  62709. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  62710. sqlite3BtreeLeave(aDb[i].pBt);
  62711. }
  62712. }
  62713. }
  62714. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  62715. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  62716. vdbeLeave(p);
  62717. }
  62718. #endif
  62719. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  62720. /*
  62721. ** Print a single opcode. This routine is used for debugging only.
  62722. */
  62723. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  62724. char *zP4;
  62725. char zPtr[50];
  62726. char zCom[100];
  62727. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  62728. if( pOut==0 ) pOut = stdout;
  62729. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  62730. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  62731. displayComment(pOp, zP4, zCom, sizeof(zCom));
  62732. #else
  62733. zCom[0] = 0;
  62734. #endif
  62735. /* NB: The sqlite3OpcodeName() function is implemented by code created
  62736. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  62737. ** information from the vdbe.c source text */
  62738. fprintf(pOut, zFormat1, pc,
  62739. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  62740. zCom
  62741. );
  62742. fflush(pOut);
  62743. }
  62744. #endif
  62745. /*
  62746. ** Release an array of N Mem elements
  62747. */
  62748. static void releaseMemArray(Mem *p, int N){
  62749. if( p && N ){
  62750. Mem *pEnd = &p[N];
  62751. sqlite3 *db = p->db;
  62752. u8 malloc_failed = db->mallocFailed;
  62753. if( db->pnBytesFreed ){
  62754. do{
  62755. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  62756. }while( (++p)<pEnd );
  62757. return;
  62758. }
  62759. do{
  62760. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  62761. assert( sqlite3VdbeCheckMemInvariants(p) );
  62762. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  62763. ** that takes advantage of the fact that the memory cell value is
  62764. ** being set to NULL after releasing any dynamic resources.
  62765. **
  62766. ** The justification for duplicating code is that according to
  62767. ** callgrind, this causes a certain test case to hit the CPU 4.7
  62768. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  62769. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  62770. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  62771. ** with no indexes using a single prepared INSERT statement, bind()
  62772. ** and reset(). Inserts are grouped into a transaction.
  62773. */
  62774. testcase( p->flags & MEM_Agg );
  62775. testcase( p->flags & MEM_Dyn );
  62776. testcase( p->flags & MEM_Frame );
  62777. testcase( p->flags & MEM_RowSet );
  62778. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  62779. sqlite3VdbeMemRelease(p);
  62780. }else if( p->szMalloc ){
  62781. sqlite3DbFree(db, p->zMalloc);
  62782. p->szMalloc = 0;
  62783. }
  62784. p->flags = MEM_Undefined;
  62785. }while( (++p)<pEnd );
  62786. db->mallocFailed = malloc_failed;
  62787. }
  62788. }
  62789. /*
  62790. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  62791. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  62792. */
  62793. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  62794. int i;
  62795. Mem *aMem = VdbeFrameMem(p);
  62796. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  62797. for(i=0; i<p->nChildCsr; i++){
  62798. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  62799. }
  62800. releaseMemArray(aMem, p->nChildMem);
  62801. sqlite3DbFree(p->v->db, p);
  62802. }
  62803. #ifndef SQLITE_OMIT_EXPLAIN
  62804. /*
  62805. ** Give a listing of the program in the virtual machine.
  62806. **
  62807. ** The interface is the same as sqlite3VdbeExec(). But instead of
  62808. ** running the code, it invokes the callback once for each instruction.
  62809. ** This feature is used to implement "EXPLAIN".
  62810. **
  62811. ** When p->explain==1, each instruction is listed. When
  62812. ** p->explain==2, only OP_Explain instructions are listed and these
  62813. ** are shown in a different format. p->explain==2 is used to implement
  62814. ** EXPLAIN QUERY PLAN.
  62815. **
  62816. ** When p->explain==1, first the main program is listed, then each of
  62817. ** the trigger subprograms are listed one by one.
  62818. */
  62819. SQLITE_PRIVATE int sqlite3VdbeList(
  62820. Vdbe *p /* The VDBE */
  62821. ){
  62822. int nRow; /* Stop when row count reaches this */
  62823. int nSub = 0; /* Number of sub-vdbes seen so far */
  62824. SubProgram **apSub = 0; /* Array of sub-vdbes */
  62825. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  62826. sqlite3 *db = p->db; /* The database connection */
  62827. int i; /* Loop counter */
  62828. int rc = SQLITE_OK; /* Return code */
  62829. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  62830. assert( p->explain );
  62831. assert( p->magic==VDBE_MAGIC_RUN );
  62832. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  62833. /* Even though this opcode does not use dynamic strings for
  62834. ** the result, result columns may become dynamic if the user calls
  62835. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  62836. */
  62837. releaseMemArray(pMem, 8);
  62838. p->pResultSet = 0;
  62839. if( p->rc==SQLITE_NOMEM ){
  62840. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  62841. ** sqlite3_column_text16() failed. */
  62842. db->mallocFailed = 1;
  62843. return SQLITE_ERROR;
  62844. }
  62845. /* When the number of output rows reaches nRow, that means the
  62846. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  62847. ** nRow is the sum of the number of rows in the main program, plus
  62848. ** the sum of the number of rows in all trigger subprograms encountered
  62849. ** so far. The nRow value will increase as new trigger subprograms are
  62850. ** encountered, but p->pc will eventually catch up to nRow.
  62851. */
  62852. nRow = p->nOp;
  62853. if( p->explain==1 ){
  62854. /* The first 8 memory cells are used for the result set. So we will
  62855. ** commandeer the 9th cell to use as storage for an array of pointers
  62856. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  62857. ** cells. */
  62858. assert( p->nMem>9 );
  62859. pSub = &p->aMem[9];
  62860. if( pSub->flags&MEM_Blob ){
  62861. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  62862. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  62863. nSub = pSub->n/sizeof(Vdbe*);
  62864. apSub = (SubProgram **)pSub->z;
  62865. }
  62866. for(i=0; i<nSub; i++){
  62867. nRow += apSub[i]->nOp;
  62868. }
  62869. }
  62870. do{
  62871. i = p->pc++;
  62872. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  62873. if( i>=nRow ){
  62874. p->rc = SQLITE_OK;
  62875. rc = SQLITE_DONE;
  62876. }else if( db->u1.isInterrupted ){
  62877. p->rc = SQLITE_INTERRUPT;
  62878. rc = SQLITE_ERROR;
  62879. sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
  62880. }else{
  62881. char *zP4;
  62882. Op *pOp;
  62883. if( i<p->nOp ){
  62884. /* The output line number is small enough that we are still in the
  62885. ** main program. */
  62886. pOp = &p->aOp[i];
  62887. }else{
  62888. /* We are currently listing subprograms. Figure out which one and
  62889. ** pick up the appropriate opcode. */
  62890. int j;
  62891. i -= p->nOp;
  62892. for(j=0; i>=apSub[j]->nOp; j++){
  62893. i -= apSub[j]->nOp;
  62894. }
  62895. pOp = &apSub[j]->aOp[i];
  62896. }
  62897. if( p->explain==1 ){
  62898. pMem->flags = MEM_Int;
  62899. pMem->u.i = i; /* Program counter */
  62900. pMem++;
  62901. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  62902. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  62903. assert( pMem->z!=0 );
  62904. pMem->n = sqlite3Strlen30(pMem->z);
  62905. pMem->enc = SQLITE_UTF8;
  62906. pMem++;
  62907. /* When an OP_Program opcode is encounter (the only opcode that has
  62908. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  62909. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  62910. ** has not already been seen.
  62911. */
  62912. if( pOp->p4type==P4_SUBPROGRAM ){
  62913. int nByte = (nSub+1)*sizeof(SubProgram*);
  62914. int j;
  62915. for(j=0; j<nSub; j++){
  62916. if( apSub[j]==pOp->p4.pProgram ) break;
  62917. }
  62918. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  62919. apSub = (SubProgram **)pSub->z;
  62920. apSub[nSub++] = pOp->p4.pProgram;
  62921. pSub->flags |= MEM_Blob;
  62922. pSub->n = nSub*sizeof(SubProgram*);
  62923. }
  62924. }
  62925. }
  62926. pMem->flags = MEM_Int;
  62927. pMem->u.i = pOp->p1; /* P1 */
  62928. pMem++;
  62929. pMem->flags = MEM_Int;
  62930. pMem->u.i = pOp->p2; /* P2 */
  62931. pMem++;
  62932. pMem->flags = MEM_Int;
  62933. pMem->u.i = pOp->p3; /* P3 */
  62934. pMem++;
  62935. if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
  62936. assert( p->db->mallocFailed );
  62937. return SQLITE_ERROR;
  62938. }
  62939. pMem->flags = MEM_Str|MEM_Term;
  62940. zP4 = displayP4(pOp, pMem->z, 32);
  62941. if( zP4!=pMem->z ){
  62942. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  62943. }else{
  62944. assert( pMem->z!=0 );
  62945. pMem->n = sqlite3Strlen30(pMem->z);
  62946. pMem->enc = SQLITE_UTF8;
  62947. }
  62948. pMem++;
  62949. if( p->explain==1 ){
  62950. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  62951. assert( p->db->mallocFailed );
  62952. return SQLITE_ERROR;
  62953. }
  62954. pMem->flags = MEM_Str|MEM_Term;
  62955. pMem->n = 2;
  62956. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  62957. pMem->enc = SQLITE_UTF8;
  62958. pMem++;
  62959. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  62960. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  62961. assert( p->db->mallocFailed );
  62962. return SQLITE_ERROR;
  62963. }
  62964. pMem->flags = MEM_Str|MEM_Term;
  62965. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  62966. pMem->enc = SQLITE_UTF8;
  62967. #else
  62968. pMem->flags = MEM_Null; /* Comment */
  62969. #endif
  62970. }
  62971. p->nResColumn = 8 - 4*(p->explain-1);
  62972. p->pResultSet = &p->aMem[1];
  62973. p->rc = SQLITE_OK;
  62974. rc = SQLITE_ROW;
  62975. }
  62976. return rc;
  62977. }
  62978. #endif /* SQLITE_OMIT_EXPLAIN */
  62979. #ifdef SQLITE_DEBUG
  62980. /*
  62981. ** Print the SQL that was used to generate a VDBE program.
  62982. */
  62983. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  62984. const char *z = 0;
  62985. if( p->zSql ){
  62986. z = p->zSql;
  62987. }else if( p->nOp>=1 ){
  62988. const VdbeOp *pOp = &p->aOp[0];
  62989. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  62990. z = pOp->p4.z;
  62991. while( sqlite3Isspace(*z) ) z++;
  62992. }
  62993. }
  62994. if( z ) printf("SQL: [%s]\n", z);
  62995. }
  62996. #endif
  62997. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  62998. /*
  62999. ** Print an IOTRACE message showing SQL content.
  63000. */
  63001. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  63002. int nOp = p->nOp;
  63003. VdbeOp *pOp;
  63004. if( sqlite3IoTrace==0 ) return;
  63005. if( nOp<1 ) return;
  63006. pOp = &p->aOp[0];
  63007. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  63008. int i, j;
  63009. char z[1000];
  63010. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  63011. for(i=0; sqlite3Isspace(z[i]); i++){}
  63012. for(j=0; z[i]; i++){
  63013. if( sqlite3Isspace(z[i]) ){
  63014. if( z[i-1]!=' ' ){
  63015. z[j++] = ' ';
  63016. }
  63017. }else{
  63018. z[j++] = z[i];
  63019. }
  63020. }
  63021. z[j] = 0;
  63022. sqlite3IoTrace("SQL %s\n", z);
  63023. }
  63024. }
  63025. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  63026. /*
  63027. ** Allocate space from a fixed size buffer and return a pointer to
  63028. ** that space. If insufficient space is available, return NULL.
  63029. **
  63030. ** The pBuf parameter is the initial value of a pointer which will
  63031. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  63032. ** NULL, it means that memory space has already been allocated and that
  63033. ** this routine should not allocate any new memory. When pBuf is not
  63034. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  63035. ** is NULL.
  63036. **
  63037. ** nByte is the number of bytes of space needed.
  63038. **
  63039. ** *ppFrom points to available space and pEnd points to the end of the
  63040. ** available space. When space is allocated, *ppFrom is advanced past
  63041. ** the end of the allocated space.
  63042. **
  63043. ** *pnByte is a counter of the number of bytes of space that have failed
  63044. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  63045. ** request, then increment *pnByte by the amount of the request.
  63046. */
  63047. static void *allocSpace(
  63048. void *pBuf, /* Where return pointer will be stored */
  63049. int nByte, /* Number of bytes to allocate */
  63050. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  63051. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  63052. int *pnByte /* If allocation cannot be made, increment *pnByte */
  63053. ){
  63054. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  63055. if( pBuf ) return pBuf;
  63056. nByte = ROUND8(nByte);
  63057. if( &(*ppFrom)[nByte] <= pEnd ){
  63058. pBuf = (void*)*ppFrom;
  63059. *ppFrom += nByte;
  63060. }else{
  63061. *pnByte += nByte;
  63062. }
  63063. return pBuf;
  63064. }
  63065. /*
  63066. ** Rewind the VDBE back to the beginning in preparation for
  63067. ** running it.
  63068. */
  63069. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  63070. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  63071. int i;
  63072. #endif
  63073. assert( p!=0 );
  63074. assert( p->magic==VDBE_MAGIC_INIT );
  63075. /* There should be at least one opcode.
  63076. */
  63077. assert( p->nOp>0 );
  63078. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  63079. p->magic = VDBE_MAGIC_RUN;
  63080. #ifdef SQLITE_DEBUG
  63081. for(i=1; i<p->nMem; i++){
  63082. assert( p->aMem[i].db==p->db );
  63083. }
  63084. #endif
  63085. p->pc = -1;
  63086. p->rc = SQLITE_OK;
  63087. p->errorAction = OE_Abort;
  63088. p->magic = VDBE_MAGIC_RUN;
  63089. p->nChange = 0;
  63090. p->cacheCtr = 1;
  63091. p->minWriteFileFormat = 255;
  63092. p->iStatement = 0;
  63093. p->nFkConstraint = 0;
  63094. #ifdef VDBE_PROFILE
  63095. for(i=0; i<p->nOp; i++){
  63096. p->aOp[i].cnt = 0;
  63097. p->aOp[i].cycles = 0;
  63098. }
  63099. #endif
  63100. }
  63101. /*
  63102. ** Prepare a virtual machine for execution for the first time after
  63103. ** creating the virtual machine. This involves things such
  63104. ** as allocating registers and initializing the program counter.
  63105. ** After the VDBE has be prepped, it can be executed by one or more
  63106. ** calls to sqlite3VdbeExec().
  63107. **
  63108. ** This function may be called exactly once on each virtual machine.
  63109. ** After this routine is called the VM has been "packaged" and is ready
  63110. ** to run. After this routine is called, further calls to
  63111. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  63112. ** the Vdbe from the Parse object that helped generate it so that the
  63113. ** the Vdbe becomes an independent entity and the Parse object can be
  63114. ** destroyed.
  63115. **
  63116. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  63117. ** to its initial state after it has been run.
  63118. */
  63119. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  63120. Vdbe *p, /* The VDBE */
  63121. Parse *pParse /* Parsing context */
  63122. ){
  63123. sqlite3 *db; /* The database connection */
  63124. int nVar; /* Number of parameters */
  63125. int nMem; /* Number of VM memory registers */
  63126. int nCursor; /* Number of cursors required */
  63127. int nArg; /* Number of arguments in subprograms */
  63128. int nOnce; /* Number of OP_Once instructions */
  63129. int n; /* Loop counter */
  63130. u8 *zCsr; /* Memory available for allocation */
  63131. u8 *zEnd; /* First byte past allocated memory */
  63132. int nByte; /* How much extra memory is needed */
  63133. assert( p!=0 );
  63134. assert( p->nOp>0 );
  63135. assert( pParse!=0 );
  63136. assert( p->magic==VDBE_MAGIC_INIT );
  63137. assert( pParse==p->pParse );
  63138. db = p->db;
  63139. assert( db->mallocFailed==0 );
  63140. nVar = pParse->nVar;
  63141. nMem = pParse->nMem;
  63142. nCursor = pParse->nTab;
  63143. nArg = pParse->nMaxArg;
  63144. nOnce = pParse->nOnce;
  63145. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  63146. /* For each cursor required, also allocate a memory cell. Memory
  63147. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  63148. ** the vdbe program. Instead they are used to allocate space for
  63149. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  63150. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  63151. ** stores the blob of memory associated with cursor 1, etc.
  63152. **
  63153. ** See also: allocateCursor().
  63154. */
  63155. nMem += nCursor;
  63156. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  63157. ** an array to marshal SQL function arguments in.
  63158. */
  63159. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  63160. zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
  63161. resolveP2Values(p, &nArg);
  63162. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  63163. if( pParse->explain && nMem<10 ){
  63164. nMem = 10;
  63165. }
  63166. memset(zCsr, 0, zEnd-zCsr);
  63167. zCsr += (zCsr - (u8*)0)&7;
  63168. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  63169. p->expired = 0;
  63170. /* Memory for registers, parameters, cursor, etc, is allocated in two
  63171. ** passes. On the first pass, we try to reuse unused space at the
  63172. ** end of the opcode array. If we are unable to satisfy all memory
  63173. ** requirements by reusing the opcode array tail, then the second
  63174. ** pass will fill in the rest using a fresh allocation.
  63175. **
  63176. ** This two-pass approach that reuses as much memory as possible from
  63177. ** the leftover space at the end of the opcode array can significantly
  63178. ** reduce the amount of memory held by a prepared statement.
  63179. */
  63180. do {
  63181. nByte = 0;
  63182. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  63183. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  63184. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  63185. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  63186. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  63187. &zCsr, zEnd, &nByte);
  63188. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  63189. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  63190. p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
  63191. #endif
  63192. if( nByte ){
  63193. p->pFree = sqlite3DbMallocZero(db, nByte);
  63194. }
  63195. zCsr = p->pFree;
  63196. zEnd = &zCsr[nByte];
  63197. }while( nByte && !db->mallocFailed );
  63198. p->nCursor = nCursor;
  63199. p->nOnceFlag = nOnce;
  63200. if( p->aVar ){
  63201. p->nVar = (ynVar)nVar;
  63202. for(n=0; n<nVar; n++){
  63203. p->aVar[n].flags = MEM_Null;
  63204. p->aVar[n].db = db;
  63205. }
  63206. }
  63207. if( p->azVar && pParse->nzVar>0 ){
  63208. p->nzVar = pParse->nzVar;
  63209. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  63210. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  63211. }
  63212. if( p->aMem ){
  63213. p->aMem--; /* aMem[] goes from 1..nMem */
  63214. p->nMem = nMem; /* not from 0..nMem-1 */
  63215. for(n=1; n<=nMem; n++){
  63216. p->aMem[n].flags = MEM_Undefined;
  63217. p->aMem[n].db = db;
  63218. }
  63219. }
  63220. p->explain = pParse->explain;
  63221. sqlite3VdbeRewind(p);
  63222. }
  63223. /*
  63224. ** Close a VDBE cursor and release all the resources that cursor
  63225. ** happens to hold.
  63226. */
  63227. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  63228. if( pCx==0 ){
  63229. return;
  63230. }
  63231. sqlite3VdbeSorterClose(p->db, pCx);
  63232. if( pCx->pBt ){
  63233. sqlite3BtreeClose(pCx->pBt);
  63234. /* The pCx->pCursor will be close automatically, if it exists, by
  63235. ** the call above. */
  63236. }else if( pCx->pCursor ){
  63237. sqlite3BtreeCloseCursor(pCx->pCursor);
  63238. }
  63239. #ifndef SQLITE_OMIT_VIRTUALTABLE
  63240. else if( pCx->pVtabCursor ){
  63241. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  63242. const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
  63243. assert( pVtabCursor->pVtab->nRef>0 );
  63244. pVtabCursor->pVtab->nRef--;
  63245. pModule->xClose(pVtabCursor);
  63246. }
  63247. #endif
  63248. }
  63249. /*
  63250. ** Close all cursors in the current frame.
  63251. */
  63252. static void closeCursorsInFrame(Vdbe *p){
  63253. if( p->apCsr ){
  63254. int i;
  63255. for(i=0; i<p->nCursor; i++){
  63256. VdbeCursor *pC = p->apCsr[i];
  63257. if( pC ){
  63258. sqlite3VdbeFreeCursor(p, pC);
  63259. p->apCsr[i] = 0;
  63260. }
  63261. }
  63262. }
  63263. }
  63264. /*
  63265. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  63266. ** is used, for example, when a trigger sub-program is halted to restore
  63267. ** control to the main program.
  63268. */
  63269. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  63270. Vdbe *v = pFrame->v;
  63271. closeCursorsInFrame(v);
  63272. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  63273. v->anExec = pFrame->anExec;
  63274. #endif
  63275. v->aOnceFlag = pFrame->aOnceFlag;
  63276. v->nOnceFlag = pFrame->nOnceFlag;
  63277. v->aOp = pFrame->aOp;
  63278. v->nOp = pFrame->nOp;
  63279. v->aMem = pFrame->aMem;
  63280. v->nMem = pFrame->nMem;
  63281. v->apCsr = pFrame->apCsr;
  63282. v->nCursor = pFrame->nCursor;
  63283. v->db->lastRowid = pFrame->lastRowid;
  63284. v->nChange = pFrame->nChange;
  63285. v->db->nChange = pFrame->nDbChange;
  63286. return pFrame->pc;
  63287. }
  63288. /*
  63289. ** Close all cursors.
  63290. **
  63291. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  63292. ** cell array. This is necessary as the memory cell array may contain
  63293. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  63294. ** open cursors.
  63295. */
  63296. static void closeAllCursors(Vdbe *p){
  63297. if( p->pFrame ){
  63298. VdbeFrame *pFrame;
  63299. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  63300. sqlite3VdbeFrameRestore(pFrame);
  63301. p->pFrame = 0;
  63302. p->nFrame = 0;
  63303. }
  63304. assert( p->nFrame==0 );
  63305. closeCursorsInFrame(p);
  63306. if( p->aMem ){
  63307. releaseMemArray(&p->aMem[1], p->nMem);
  63308. }
  63309. while( p->pDelFrame ){
  63310. VdbeFrame *pDel = p->pDelFrame;
  63311. p->pDelFrame = pDel->pParent;
  63312. sqlite3VdbeFrameDelete(pDel);
  63313. }
  63314. /* Delete any auxdata allocations made by the VM */
  63315. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
  63316. assert( p->pAuxData==0 );
  63317. }
  63318. /*
  63319. ** Clean up the VM after a single run.
  63320. */
  63321. static void Cleanup(Vdbe *p){
  63322. sqlite3 *db = p->db;
  63323. #ifdef SQLITE_DEBUG
  63324. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  63325. ** Vdbe.aMem[] arrays have already been cleaned up. */
  63326. int i;
  63327. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  63328. if( p->aMem ){
  63329. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  63330. }
  63331. #endif
  63332. sqlite3DbFree(db, p->zErrMsg);
  63333. p->zErrMsg = 0;
  63334. p->pResultSet = 0;
  63335. }
  63336. /*
  63337. ** Set the number of result columns that will be returned by this SQL
  63338. ** statement. This is now set at compile time, rather than during
  63339. ** execution of the vdbe program so that sqlite3_column_count() can
  63340. ** be called on an SQL statement before sqlite3_step().
  63341. */
  63342. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  63343. Mem *pColName;
  63344. int n;
  63345. sqlite3 *db = p->db;
  63346. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  63347. sqlite3DbFree(db, p->aColName);
  63348. n = nResColumn*COLNAME_N;
  63349. p->nResColumn = (u16)nResColumn;
  63350. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  63351. if( p->aColName==0 ) return;
  63352. while( n-- > 0 ){
  63353. pColName->flags = MEM_Null;
  63354. pColName->db = p->db;
  63355. pColName++;
  63356. }
  63357. }
  63358. /*
  63359. ** Set the name of the idx'th column to be returned by the SQL statement.
  63360. ** zName must be a pointer to a nul terminated string.
  63361. **
  63362. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  63363. **
  63364. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  63365. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  63366. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  63367. */
  63368. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  63369. Vdbe *p, /* Vdbe being configured */
  63370. int idx, /* Index of column zName applies to */
  63371. int var, /* One of the COLNAME_* constants */
  63372. const char *zName, /* Pointer to buffer containing name */
  63373. void (*xDel)(void*) /* Memory management strategy for zName */
  63374. ){
  63375. int rc;
  63376. Mem *pColName;
  63377. assert( idx<p->nResColumn );
  63378. assert( var<COLNAME_N );
  63379. if( p->db->mallocFailed ){
  63380. assert( !zName || xDel!=SQLITE_DYNAMIC );
  63381. return SQLITE_NOMEM;
  63382. }
  63383. assert( p->aColName!=0 );
  63384. pColName = &(p->aColName[idx+var*p->nResColumn]);
  63385. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  63386. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  63387. return rc;
  63388. }
  63389. /*
  63390. ** A read or write transaction may or may not be active on database handle
  63391. ** db. If a transaction is active, commit it. If there is a
  63392. ** write-transaction spanning more than one database file, this routine
  63393. ** takes care of the master journal trickery.
  63394. */
  63395. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  63396. int i;
  63397. int nTrans = 0; /* Number of databases with an active write-transaction */
  63398. int rc = SQLITE_OK;
  63399. int needXcommit = 0;
  63400. #ifdef SQLITE_OMIT_VIRTUALTABLE
  63401. /* With this option, sqlite3VtabSync() is defined to be simply
  63402. ** SQLITE_OK so p is not used.
  63403. */
  63404. UNUSED_PARAMETER(p);
  63405. #endif
  63406. /* Before doing anything else, call the xSync() callback for any
  63407. ** virtual module tables written in this transaction. This has to
  63408. ** be done before determining whether a master journal file is
  63409. ** required, as an xSync() callback may add an attached database
  63410. ** to the transaction.
  63411. */
  63412. rc = sqlite3VtabSync(db, p);
  63413. /* This loop determines (a) if the commit hook should be invoked and
  63414. ** (b) how many database files have open write transactions, not
  63415. ** including the temp database. (b) is important because if more than
  63416. ** one database file has an open write transaction, a master journal
  63417. ** file is required for an atomic commit.
  63418. */
  63419. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  63420. Btree *pBt = db->aDb[i].pBt;
  63421. if( sqlite3BtreeIsInTrans(pBt) ){
  63422. needXcommit = 1;
  63423. if( i!=1 ) nTrans++;
  63424. sqlite3BtreeEnter(pBt);
  63425. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  63426. sqlite3BtreeLeave(pBt);
  63427. }
  63428. }
  63429. if( rc!=SQLITE_OK ){
  63430. return rc;
  63431. }
  63432. /* If there are any write-transactions at all, invoke the commit hook */
  63433. if( needXcommit && db->xCommitCallback ){
  63434. rc = db->xCommitCallback(db->pCommitArg);
  63435. if( rc ){
  63436. return SQLITE_CONSTRAINT_COMMITHOOK;
  63437. }
  63438. }
  63439. /* The simple case - no more than one database file (not counting the
  63440. ** TEMP database) has a transaction active. There is no need for the
  63441. ** master-journal.
  63442. **
  63443. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  63444. ** string, it means the main database is :memory: or a temp file. In
  63445. ** that case we do not support atomic multi-file commits, so use the
  63446. ** simple case then too.
  63447. */
  63448. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  63449. || nTrans<=1
  63450. ){
  63451. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  63452. Btree *pBt = db->aDb[i].pBt;
  63453. if( pBt ){
  63454. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  63455. }
  63456. }
  63457. /* Do the commit only if all databases successfully complete phase 1.
  63458. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  63459. ** IO error while deleting or truncating a journal file. It is unlikely,
  63460. ** but could happen. In this case abandon processing and return the error.
  63461. */
  63462. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  63463. Btree *pBt = db->aDb[i].pBt;
  63464. if( pBt ){
  63465. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  63466. }
  63467. }
  63468. if( rc==SQLITE_OK ){
  63469. sqlite3VtabCommit(db);
  63470. }
  63471. }
  63472. /* The complex case - There is a multi-file write-transaction active.
  63473. ** This requires a master journal file to ensure the transaction is
  63474. ** committed atomically.
  63475. */
  63476. #ifndef SQLITE_OMIT_DISKIO
  63477. else{
  63478. sqlite3_vfs *pVfs = db->pVfs;
  63479. int needSync = 0;
  63480. char *zMaster = 0; /* File-name for the master journal */
  63481. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  63482. sqlite3_file *pMaster = 0;
  63483. i64 offset = 0;
  63484. int res;
  63485. int retryCount = 0;
  63486. int nMainFile;
  63487. /* Select a master journal file name */
  63488. nMainFile = sqlite3Strlen30(zMainFile);
  63489. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  63490. if( zMaster==0 ) return SQLITE_NOMEM;
  63491. do {
  63492. u32 iRandom;
  63493. if( retryCount ){
  63494. if( retryCount>100 ){
  63495. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  63496. sqlite3OsDelete(pVfs, zMaster, 0);
  63497. break;
  63498. }else if( retryCount==1 ){
  63499. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  63500. }
  63501. }
  63502. retryCount++;
  63503. sqlite3_randomness(sizeof(iRandom), &iRandom);
  63504. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  63505. (iRandom>>8)&0xffffff, iRandom&0xff);
  63506. /* The antipenultimate character of the master journal name must
  63507. ** be "9" to avoid name collisions when using 8+3 filenames. */
  63508. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  63509. sqlite3FileSuffix3(zMainFile, zMaster);
  63510. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  63511. }while( rc==SQLITE_OK && res );
  63512. if( rc==SQLITE_OK ){
  63513. /* Open the master journal. */
  63514. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  63515. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  63516. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  63517. );
  63518. }
  63519. if( rc!=SQLITE_OK ){
  63520. sqlite3DbFree(db, zMaster);
  63521. return rc;
  63522. }
  63523. /* Write the name of each database file in the transaction into the new
  63524. ** master journal file. If an error occurs at this point close
  63525. ** and delete the master journal file. All the individual journal files
  63526. ** still have 'null' as the master journal pointer, so they will roll
  63527. ** back independently if a failure occurs.
  63528. */
  63529. for(i=0; i<db->nDb; i++){
  63530. Btree *pBt = db->aDb[i].pBt;
  63531. if( sqlite3BtreeIsInTrans(pBt) ){
  63532. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  63533. if( zFile==0 ){
  63534. continue; /* Ignore TEMP and :memory: databases */
  63535. }
  63536. assert( zFile[0]!=0 );
  63537. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  63538. needSync = 1;
  63539. }
  63540. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  63541. offset += sqlite3Strlen30(zFile)+1;
  63542. if( rc!=SQLITE_OK ){
  63543. sqlite3OsCloseFree(pMaster);
  63544. sqlite3OsDelete(pVfs, zMaster, 0);
  63545. sqlite3DbFree(db, zMaster);
  63546. return rc;
  63547. }
  63548. }
  63549. }
  63550. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  63551. ** flag is set this is not required.
  63552. */
  63553. if( needSync
  63554. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  63555. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  63556. ){
  63557. sqlite3OsCloseFree(pMaster);
  63558. sqlite3OsDelete(pVfs, zMaster, 0);
  63559. sqlite3DbFree(db, zMaster);
  63560. return rc;
  63561. }
  63562. /* Sync all the db files involved in the transaction. The same call
  63563. ** sets the master journal pointer in each individual journal. If
  63564. ** an error occurs here, do not delete the master journal file.
  63565. **
  63566. ** If the error occurs during the first call to
  63567. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  63568. ** master journal file will be orphaned. But we cannot delete it,
  63569. ** in case the master journal file name was written into the journal
  63570. ** file before the failure occurred.
  63571. */
  63572. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  63573. Btree *pBt = db->aDb[i].pBt;
  63574. if( pBt ){
  63575. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  63576. }
  63577. }
  63578. sqlite3OsCloseFree(pMaster);
  63579. assert( rc!=SQLITE_BUSY );
  63580. if( rc!=SQLITE_OK ){
  63581. sqlite3DbFree(db, zMaster);
  63582. return rc;
  63583. }
  63584. /* Delete the master journal file. This commits the transaction. After
  63585. ** doing this the directory is synced again before any individual
  63586. ** transaction files are deleted.
  63587. */
  63588. rc = sqlite3OsDelete(pVfs, zMaster, needSync);
  63589. sqlite3DbFree(db, zMaster);
  63590. zMaster = 0;
  63591. if( rc ){
  63592. return rc;
  63593. }
  63594. /* All files and directories have already been synced, so the following
  63595. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  63596. ** deleting or truncating journals. If something goes wrong while
  63597. ** this is happening we don't really care. The integrity of the
  63598. ** transaction is already guaranteed, but some stray 'cold' journals
  63599. ** may be lying around. Returning an error code won't help matters.
  63600. */
  63601. disable_simulated_io_errors();
  63602. sqlite3BeginBenignMalloc();
  63603. for(i=0; i<db->nDb; i++){
  63604. Btree *pBt = db->aDb[i].pBt;
  63605. if( pBt ){
  63606. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  63607. }
  63608. }
  63609. sqlite3EndBenignMalloc();
  63610. enable_simulated_io_errors();
  63611. sqlite3VtabCommit(db);
  63612. }
  63613. #endif
  63614. return rc;
  63615. }
  63616. /*
  63617. ** This routine checks that the sqlite3.nVdbeActive count variable
  63618. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  63619. ** currently active. An assertion fails if the two counts do not match.
  63620. ** This is an internal self-check only - it is not an essential processing
  63621. ** step.
  63622. **
  63623. ** This is a no-op if NDEBUG is defined.
  63624. */
  63625. #ifndef NDEBUG
  63626. static void checkActiveVdbeCnt(sqlite3 *db){
  63627. Vdbe *p;
  63628. int cnt = 0;
  63629. int nWrite = 0;
  63630. int nRead = 0;
  63631. p = db->pVdbe;
  63632. while( p ){
  63633. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  63634. cnt++;
  63635. if( p->readOnly==0 ) nWrite++;
  63636. if( p->bIsReader ) nRead++;
  63637. }
  63638. p = p->pNext;
  63639. }
  63640. assert( cnt==db->nVdbeActive );
  63641. assert( nWrite==db->nVdbeWrite );
  63642. assert( nRead==db->nVdbeRead );
  63643. }
  63644. #else
  63645. #define checkActiveVdbeCnt(x)
  63646. #endif
  63647. /*
  63648. ** If the Vdbe passed as the first argument opened a statement-transaction,
  63649. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  63650. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  63651. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  63652. ** statement transaction is committed.
  63653. **
  63654. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  63655. ** Otherwise SQLITE_OK.
  63656. */
  63657. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  63658. sqlite3 *const db = p->db;
  63659. int rc = SQLITE_OK;
  63660. /* If p->iStatement is greater than zero, then this Vdbe opened a
  63661. ** statement transaction that should be closed here. The only exception
  63662. ** is that an IO error may have occurred, causing an emergency rollback.
  63663. ** In this case (db->nStatement==0), and there is nothing to do.
  63664. */
  63665. if( db->nStatement && p->iStatement ){
  63666. int i;
  63667. const int iSavepoint = p->iStatement-1;
  63668. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  63669. assert( db->nStatement>0 );
  63670. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  63671. for(i=0; i<db->nDb; i++){
  63672. int rc2 = SQLITE_OK;
  63673. Btree *pBt = db->aDb[i].pBt;
  63674. if( pBt ){
  63675. if( eOp==SAVEPOINT_ROLLBACK ){
  63676. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  63677. }
  63678. if( rc2==SQLITE_OK ){
  63679. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  63680. }
  63681. if( rc==SQLITE_OK ){
  63682. rc = rc2;
  63683. }
  63684. }
  63685. }
  63686. db->nStatement--;
  63687. p->iStatement = 0;
  63688. if( rc==SQLITE_OK ){
  63689. if( eOp==SAVEPOINT_ROLLBACK ){
  63690. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  63691. }
  63692. if( rc==SQLITE_OK ){
  63693. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  63694. }
  63695. }
  63696. /* If the statement transaction is being rolled back, also restore the
  63697. ** database handles deferred constraint counter to the value it had when
  63698. ** the statement transaction was opened. */
  63699. if( eOp==SAVEPOINT_ROLLBACK ){
  63700. db->nDeferredCons = p->nStmtDefCons;
  63701. db->nDeferredImmCons = p->nStmtDefImmCons;
  63702. }
  63703. }
  63704. return rc;
  63705. }
  63706. /*
  63707. ** This function is called when a transaction opened by the database
  63708. ** handle associated with the VM passed as an argument is about to be
  63709. ** committed. If there are outstanding deferred foreign key constraint
  63710. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  63711. **
  63712. ** If there are outstanding FK violations and this function returns
  63713. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  63714. ** and write an error message to it. Then return SQLITE_ERROR.
  63715. */
  63716. #ifndef SQLITE_OMIT_FOREIGN_KEY
  63717. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  63718. sqlite3 *db = p->db;
  63719. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  63720. || (!deferred && p->nFkConstraint>0)
  63721. ){
  63722. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  63723. p->errorAction = OE_Abort;
  63724. sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
  63725. return SQLITE_ERROR;
  63726. }
  63727. return SQLITE_OK;
  63728. }
  63729. #endif
  63730. /*
  63731. ** This routine is called the when a VDBE tries to halt. If the VDBE
  63732. ** has made changes and is in autocommit mode, then commit those
  63733. ** changes. If a rollback is needed, then do the rollback.
  63734. **
  63735. ** This routine is the only way to move the state of a VM from
  63736. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  63737. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  63738. **
  63739. ** Return an error code. If the commit could not complete because of
  63740. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  63741. ** means the close did not happen and needs to be repeated.
  63742. */
  63743. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  63744. int rc; /* Used to store transient return codes */
  63745. sqlite3 *db = p->db;
  63746. /* This function contains the logic that determines if a statement or
  63747. ** transaction will be committed or rolled back as a result of the
  63748. ** execution of this virtual machine.
  63749. **
  63750. ** If any of the following errors occur:
  63751. **
  63752. ** SQLITE_NOMEM
  63753. ** SQLITE_IOERR
  63754. ** SQLITE_FULL
  63755. ** SQLITE_INTERRUPT
  63756. **
  63757. ** Then the internal cache might have been left in an inconsistent
  63758. ** state. We need to rollback the statement transaction, if there is
  63759. ** one, or the complete transaction if there is no statement transaction.
  63760. */
  63761. if( p->db->mallocFailed ){
  63762. p->rc = SQLITE_NOMEM;
  63763. }
  63764. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  63765. closeAllCursors(p);
  63766. if( p->magic!=VDBE_MAGIC_RUN ){
  63767. return SQLITE_OK;
  63768. }
  63769. checkActiveVdbeCnt(db);
  63770. /* No commit or rollback needed if the program never started or if the
  63771. ** SQL statement does not read or write a database file. */
  63772. if( p->pc>=0 && p->bIsReader ){
  63773. int mrc; /* Primary error code from p->rc */
  63774. int eStatementOp = 0;
  63775. int isSpecialError; /* Set to true if a 'special' error */
  63776. /* Lock all btrees used by the statement */
  63777. sqlite3VdbeEnter(p);
  63778. /* Check for one of the special errors */
  63779. mrc = p->rc & 0xff;
  63780. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  63781. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  63782. if( isSpecialError ){
  63783. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  63784. ** no rollback is necessary. Otherwise, at least a savepoint
  63785. ** transaction must be rolled back to restore the database to a
  63786. ** consistent state.
  63787. **
  63788. ** Even if the statement is read-only, it is important to perform
  63789. ** a statement or transaction rollback operation. If the error
  63790. ** occurred while writing to the journal, sub-journal or database
  63791. ** file as part of an effort to free up cache space (see function
  63792. ** pagerStress() in pager.c), the rollback is required to restore
  63793. ** the pager to a consistent state.
  63794. */
  63795. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  63796. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  63797. eStatementOp = SAVEPOINT_ROLLBACK;
  63798. }else{
  63799. /* We are forced to roll back the active transaction. Before doing
  63800. ** so, abort any other statements this handle currently has active.
  63801. */
  63802. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  63803. sqlite3CloseSavepoints(db);
  63804. db->autoCommit = 1;
  63805. p->nChange = 0;
  63806. }
  63807. }
  63808. }
  63809. /* Check for immediate foreign key violations. */
  63810. if( p->rc==SQLITE_OK ){
  63811. sqlite3VdbeCheckFk(p, 0);
  63812. }
  63813. /* If the auto-commit flag is set and this is the only active writer
  63814. ** VM, then we do either a commit or rollback of the current transaction.
  63815. **
  63816. ** Note: This block also runs if one of the special errors handled
  63817. ** above has occurred.
  63818. */
  63819. if( !sqlite3VtabInSync(db)
  63820. && db->autoCommit
  63821. && db->nVdbeWrite==(p->readOnly==0)
  63822. ){
  63823. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  63824. rc = sqlite3VdbeCheckFk(p, 1);
  63825. if( rc!=SQLITE_OK ){
  63826. if( NEVER(p->readOnly) ){
  63827. sqlite3VdbeLeave(p);
  63828. return SQLITE_ERROR;
  63829. }
  63830. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  63831. }else{
  63832. /* The auto-commit flag is true, the vdbe program was successful
  63833. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  63834. ** key constraints to hold up the transaction. This means a commit
  63835. ** is required. */
  63836. rc = vdbeCommit(db, p);
  63837. }
  63838. if( rc==SQLITE_BUSY && p->readOnly ){
  63839. sqlite3VdbeLeave(p);
  63840. return SQLITE_BUSY;
  63841. }else if( rc!=SQLITE_OK ){
  63842. p->rc = rc;
  63843. sqlite3RollbackAll(db, SQLITE_OK);
  63844. p->nChange = 0;
  63845. }else{
  63846. db->nDeferredCons = 0;
  63847. db->nDeferredImmCons = 0;
  63848. db->flags &= ~SQLITE_DeferFKs;
  63849. sqlite3CommitInternalChanges(db);
  63850. }
  63851. }else{
  63852. sqlite3RollbackAll(db, SQLITE_OK);
  63853. p->nChange = 0;
  63854. }
  63855. db->nStatement = 0;
  63856. }else if( eStatementOp==0 ){
  63857. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  63858. eStatementOp = SAVEPOINT_RELEASE;
  63859. }else if( p->errorAction==OE_Abort ){
  63860. eStatementOp = SAVEPOINT_ROLLBACK;
  63861. }else{
  63862. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  63863. sqlite3CloseSavepoints(db);
  63864. db->autoCommit = 1;
  63865. p->nChange = 0;
  63866. }
  63867. }
  63868. /* If eStatementOp is non-zero, then a statement transaction needs to
  63869. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  63870. ** do so. If this operation returns an error, and the current statement
  63871. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  63872. ** current statement error code.
  63873. */
  63874. if( eStatementOp ){
  63875. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  63876. if( rc ){
  63877. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  63878. p->rc = rc;
  63879. sqlite3DbFree(db, p->zErrMsg);
  63880. p->zErrMsg = 0;
  63881. }
  63882. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  63883. sqlite3CloseSavepoints(db);
  63884. db->autoCommit = 1;
  63885. p->nChange = 0;
  63886. }
  63887. }
  63888. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  63889. ** has been rolled back, update the database connection change-counter.
  63890. */
  63891. if( p->changeCntOn ){
  63892. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  63893. sqlite3VdbeSetChanges(db, p->nChange);
  63894. }else{
  63895. sqlite3VdbeSetChanges(db, 0);
  63896. }
  63897. p->nChange = 0;
  63898. }
  63899. /* Release the locks */
  63900. sqlite3VdbeLeave(p);
  63901. }
  63902. /* We have successfully halted and closed the VM. Record this fact. */
  63903. if( p->pc>=0 ){
  63904. db->nVdbeActive--;
  63905. if( !p->readOnly ) db->nVdbeWrite--;
  63906. if( p->bIsReader ) db->nVdbeRead--;
  63907. assert( db->nVdbeActive>=db->nVdbeRead );
  63908. assert( db->nVdbeRead>=db->nVdbeWrite );
  63909. assert( db->nVdbeWrite>=0 );
  63910. }
  63911. p->magic = VDBE_MAGIC_HALT;
  63912. checkActiveVdbeCnt(db);
  63913. if( p->db->mallocFailed ){
  63914. p->rc = SQLITE_NOMEM;
  63915. }
  63916. /* If the auto-commit flag is set to true, then any locks that were held
  63917. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  63918. ** to invoke any required unlock-notify callbacks.
  63919. */
  63920. if( db->autoCommit ){
  63921. sqlite3ConnectionUnlocked(db);
  63922. }
  63923. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  63924. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  63925. }
  63926. /*
  63927. ** Each VDBE holds the result of the most recent sqlite3_step() call
  63928. ** in p->rc. This routine sets that result back to SQLITE_OK.
  63929. */
  63930. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  63931. p->rc = SQLITE_OK;
  63932. }
  63933. /*
  63934. ** Copy the error code and error message belonging to the VDBE passed
  63935. ** as the first argument to its database handle (so that they will be
  63936. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  63937. **
  63938. ** This function does not clear the VDBE error code or message, just
  63939. ** copies them to the database handle.
  63940. */
  63941. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  63942. sqlite3 *db = p->db;
  63943. int rc = p->rc;
  63944. if( p->zErrMsg ){
  63945. u8 mallocFailed = db->mallocFailed;
  63946. sqlite3BeginBenignMalloc();
  63947. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  63948. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  63949. sqlite3EndBenignMalloc();
  63950. db->mallocFailed = mallocFailed;
  63951. db->errCode = rc;
  63952. }else{
  63953. sqlite3Error(db, rc);
  63954. }
  63955. return rc;
  63956. }
  63957. #ifdef SQLITE_ENABLE_SQLLOG
  63958. /*
  63959. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  63960. ** invoke it.
  63961. */
  63962. static void vdbeInvokeSqllog(Vdbe *v){
  63963. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  63964. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  63965. assert( v->db->init.busy==0 );
  63966. if( zExpanded ){
  63967. sqlite3GlobalConfig.xSqllog(
  63968. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  63969. );
  63970. sqlite3DbFree(v->db, zExpanded);
  63971. }
  63972. }
  63973. }
  63974. #else
  63975. # define vdbeInvokeSqllog(x)
  63976. #endif
  63977. /*
  63978. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  63979. ** Write any error messages into *pzErrMsg. Return the result code.
  63980. **
  63981. ** After this routine is run, the VDBE should be ready to be executed
  63982. ** again.
  63983. **
  63984. ** To look at it another way, this routine resets the state of the
  63985. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  63986. ** VDBE_MAGIC_INIT.
  63987. */
  63988. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  63989. sqlite3 *db;
  63990. db = p->db;
  63991. /* If the VM did not run to completion or if it encountered an
  63992. ** error, then it might not have been halted properly. So halt
  63993. ** it now.
  63994. */
  63995. sqlite3VdbeHalt(p);
  63996. /* If the VDBE has be run even partially, then transfer the error code
  63997. ** and error message from the VDBE into the main database structure. But
  63998. ** if the VDBE has just been set to run but has not actually executed any
  63999. ** instructions yet, leave the main database error information unchanged.
  64000. */
  64001. if( p->pc>=0 ){
  64002. vdbeInvokeSqllog(p);
  64003. sqlite3VdbeTransferError(p);
  64004. sqlite3DbFree(db, p->zErrMsg);
  64005. p->zErrMsg = 0;
  64006. if( p->runOnlyOnce ) p->expired = 1;
  64007. }else if( p->rc && p->expired ){
  64008. /* The expired flag was set on the VDBE before the first call
  64009. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  64010. ** called), set the database error in this case as well.
  64011. */
  64012. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  64013. sqlite3DbFree(db, p->zErrMsg);
  64014. p->zErrMsg = 0;
  64015. }
  64016. /* Reclaim all memory used by the VDBE
  64017. */
  64018. Cleanup(p);
  64019. /* Save profiling information from this VDBE run.
  64020. */
  64021. #ifdef VDBE_PROFILE
  64022. {
  64023. FILE *out = fopen("vdbe_profile.out", "a");
  64024. if( out ){
  64025. int i;
  64026. fprintf(out, "---- ");
  64027. for(i=0; i<p->nOp; i++){
  64028. fprintf(out, "%02x", p->aOp[i].opcode);
  64029. }
  64030. fprintf(out, "\n");
  64031. if( p->zSql ){
  64032. char c, pc = 0;
  64033. fprintf(out, "-- ");
  64034. for(i=0; (c = p->zSql[i])!=0; i++){
  64035. if( pc=='\n' ) fprintf(out, "-- ");
  64036. putc(c, out);
  64037. pc = c;
  64038. }
  64039. if( pc!='\n' ) fprintf(out, "\n");
  64040. }
  64041. for(i=0; i<p->nOp; i++){
  64042. char zHdr[100];
  64043. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  64044. p->aOp[i].cnt,
  64045. p->aOp[i].cycles,
  64046. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  64047. );
  64048. fprintf(out, "%s", zHdr);
  64049. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  64050. }
  64051. fclose(out);
  64052. }
  64053. }
  64054. #endif
  64055. p->iCurrentTime = 0;
  64056. p->magic = VDBE_MAGIC_INIT;
  64057. return p->rc & db->errMask;
  64058. }
  64059. /*
  64060. ** Clean up and delete a VDBE after execution. Return an integer which is
  64061. ** the result code. Write any error message text into *pzErrMsg.
  64062. */
  64063. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  64064. int rc = SQLITE_OK;
  64065. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  64066. rc = sqlite3VdbeReset(p);
  64067. assert( (rc & p->db->errMask)==rc );
  64068. }
  64069. sqlite3VdbeDelete(p);
  64070. return rc;
  64071. }
  64072. /*
  64073. ** If parameter iOp is less than zero, then invoke the destructor for
  64074. ** all auxiliary data pointers currently cached by the VM passed as
  64075. ** the first argument.
  64076. **
  64077. ** Or, if iOp is greater than or equal to zero, then the destructor is
  64078. ** only invoked for those auxiliary data pointers created by the user
  64079. ** function invoked by the OP_Function opcode at instruction iOp of
  64080. ** VM pVdbe, and only then if:
  64081. **
  64082. ** * the associated function parameter is the 32nd or later (counting
  64083. ** from left to right), or
  64084. **
  64085. ** * the corresponding bit in argument mask is clear (where the first
  64086. ** function parameter corresponds to bit 0 etc.).
  64087. */
  64088. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  64089. AuxData **pp = &pVdbe->pAuxData;
  64090. while( *pp ){
  64091. AuxData *pAux = *pp;
  64092. if( (iOp<0)
  64093. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
  64094. ){
  64095. testcase( pAux->iArg==31 );
  64096. if( pAux->xDelete ){
  64097. pAux->xDelete(pAux->pAux);
  64098. }
  64099. *pp = pAux->pNext;
  64100. sqlite3DbFree(pVdbe->db, pAux);
  64101. }else{
  64102. pp= &pAux->pNext;
  64103. }
  64104. }
  64105. }
  64106. /*
  64107. ** Free all memory associated with the Vdbe passed as the second argument,
  64108. ** except for object itself, which is preserved.
  64109. **
  64110. ** The difference between this function and sqlite3VdbeDelete() is that
  64111. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  64112. ** the database connection and frees the object itself.
  64113. */
  64114. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  64115. SubProgram *pSub, *pNext;
  64116. int i;
  64117. assert( p->db==0 || p->db==db );
  64118. releaseMemArray(p->aVar, p->nVar);
  64119. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  64120. for(pSub=p->pProgram; pSub; pSub=pNext){
  64121. pNext = pSub->pNext;
  64122. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  64123. sqlite3DbFree(db, pSub);
  64124. }
  64125. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  64126. vdbeFreeOpArray(db, p->aOp, p->nOp);
  64127. sqlite3DbFree(db, p->aColName);
  64128. sqlite3DbFree(db, p->zSql);
  64129. sqlite3DbFree(db, p->pFree);
  64130. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  64131. for(i=0; i<p->nScan; i++){
  64132. sqlite3DbFree(db, p->aScan[i].zName);
  64133. }
  64134. sqlite3DbFree(db, p->aScan);
  64135. #endif
  64136. }
  64137. /*
  64138. ** Delete an entire VDBE.
  64139. */
  64140. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  64141. sqlite3 *db;
  64142. if( NEVER(p==0) ) return;
  64143. db = p->db;
  64144. assert( sqlite3_mutex_held(db->mutex) );
  64145. sqlite3VdbeClearObject(db, p);
  64146. if( p->pPrev ){
  64147. p->pPrev->pNext = p->pNext;
  64148. }else{
  64149. assert( db->pVdbe==p );
  64150. db->pVdbe = p->pNext;
  64151. }
  64152. if( p->pNext ){
  64153. p->pNext->pPrev = p->pPrev;
  64154. }
  64155. p->magic = VDBE_MAGIC_DEAD;
  64156. p->db = 0;
  64157. sqlite3DbFree(db, p);
  64158. }
  64159. /*
  64160. ** The cursor "p" has a pending seek operation that has not yet been
  64161. ** carried out. Seek the cursor now. If an error occurs, return
  64162. ** the appropriate error code.
  64163. */
  64164. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  64165. int res, rc;
  64166. #ifdef SQLITE_TEST
  64167. extern int sqlite3_search_count;
  64168. #endif
  64169. assert( p->deferredMoveto );
  64170. assert( p->isTable );
  64171. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  64172. if( rc ) return rc;
  64173. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  64174. #ifdef SQLITE_TEST
  64175. sqlite3_search_count++;
  64176. #endif
  64177. p->deferredMoveto = 0;
  64178. p->cacheStatus = CACHE_STALE;
  64179. return SQLITE_OK;
  64180. }
  64181. /*
  64182. ** Something has moved cursor "p" out of place. Maybe the row it was
  64183. ** pointed to was deleted out from under it. Or maybe the btree was
  64184. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  64185. ** is supposed to be pointing. If the row was deleted out from under the
  64186. ** cursor, set the cursor to point to a NULL row.
  64187. */
  64188. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  64189. int isDifferentRow, rc;
  64190. assert( p->pCursor!=0 );
  64191. assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
  64192. rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
  64193. p->cacheStatus = CACHE_STALE;
  64194. if( isDifferentRow ) p->nullRow = 1;
  64195. return rc;
  64196. }
  64197. /*
  64198. ** Check to ensure that the cursor is valid. Restore the cursor
  64199. ** if need be. Return any I/O error from the restore operation.
  64200. */
  64201. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  64202. if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
  64203. return handleMovedCursor(p);
  64204. }
  64205. return SQLITE_OK;
  64206. }
  64207. /*
  64208. ** Make sure the cursor p is ready to read or write the row to which it
  64209. ** was last positioned. Return an error code if an OOM fault or I/O error
  64210. ** prevents us from positioning the cursor to its correct position.
  64211. **
  64212. ** If a MoveTo operation is pending on the given cursor, then do that
  64213. ** MoveTo now. If no move is pending, check to see if the row has been
  64214. ** deleted out from under the cursor and if it has, mark the row as
  64215. ** a NULL row.
  64216. **
  64217. ** If the cursor is already pointing to the correct row and that row has
  64218. ** not been deleted out from under the cursor, then this routine is a no-op.
  64219. */
  64220. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  64221. if( p->deferredMoveto ){
  64222. return handleDeferredMoveto(p);
  64223. }
  64224. if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
  64225. return handleMovedCursor(p);
  64226. }
  64227. return SQLITE_OK;
  64228. }
  64229. /*
  64230. ** The following functions:
  64231. **
  64232. ** sqlite3VdbeSerialType()
  64233. ** sqlite3VdbeSerialTypeLen()
  64234. ** sqlite3VdbeSerialLen()
  64235. ** sqlite3VdbeSerialPut()
  64236. ** sqlite3VdbeSerialGet()
  64237. **
  64238. ** encapsulate the code that serializes values for storage in SQLite
  64239. ** data and index records. Each serialized value consists of a
  64240. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  64241. ** integer, stored as a varint.
  64242. **
  64243. ** In an SQLite index record, the serial type is stored directly before
  64244. ** the blob of data that it corresponds to. In a table record, all serial
  64245. ** types are stored at the start of the record, and the blobs of data at
  64246. ** the end. Hence these functions allow the caller to handle the
  64247. ** serial-type and data blob separately.
  64248. **
  64249. ** The following table describes the various storage classes for data:
  64250. **
  64251. ** serial type bytes of data type
  64252. ** -------------- --------------- ---------------
  64253. ** 0 0 NULL
  64254. ** 1 1 signed integer
  64255. ** 2 2 signed integer
  64256. ** 3 3 signed integer
  64257. ** 4 4 signed integer
  64258. ** 5 6 signed integer
  64259. ** 6 8 signed integer
  64260. ** 7 8 IEEE float
  64261. ** 8 0 Integer constant 0
  64262. ** 9 0 Integer constant 1
  64263. ** 10,11 reserved for expansion
  64264. ** N>=12 and even (N-12)/2 BLOB
  64265. ** N>=13 and odd (N-13)/2 text
  64266. **
  64267. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  64268. ** of SQLite will not understand those serial types.
  64269. */
  64270. /*
  64271. ** Return the serial-type for the value stored in pMem.
  64272. */
  64273. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  64274. int flags = pMem->flags;
  64275. u32 n;
  64276. if( flags&MEM_Null ){
  64277. return 0;
  64278. }
  64279. if( flags&MEM_Int ){
  64280. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  64281. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  64282. i64 i = pMem->u.i;
  64283. u64 u;
  64284. if( i<0 ){
  64285. u = ~i;
  64286. }else{
  64287. u = i;
  64288. }
  64289. if( u<=127 ){
  64290. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  64291. }
  64292. if( u<=32767 ) return 2;
  64293. if( u<=8388607 ) return 3;
  64294. if( u<=2147483647 ) return 4;
  64295. if( u<=MAX_6BYTE ) return 5;
  64296. return 6;
  64297. }
  64298. if( flags&MEM_Real ){
  64299. return 7;
  64300. }
  64301. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  64302. assert( pMem->n>=0 );
  64303. n = (u32)pMem->n;
  64304. if( flags & MEM_Zero ){
  64305. n += pMem->u.nZero;
  64306. }
  64307. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  64308. }
  64309. /*
  64310. ** The sizes for serial types less than 12
  64311. */
  64312. static const u8 sqlite3SmallTypeSizes[] = {
  64313. 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0
  64314. };
  64315. /*
  64316. ** Return the length of the data corresponding to the supplied serial-type.
  64317. */
  64318. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  64319. if( serial_type>=12 ){
  64320. return (serial_type-12)/2;
  64321. }else{
  64322. return sqlite3SmallTypeSizes[serial_type];
  64323. }
  64324. }
  64325. /*
  64326. ** If we are on an architecture with mixed-endian floating
  64327. ** points (ex: ARM7) then swap the lower 4 bytes with the
  64328. ** upper 4 bytes. Return the result.
  64329. **
  64330. ** For most architectures, this is a no-op.
  64331. **
  64332. ** (later): It is reported to me that the mixed-endian problem
  64333. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  64334. ** that early versions of GCC stored the two words of a 64-bit
  64335. ** float in the wrong order. And that error has been propagated
  64336. ** ever since. The blame is not necessarily with GCC, though.
  64337. ** GCC might have just copying the problem from a prior compiler.
  64338. ** I am also told that newer versions of GCC that follow a different
  64339. ** ABI get the byte order right.
  64340. **
  64341. ** Developers using SQLite on an ARM7 should compile and run their
  64342. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  64343. ** enabled, some asserts below will ensure that the byte order of
  64344. ** floating point values is correct.
  64345. **
  64346. ** (2007-08-30) Frank van Vugt has studied this problem closely
  64347. ** and has send his findings to the SQLite developers. Frank
  64348. ** writes that some Linux kernels offer floating point hardware
  64349. ** emulation that uses only 32-bit mantissas instead of a full
  64350. ** 48-bits as required by the IEEE standard. (This is the
  64351. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  64352. ** byte swapping becomes very complicated. To avoid problems,
  64353. ** the necessary byte swapping is carried out using a 64-bit integer
  64354. ** rather than a 64-bit float. Frank assures us that the code here
  64355. ** works for him. We, the developers, have no way to independently
  64356. ** verify this, but Frank seems to know what he is talking about
  64357. ** so we trust him.
  64358. */
  64359. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  64360. static u64 floatSwap(u64 in){
  64361. union {
  64362. u64 r;
  64363. u32 i[2];
  64364. } u;
  64365. u32 t;
  64366. u.r = in;
  64367. t = u.i[0];
  64368. u.i[0] = u.i[1];
  64369. u.i[1] = t;
  64370. return u.r;
  64371. }
  64372. # define swapMixedEndianFloat(X) X = floatSwap(X)
  64373. #else
  64374. # define swapMixedEndianFloat(X)
  64375. #endif
  64376. /*
  64377. ** Write the serialized data blob for the value stored in pMem into
  64378. ** buf. It is assumed that the caller has allocated sufficient space.
  64379. ** Return the number of bytes written.
  64380. **
  64381. ** nBuf is the amount of space left in buf[]. The caller is responsible
  64382. ** for allocating enough space to buf[] to hold the entire field, exclusive
  64383. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  64384. **
  64385. ** Return the number of bytes actually written into buf[]. The number
  64386. ** of bytes in the zero-filled tail is included in the return value only
  64387. ** if those bytes were zeroed in buf[].
  64388. */
  64389. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  64390. u32 len;
  64391. /* Integer and Real */
  64392. if( serial_type<=7 && serial_type>0 ){
  64393. u64 v;
  64394. u32 i;
  64395. if( serial_type==7 ){
  64396. assert( sizeof(v)==sizeof(pMem->u.r) );
  64397. memcpy(&v, &pMem->u.r, sizeof(v));
  64398. swapMixedEndianFloat(v);
  64399. }else{
  64400. v = pMem->u.i;
  64401. }
  64402. len = i = sqlite3SmallTypeSizes[serial_type];
  64403. assert( i>0 );
  64404. do{
  64405. buf[--i] = (u8)(v&0xFF);
  64406. v >>= 8;
  64407. }while( i );
  64408. return len;
  64409. }
  64410. /* String or blob */
  64411. if( serial_type>=12 ){
  64412. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  64413. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  64414. len = pMem->n;
  64415. memcpy(buf, pMem->z, len);
  64416. return len;
  64417. }
  64418. /* NULL or constants 0 or 1 */
  64419. return 0;
  64420. }
  64421. /* Input "x" is a sequence of unsigned characters that represent a
  64422. ** big-endian integer. Return the equivalent native integer
  64423. */
  64424. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  64425. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  64426. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  64427. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  64428. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  64429. /*
  64430. ** Deserialize the data blob pointed to by buf as serial type serial_type
  64431. ** and store the result in pMem. Return the number of bytes read.
  64432. **
  64433. ** This function is implemented as two separate routines for performance.
  64434. ** The few cases that require local variables are broken out into a separate
  64435. ** routine so that in most cases the overhead of moving the stack pointer
  64436. ** is avoided.
  64437. */
  64438. static u32 SQLITE_NOINLINE serialGet(
  64439. const unsigned char *buf, /* Buffer to deserialize from */
  64440. u32 serial_type, /* Serial type to deserialize */
  64441. Mem *pMem /* Memory cell to write value into */
  64442. ){
  64443. u64 x = FOUR_BYTE_UINT(buf);
  64444. u32 y = FOUR_BYTE_UINT(buf+4);
  64445. x = (x<<32) + y;
  64446. if( serial_type==6 ){
  64447. /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
  64448. ** twos-complement integer. */
  64449. pMem->u.i = *(i64*)&x;
  64450. pMem->flags = MEM_Int;
  64451. testcase( pMem->u.i<0 );
  64452. }else{
  64453. /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
  64454. ** floating point number. */
  64455. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  64456. /* Verify that integers and floating point values use the same
  64457. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  64458. ** defined that 64-bit floating point values really are mixed
  64459. ** endian.
  64460. */
  64461. static const u64 t1 = ((u64)0x3ff00000)<<32;
  64462. static const double r1 = 1.0;
  64463. u64 t2 = t1;
  64464. swapMixedEndianFloat(t2);
  64465. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  64466. #endif
  64467. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  64468. swapMixedEndianFloat(x);
  64469. memcpy(&pMem->u.r, &x, sizeof(x));
  64470. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  64471. }
  64472. return 8;
  64473. }
  64474. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  64475. const unsigned char *buf, /* Buffer to deserialize from */
  64476. u32 serial_type, /* Serial type to deserialize */
  64477. Mem *pMem /* Memory cell to write value into */
  64478. ){
  64479. switch( serial_type ){
  64480. case 10: /* Reserved for future use */
  64481. case 11: /* Reserved for future use */
  64482. case 0: { /* Null */
  64483. /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
  64484. pMem->flags = MEM_Null;
  64485. break;
  64486. }
  64487. case 1: {
  64488. /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
  64489. ** integer. */
  64490. pMem->u.i = ONE_BYTE_INT(buf);
  64491. pMem->flags = MEM_Int;
  64492. testcase( pMem->u.i<0 );
  64493. return 1;
  64494. }
  64495. case 2: { /* 2-byte signed integer */
  64496. /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
  64497. ** twos-complement integer. */
  64498. pMem->u.i = TWO_BYTE_INT(buf);
  64499. pMem->flags = MEM_Int;
  64500. testcase( pMem->u.i<0 );
  64501. return 2;
  64502. }
  64503. case 3: { /* 3-byte signed integer */
  64504. /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
  64505. ** twos-complement integer. */
  64506. pMem->u.i = THREE_BYTE_INT(buf);
  64507. pMem->flags = MEM_Int;
  64508. testcase( pMem->u.i<0 );
  64509. return 3;
  64510. }
  64511. case 4: { /* 4-byte signed integer */
  64512. /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
  64513. ** twos-complement integer. */
  64514. pMem->u.i = FOUR_BYTE_INT(buf);
  64515. pMem->flags = MEM_Int;
  64516. testcase( pMem->u.i<0 );
  64517. return 4;
  64518. }
  64519. case 5: { /* 6-byte signed integer */
  64520. /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
  64521. ** twos-complement integer. */
  64522. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  64523. pMem->flags = MEM_Int;
  64524. testcase( pMem->u.i<0 );
  64525. return 6;
  64526. }
  64527. case 6: /* 8-byte signed integer */
  64528. case 7: { /* IEEE floating point */
  64529. /* These use local variables, so do them in a separate routine
  64530. ** to avoid having to move the frame pointer in the common case */
  64531. return serialGet(buf,serial_type,pMem);
  64532. }
  64533. case 8: /* Integer 0 */
  64534. case 9: { /* Integer 1 */
  64535. /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
  64536. /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
  64537. pMem->u.i = serial_type-8;
  64538. pMem->flags = MEM_Int;
  64539. return 0;
  64540. }
  64541. default: {
  64542. /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
  64543. ** length.
  64544. ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
  64545. ** (N-13)/2 bytes in length. */
  64546. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  64547. pMem->z = (char *)buf;
  64548. pMem->n = (serial_type-12)/2;
  64549. pMem->flags = aFlag[serial_type&1];
  64550. return pMem->n;
  64551. }
  64552. }
  64553. return 0;
  64554. }
  64555. /*
  64556. ** This routine is used to allocate sufficient space for an UnpackedRecord
  64557. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  64558. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  64559. **
  64560. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  64561. ** the unaligned buffer passed via the second and third arguments (presumably
  64562. ** stack space). If the former, then *ppFree is set to a pointer that should
  64563. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  64564. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  64565. ** before returning.
  64566. **
  64567. ** If an OOM error occurs, NULL is returned.
  64568. */
  64569. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  64570. KeyInfo *pKeyInfo, /* Description of the record */
  64571. char *pSpace, /* Unaligned space available */
  64572. int szSpace, /* Size of pSpace[] in bytes */
  64573. char **ppFree /* OUT: Caller should free this pointer */
  64574. ){
  64575. UnpackedRecord *p; /* Unpacked record to return */
  64576. int nOff; /* Increment pSpace by nOff to align it */
  64577. int nByte; /* Number of bytes required for *p */
  64578. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  64579. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  64580. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  64581. */
  64582. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  64583. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  64584. if( nByte>szSpace+nOff ){
  64585. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  64586. *ppFree = (char *)p;
  64587. if( !p ) return 0;
  64588. }else{
  64589. p = (UnpackedRecord*)&pSpace[nOff];
  64590. *ppFree = 0;
  64591. }
  64592. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  64593. assert( pKeyInfo->aSortOrder!=0 );
  64594. p->pKeyInfo = pKeyInfo;
  64595. p->nField = pKeyInfo->nField + 1;
  64596. return p;
  64597. }
  64598. /*
  64599. ** Given the nKey-byte encoding of a record in pKey[], populate the
  64600. ** UnpackedRecord structure indicated by the fourth argument with the
  64601. ** contents of the decoded record.
  64602. */
  64603. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  64604. KeyInfo *pKeyInfo, /* Information about the record format */
  64605. int nKey, /* Size of the binary record */
  64606. const void *pKey, /* The binary record */
  64607. UnpackedRecord *p /* Populate this structure before returning. */
  64608. ){
  64609. const unsigned char *aKey = (const unsigned char *)pKey;
  64610. int d;
  64611. u32 idx; /* Offset in aKey[] to read from */
  64612. u16 u; /* Unsigned loop counter */
  64613. u32 szHdr;
  64614. Mem *pMem = p->aMem;
  64615. p->default_rc = 0;
  64616. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  64617. idx = getVarint32(aKey, szHdr);
  64618. d = szHdr;
  64619. u = 0;
  64620. while( idx<szHdr && d<=nKey ){
  64621. u32 serial_type;
  64622. idx += getVarint32(&aKey[idx], serial_type);
  64623. pMem->enc = pKeyInfo->enc;
  64624. pMem->db = pKeyInfo->db;
  64625. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  64626. pMem->szMalloc = 0;
  64627. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  64628. pMem++;
  64629. if( (++u)>=p->nField ) break;
  64630. }
  64631. assert( u<=pKeyInfo->nField + 1 );
  64632. p->nField = u;
  64633. }
  64634. #if SQLITE_DEBUG
  64635. /*
  64636. ** This function compares two index or table record keys in the same way
  64637. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  64638. ** this function deserializes and compares values using the
  64639. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  64640. ** in assert() statements to ensure that the optimized code in
  64641. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  64642. **
  64643. ** Return true if the result of comparison is equivalent to desiredResult.
  64644. ** Return false if there is a disagreement.
  64645. */
  64646. static int vdbeRecordCompareDebug(
  64647. int nKey1, const void *pKey1, /* Left key */
  64648. const UnpackedRecord *pPKey2, /* Right key */
  64649. int desiredResult /* Correct answer */
  64650. ){
  64651. u32 d1; /* Offset into aKey[] of next data element */
  64652. u32 idx1; /* Offset into aKey[] of next header element */
  64653. u32 szHdr1; /* Number of bytes in header */
  64654. int i = 0;
  64655. int rc = 0;
  64656. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  64657. KeyInfo *pKeyInfo;
  64658. Mem mem1;
  64659. pKeyInfo = pPKey2->pKeyInfo;
  64660. if( pKeyInfo->db==0 ) return 1;
  64661. mem1.enc = pKeyInfo->enc;
  64662. mem1.db = pKeyInfo->db;
  64663. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  64664. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  64665. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  64666. ** We could initialize it, as shown here, to silence those complaints.
  64667. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  64668. ** the unnecessary initialization has a measurable negative performance
  64669. ** impact, since this routine is a very high runner. And so, we choose
  64670. ** to ignore the compiler warnings and leave this variable uninitialized.
  64671. */
  64672. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  64673. idx1 = getVarint32(aKey1, szHdr1);
  64674. if( szHdr1>98307 ) return SQLITE_CORRUPT;
  64675. d1 = szHdr1;
  64676. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  64677. assert( pKeyInfo->aSortOrder!=0 );
  64678. assert( pKeyInfo->nField>0 );
  64679. assert( idx1<=szHdr1 || CORRUPT_DB );
  64680. do{
  64681. u32 serial_type1;
  64682. /* Read the serial types for the next element in each key. */
  64683. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  64684. /* Verify that there is enough key space remaining to avoid
  64685. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  64686. ** always be greater than or equal to the amount of required key space.
  64687. ** Use that approximation to avoid the more expensive call to
  64688. ** sqlite3VdbeSerialTypeLen() in the common case.
  64689. */
  64690. if( d1+serial_type1+2>(u32)nKey1
  64691. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  64692. ){
  64693. break;
  64694. }
  64695. /* Extract the values to be compared.
  64696. */
  64697. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  64698. /* Do the comparison
  64699. */
  64700. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  64701. if( rc!=0 ){
  64702. assert( mem1.szMalloc==0 ); /* See comment below */
  64703. if( pKeyInfo->aSortOrder[i] ){
  64704. rc = -rc; /* Invert the result for DESC sort order. */
  64705. }
  64706. goto debugCompareEnd;
  64707. }
  64708. i++;
  64709. }while( idx1<szHdr1 && i<pPKey2->nField );
  64710. /* No memory allocation is ever used on mem1. Prove this using
  64711. ** the following assert(). If the assert() fails, it indicates a
  64712. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  64713. */
  64714. assert( mem1.szMalloc==0 );
  64715. /* rc==0 here means that one of the keys ran out of fields and
  64716. ** all the fields up to that point were equal. Return the default_rc
  64717. ** value. */
  64718. rc = pPKey2->default_rc;
  64719. debugCompareEnd:
  64720. if( desiredResult==0 && rc==0 ) return 1;
  64721. if( desiredResult<0 && rc<0 ) return 1;
  64722. if( desiredResult>0 && rc>0 ) return 1;
  64723. if( CORRUPT_DB ) return 1;
  64724. if( pKeyInfo->db->mallocFailed ) return 1;
  64725. return 0;
  64726. }
  64727. #endif
  64728. #if SQLITE_DEBUG
  64729. /*
  64730. ** Count the number of fields (a.k.a. columns) in the record given by
  64731. ** pKey,nKey. The verify that this count is less than or equal to the
  64732. ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
  64733. **
  64734. ** If this constraint is not satisfied, it means that the high-speed
  64735. ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
  64736. ** not work correctly. If this assert() ever fires, it probably means
  64737. ** that the KeyInfo.nField or KeyInfo.nXField values were computed
  64738. ** incorrectly.
  64739. */
  64740. static void vdbeAssertFieldCountWithinLimits(
  64741. int nKey, const void *pKey, /* The record to verify */
  64742. const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
  64743. ){
  64744. int nField = 0;
  64745. u32 szHdr;
  64746. u32 idx;
  64747. u32 notUsed;
  64748. const unsigned char *aKey = (const unsigned char*)pKey;
  64749. if( CORRUPT_DB ) return;
  64750. idx = getVarint32(aKey, szHdr);
  64751. assert( nKey>=0 );
  64752. assert( szHdr<=(u32)nKey );
  64753. while( idx<szHdr ){
  64754. idx += getVarint32(aKey+idx, notUsed);
  64755. nField++;
  64756. }
  64757. assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
  64758. }
  64759. #else
  64760. # define vdbeAssertFieldCountWithinLimits(A,B,C)
  64761. #endif
  64762. /*
  64763. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  64764. ** using the collation sequence pColl. As usual, return a negative , zero
  64765. ** or positive value if *pMem1 is less than, equal to or greater than
  64766. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  64767. */
  64768. static int vdbeCompareMemString(
  64769. const Mem *pMem1,
  64770. const Mem *pMem2,
  64771. const CollSeq *pColl,
  64772. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  64773. ){
  64774. if( pMem1->enc==pColl->enc ){
  64775. /* The strings are already in the correct encoding. Call the
  64776. ** comparison function directly */
  64777. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  64778. }else{
  64779. int rc;
  64780. const void *v1, *v2;
  64781. int n1, n2;
  64782. Mem c1;
  64783. Mem c2;
  64784. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  64785. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  64786. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  64787. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  64788. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  64789. n1 = v1==0 ? 0 : c1.n;
  64790. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  64791. n2 = v2==0 ? 0 : c2.n;
  64792. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  64793. sqlite3VdbeMemRelease(&c1);
  64794. sqlite3VdbeMemRelease(&c2);
  64795. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
  64796. return rc;
  64797. }
  64798. }
  64799. /*
  64800. ** Compare two blobs. Return negative, zero, or positive if the first
  64801. ** is less than, equal to, or greater than the second, respectively.
  64802. ** If one blob is a prefix of the other, then the shorter is the lessor.
  64803. */
  64804. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  64805. int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
  64806. if( c ) return c;
  64807. return pB1->n - pB2->n;
  64808. }
  64809. /*
  64810. ** Compare the values contained by the two memory cells, returning
  64811. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  64812. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  64813. ** and reals) sorted numerically, followed by text ordered by the collating
  64814. ** sequence pColl and finally blob's ordered by memcmp().
  64815. **
  64816. ** Two NULL values are considered equal by this function.
  64817. */
  64818. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  64819. int f1, f2;
  64820. int combined_flags;
  64821. f1 = pMem1->flags;
  64822. f2 = pMem2->flags;
  64823. combined_flags = f1|f2;
  64824. assert( (combined_flags & MEM_RowSet)==0 );
  64825. /* If one value is NULL, it is less than the other. If both values
  64826. ** are NULL, return 0.
  64827. */
  64828. if( combined_flags&MEM_Null ){
  64829. return (f2&MEM_Null) - (f1&MEM_Null);
  64830. }
  64831. /* If one value is a number and the other is not, the number is less.
  64832. ** If both are numbers, compare as reals if one is a real, or as integers
  64833. ** if both values are integers.
  64834. */
  64835. if( combined_flags&(MEM_Int|MEM_Real) ){
  64836. double r1, r2;
  64837. if( (f1 & f2 & MEM_Int)!=0 ){
  64838. if( pMem1->u.i < pMem2->u.i ) return -1;
  64839. if( pMem1->u.i > pMem2->u.i ) return 1;
  64840. return 0;
  64841. }
  64842. if( (f1&MEM_Real)!=0 ){
  64843. r1 = pMem1->u.r;
  64844. }else if( (f1&MEM_Int)!=0 ){
  64845. r1 = (double)pMem1->u.i;
  64846. }else{
  64847. return 1;
  64848. }
  64849. if( (f2&MEM_Real)!=0 ){
  64850. r2 = pMem2->u.r;
  64851. }else if( (f2&MEM_Int)!=0 ){
  64852. r2 = (double)pMem2->u.i;
  64853. }else{
  64854. return -1;
  64855. }
  64856. if( r1<r2 ) return -1;
  64857. if( r1>r2 ) return 1;
  64858. return 0;
  64859. }
  64860. /* If one value is a string and the other is a blob, the string is less.
  64861. ** If both are strings, compare using the collating functions.
  64862. */
  64863. if( combined_flags&MEM_Str ){
  64864. if( (f1 & MEM_Str)==0 ){
  64865. return 1;
  64866. }
  64867. if( (f2 & MEM_Str)==0 ){
  64868. return -1;
  64869. }
  64870. assert( pMem1->enc==pMem2->enc );
  64871. assert( pMem1->enc==SQLITE_UTF8 ||
  64872. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  64873. /* The collation sequence must be defined at this point, even if
  64874. ** the user deletes the collation sequence after the vdbe program is
  64875. ** compiled (this was not always the case).
  64876. */
  64877. assert( !pColl || pColl->xCmp );
  64878. if( pColl ){
  64879. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  64880. }
  64881. /* If a NULL pointer was passed as the collate function, fall through
  64882. ** to the blob case and use memcmp(). */
  64883. }
  64884. /* Both values must be blobs. Compare using memcmp(). */
  64885. return sqlite3BlobCompare(pMem1, pMem2);
  64886. }
  64887. /*
  64888. ** The first argument passed to this function is a serial-type that
  64889. ** corresponds to an integer - all values between 1 and 9 inclusive
  64890. ** except 7. The second points to a buffer containing an integer value
  64891. ** serialized according to serial_type. This function deserializes
  64892. ** and returns the value.
  64893. */
  64894. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  64895. u32 y;
  64896. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  64897. switch( serial_type ){
  64898. case 0:
  64899. case 1:
  64900. testcase( aKey[0]&0x80 );
  64901. return ONE_BYTE_INT(aKey);
  64902. case 2:
  64903. testcase( aKey[0]&0x80 );
  64904. return TWO_BYTE_INT(aKey);
  64905. case 3:
  64906. testcase( aKey[0]&0x80 );
  64907. return THREE_BYTE_INT(aKey);
  64908. case 4: {
  64909. testcase( aKey[0]&0x80 );
  64910. y = FOUR_BYTE_UINT(aKey);
  64911. return (i64)*(int*)&y;
  64912. }
  64913. case 5: {
  64914. testcase( aKey[0]&0x80 );
  64915. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  64916. }
  64917. case 6: {
  64918. u64 x = FOUR_BYTE_UINT(aKey);
  64919. testcase( aKey[0]&0x80 );
  64920. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  64921. return (i64)*(i64*)&x;
  64922. }
  64923. }
  64924. return (serial_type - 8);
  64925. }
  64926. /*
  64927. ** This function compares the two table rows or index records
  64928. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  64929. ** or positive integer if key1 is less than, equal to or
  64930. ** greater than key2. The {nKey1, pKey1} key must be a blob
  64931. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  64932. ** key must be a parsed key such as obtained from
  64933. ** sqlite3VdbeParseRecord.
  64934. **
  64935. ** If argument bSkip is non-zero, it is assumed that the caller has already
  64936. ** determined that the first fields of the keys are equal.
  64937. **
  64938. ** Key1 and Key2 do not have to contain the same number of fields. If all
  64939. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  64940. ** returned.
  64941. **
  64942. ** If database corruption is discovered, set pPKey2->errCode to
  64943. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  64944. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  64945. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  64946. */
  64947. SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(
  64948. int nKey1, const void *pKey1, /* Left key */
  64949. UnpackedRecord *pPKey2, /* Right key */
  64950. int bSkip /* If true, skip the first field */
  64951. ){
  64952. u32 d1; /* Offset into aKey[] of next data element */
  64953. int i; /* Index of next field to compare */
  64954. u32 szHdr1; /* Size of record header in bytes */
  64955. u32 idx1; /* Offset of first type in header */
  64956. int rc = 0; /* Return value */
  64957. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  64958. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  64959. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  64960. Mem mem1;
  64961. /* If bSkip is true, then the caller has already determined that the first
  64962. ** two elements in the keys are equal. Fix the various stack variables so
  64963. ** that this routine begins comparing at the second field. */
  64964. if( bSkip ){
  64965. u32 s1;
  64966. idx1 = 1 + getVarint32(&aKey1[1], s1);
  64967. szHdr1 = aKey1[0];
  64968. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  64969. i = 1;
  64970. pRhs++;
  64971. }else{
  64972. idx1 = getVarint32(aKey1, szHdr1);
  64973. d1 = szHdr1;
  64974. if( d1>(unsigned)nKey1 ){
  64975. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  64976. return 0; /* Corruption */
  64977. }
  64978. i = 0;
  64979. }
  64980. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  64981. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  64982. || CORRUPT_DB );
  64983. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  64984. assert( pPKey2->pKeyInfo->nField>0 );
  64985. assert( idx1<=szHdr1 || CORRUPT_DB );
  64986. do{
  64987. u32 serial_type;
  64988. /* RHS is an integer */
  64989. if( pRhs->flags & MEM_Int ){
  64990. serial_type = aKey1[idx1];
  64991. testcase( serial_type==12 );
  64992. if( serial_type>=10 ){
  64993. rc = +1;
  64994. }else if( serial_type==0 ){
  64995. rc = -1;
  64996. }else if( serial_type==7 ){
  64997. double rhs = (double)pRhs->u.i;
  64998. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  64999. if( mem1.u.r<rhs ){
  65000. rc = -1;
  65001. }else if( mem1.u.r>rhs ){
  65002. rc = +1;
  65003. }
  65004. }else{
  65005. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  65006. i64 rhs = pRhs->u.i;
  65007. if( lhs<rhs ){
  65008. rc = -1;
  65009. }else if( lhs>rhs ){
  65010. rc = +1;
  65011. }
  65012. }
  65013. }
  65014. /* RHS is real */
  65015. else if( pRhs->flags & MEM_Real ){
  65016. serial_type = aKey1[idx1];
  65017. if( serial_type>=10 ){
  65018. /* Serial types 12 or greater are strings and blobs (greater than
  65019. ** numbers). Types 10 and 11 are currently "reserved for future
  65020. ** use", so it doesn't really matter what the results of comparing
  65021. ** them to numberic values are. */
  65022. rc = +1;
  65023. }else if( serial_type==0 ){
  65024. rc = -1;
  65025. }else{
  65026. double rhs = pRhs->u.r;
  65027. double lhs;
  65028. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  65029. if( serial_type==7 ){
  65030. lhs = mem1.u.r;
  65031. }else{
  65032. lhs = (double)mem1.u.i;
  65033. }
  65034. if( lhs<rhs ){
  65035. rc = -1;
  65036. }else if( lhs>rhs ){
  65037. rc = +1;
  65038. }
  65039. }
  65040. }
  65041. /* RHS is a string */
  65042. else if( pRhs->flags & MEM_Str ){
  65043. getVarint32(&aKey1[idx1], serial_type);
  65044. testcase( serial_type==12 );
  65045. if( serial_type<12 ){
  65046. rc = -1;
  65047. }else if( !(serial_type & 0x01) ){
  65048. rc = +1;
  65049. }else{
  65050. mem1.n = (serial_type - 12) / 2;
  65051. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  65052. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  65053. if( (d1+mem1.n) > (unsigned)nKey1 ){
  65054. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  65055. return 0; /* Corruption */
  65056. }else if( pKeyInfo->aColl[i] ){
  65057. mem1.enc = pKeyInfo->enc;
  65058. mem1.db = pKeyInfo->db;
  65059. mem1.flags = MEM_Str;
  65060. mem1.z = (char*)&aKey1[d1];
  65061. rc = vdbeCompareMemString(
  65062. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  65063. );
  65064. }else{
  65065. int nCmp = MIN(mem1.n, pRhs->n);
  65066. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  65067. if( rc==0 ) rc = mem1.n - pRhs->n;
  65068. }
  65069. }
  65070. }
  65071. /* RHS is a blob */
  65072. else if( pRhs->flags & MEM_Blob ){
  65073. getVarint32(&aKey1[idx1], serial_type);
  65074. testcase( serial_type==12 );
  65075. if( serial_type<12 || (serial_type & 0x01) ){
  65076. rc = -1;
  65077. }else{
  65078. int nStr = (serial_type - 12) / 2;
  65079. testcase( (d1+nStr)==(unsigned)nKey1 );
  65080. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  65081. if( (d1+nStr) > (unsigned)nKey1 ){
  65082. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  65083. return 0; /* Corruption */
  65084. }else{
  65085. int nCmp = MIN(nStr, pRhs->n);
  65086. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  65087. if( rc==0 ) rc = nStr - pRhs->n;
  65088. }
  65089. }
  65090. }
  65091. /* RHS is null */
  65092. else{
  65093. serial_type = aKey1[idx1];
  65094. rc = (serial_type!=0);
  65095. }
  65096. if( rc!=0 ){
  65097. if( pKeyInfo->aSortOrder[i] ){
  65098. rc = -rc;
  65099. }
  65100. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  65101. assert( mem1.szMalloc==0 ); /* See comment below */
  65102. return rc;
  65103. }
  65104. i++;
  65105. pRhs++;
  65106. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  65107. idx1 += sqlite3VarintLen(serial_type);
  65108. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  65109. /* No memory allocation is ever used on mem1. Prove this using
  65110. ** the following assert(). If the assert() fails, it indicates a
  65111. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  65112. assert( mem1.szMalloc==0 );
  65113. /* rc==0 here means that one or both of the keys ran out of fields and
  65114. ** all the fields up to that point were equal. Return the default_rc
  65115. ** value. */
  65116. assert( CORRUPT_DB
  65117. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  65118. || pKeyInfo->db->mallocFailed
  65119. );
  65120. return pPKey2->default_rc;
  65121. }
  65122. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  65123. int nKey1, const void *pKey1, /* Left key */
  65124. UnpackedRecord *pPKey2 /* Right key */
  65125. ){
  65126. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  65127. }
  65128. /*
  65129. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  65130. ** that (a) the first field of pPKey2 is an integer, and (b) the
  65131. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  65132. ** byte (i.e. is less than 128).
  65133. **
  65134. ** To avoid concerns about buffer overreads, this routine is only used
  65135. ** on schemas where the maximum valid header size is 63 bytes or less.
  65136. */
  65137. static int vdbeRecordCompareInt(
  65138. int nKey1, const void *pKey1, /* Left key */
  65139. UnpackedRecord *pPKey2 /* Right key */
  65140. ){
  65141. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  65142. int serial_type = ((const u8*)pKey1)[1];
  65143. int res;
  65144. u32 y;
  65145. u64 x;
  65146. i64 v = pPKey2->aMem[0].u.i;
  65147. i64 lhs;
  65148. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  65149. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  65150. switch( serial_type ){
  65151. case 1: { /* 1-byte signed integer */
  65152. lhs = ONE_BYTE_INT(aKey);
  65153. testcase( lhs<0 );
  65154. break;
  65155. }
  65156. case 2: { /* 2-byte signed integer */
  65157. lhs = TWO_BYTE_INT(aKey);
  65158. testcase( lhs<0 );
  65159. break;
  65160. }
  65161. case 3: { /* 3-byte signed integer */
  65162. lhs = THREE_BYTE_INT(aKey);
  65163. testcase( lhs<0 );
  65164. break;
  65165. }
  65166. case 4: { /* 4-byte signed integer */
  65167. y = FOUR_BYTE_UINT(aKey);
  65168. lhs = (i64)*(int*)&y;
  65169. testcase( lhs<0 );
  65170. break;
  65171. }
  65172. case 5: { /* 6-byte signed integer */
  65173. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  65174. testcase( lhs<0 );
  65175. break;
  65176. }
  65177. case 6: { /* 8-byte signed integer */
  65178. x = FOUR_BYTE_UINT(aKey);
  65179. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  65180. lhs = *(i64*)&x;
  65181. testcase( lhs<0 );
  65182. break;
  65183. }
  65184. case 8:
  65185. lhs = 0;
  65186. break;
  65187. case 9:
  65188. lhs = 1;
  65189. break;
  65190. /* This case could be removed without changing the results of running
  65191. ** this code. Including it causes gcc to generate a faster switch
  65192. ** statement (since the range of switch targets now starts at zero and
  65193. ** is contiguous) but does not cause any duplicate code to be generated
  65194. ** (as gcc is clever enough to combine the two like cases). Other
  65195. ** compilers might be similar. */
  65196. case 0: case 7:
  65197. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  65198. default:
  65199. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  65200. }
  65201. if( v>lhs ){
  65202. res = pPKey2->r1;
  65203. }else if( v<lhs ){
  65204. res = pPKey2->r2;
  65205. }else if( pPKey2->nField>1 ){
  65206. /* The first fields of the two keys are equal. Compare the trailing
  65207. ** fields. */
  65208. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  65209. }else{
  65210. /* The first fields of the two keys are equal and there are no trailing
  65211. ** fields. Return pPKey2->default_rc in this case. */
  65212. res = pPKey2->default_rc;
  65213. }
  65214. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  65215. return res;
  65216. }
  65217. /*
  65218. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  65219. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  65220. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  65221. ** at the start of (pKey1/nKey1) fits in a single byte.
  65222. */
  65223. static int vdbeRecordCompareString(
  65224. int nKey1, const void *pKey1, /* Left key */
  65225. UnpackedRecord *pPKey2 /* Right key */
  65226. ){
  65227. const u8 *aKey1 = (const u8*)pKey1;
  65228. int serial_type;
  65229. int res;
  65230. vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
  65231. getVarint32(&aKey1[1], serial_type);
  65232. if( serial_type<12 ){
  65233. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  65234. }else if( !(serial_type & 0x01) ){
  65235. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  65236. }else{
  65237. int nCmp;
  65238. int nStr;
  65239. int szHdr = aKey1[0];
  65240. nStr = (serial_type-12) / 2;
  65241. if( (szHdr + nStr) > nKey1 ){
  65242. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  65243. return 0; /* Corruption */
  65244. }
  65245. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  65246. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  65247. if( res==0 ){
  65248. res = nStr - pPKey2->aMem[0].n;
  65249. if( res==0 ){
  65250. if( pPKey2->nField>1 ){
  65251. res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  65252. }else{
  65253. res = pPKey2->default_rc;
  65254. }
  65255. }else if( res>0 ){
  65256. res = pPKey2->r2;
  65257. }else{
  65258. res = pPKey2->r1;
  65259. }
  65260. }else if( res>0 ){
  65261. res = pPKey2->r2;
  65262. }else{
  65263. res = pPKey2->r1;
  65264. }
  65265. }
  65266. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  65267. || CORRUPT_DB
  65268. || pPKey2->pKeyInfo->db->mallocFailed
  65269. );
  65270. return res;
  65271. }
  65272. /*
  65273. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  65274. ** suitable for comparing serialized records to the unpacked record passed
  65275. ** as the only argument.
  65276. */
  65277. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  65278. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  65279. ** that the size-of-header varint that occurs at the start of each record
  65280. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  65281. ** also assumes that it is safe to overread a buffer by at least the
  65282. ** maximum possible legal header size plus 8 bytes. Because there is
  65283. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  65284. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  65285. ** limit the size of the header to 64 bytes in cases where the first field
  65286. ** is an integer.
  65287. **
  65288. ** The easiest way to enforce this limit is to consider only records with
  65289. ** 13 fields or less. If the first field is an integer, the maximum legal
  65290. ** header size is (12*5 + 1 + 1) bytes. */
  65291. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  65292. int flags = p->aMem[0].flags;
  65293. if( p->pKeyInfo->aSortOrder[0] ){
  65294. p->r1 = 1;
  65295. p->r2 = -1;
  65296. }else{
  65297. p->r1 = -1;
  65298. p->r2 = 1;
  65299. }
  65300. if( (flags & MEM_Int) ){
  65301. return vdbeRecordCompareInt;
  65302. }
  65303. testcase( flags & MEM_Real );
  65304. testcase( flags & MEM_Null );
  65305. testcase( flags & MEM_Blob );
  65306. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  65307. assert( flags & MEM_Str );
  65308. return vdbeRecordCompareString;
  65309. }
  65310. }
  65311. return sqlite3VdbeRecordCompare;
  65312. }
  65313. /*
  65314. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  65315. ** Read the rowid (the last field in the record) and store it in *rowid.
  65316. ** Return SQLITE_OK if everything works, or an error code otherwise.
  65317. **
  65318. ** pCur might be pointing to text obtained from a corrupt database file.
  65319. ** So the content cannot be trusted. Do appropriate checks on the content.
  65320. */
  65321. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  65322. i64 nCellKey = 0;
  65323. int rc;
  65324. u32 szHdr; /* Size of the header */
  65325. u32 typeRowid; /* Serial type of the rowid */
  65326. u32 lenRowid; /* Size of the rowid */
  65327. Mem m, v;
  65328. /* Get the size of the index entry. Only indices entries of less
  65329. ** than 2GiB are support - anything large must be database corruption.
  65330. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  65331. ** this code can safely assume that nCellKey is 32-bits
  65332. */
  65333. assert( sqlite3BtreeCursorIsValid(pCur) );
  65334. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  65335. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  65336. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  65337. /* Read in the complete content of the index entry */
  65338. sqlite3VdbeMemInit(&m, db, 0);
  65339. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  65340. if( rc ){
  65341. return rc;
  65342. }
  65343. /* The index entry must begin with a header size */
  65344. (void)getVarint32((u8*)m.z, szHdr);
  65345. testcase( szHdr==3 );
  65346. testcase( szHdr==m.n );
  65347. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  65348. goto idx_rowid_corruption;
  65349. }
  65350. /* The last field of the index should be an integer - the ROWID.
  65351. ** Verify that the last entry really is an integer. */
  65352. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  65353. testcase( typeRowid==1 );
  65354. testcase( typeRowid==2 );
  65355. testcase( typeRowid==3 );
  65356. testcase( typeRowid==4 );
  65357. testcase( typeRowid==5 );
  65358. testcase( typeRowid==6 );
  65359. testcase( typeRowid==8 );
  65360. testcase( typeRowid==9 );
  65361. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  65362. goto idx_rowid_corruption;
  65363. }
  65364. lenRowid = sqlite3SmallTypeSizes[typeRowid];
  65365. testcase( (u32)m.n==szHdr+lenRowid );
  65366. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  65367. goto idx_rowid_corruption;
  65368. }
  65369. /* Fetch the integer off the end of the index record */
  65370. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  65371. *rowid = v.u.i;
  65372. sqlite3VdbeMemRelease(&m);
  65373. return SQLITE_OK;
  65374. /* Jump here if database corruption is detected after m has been
  65375. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  65376. idx_rowid_corruption:
  65377. testcase( m.szMalloc!=0 );
  65378. sqlite3VdbeMemRelease(&m);
  65379. return SQLITE_CORRUPT_BKPT;
  65380. }
  65381. /*
  65382. ** Compare the key of the index entry that cursor pC is pointing to against
  65383. ** the key string in pUnpacked. Write into *pRes a number
  65384. ** that is negative, zero, or positive if pC is less than, equal to,
  65385. ** or greater than pUnpacked. Return SQLITE_OK on success.
  65386. **
  65387. ** pUnpacked is either created without a rowid or is truncated so that it
  65388. ** omits the rowid at the end. The rowid at the end of the index entry
  65389. ** is ignored as well. Hence, this routine only compares the prefixes
  65390. ** of the keys prior to the final rowid, not the entire key.
  65391. */
  65392. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  65393. sqlite3 *db, /* Database connection */
  65394. VdbeCursor *pC, /* The cursor to compare against */
  65395. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  65396. int *res /* Write the comparison result here */
  65397. ){
  65398. i64 nCellKey = 0;
  65399. int rc;
  65400. BtCursor *pCur = pC->pCursor;
  65401. Mem m;
  65402. assert( sqlite3BtreeCursorIsValid(pCur) );
  65403. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  65404. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  65405. /* nCellKey will always be between 0 and 0xffffffff because of the way
  65406. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  65407. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  65408. *res = 0;
  65409. return SQLITE_CORRUPT_BKPT;
  65410. }
  65411. sqlite3VdbeMemInit(&m, db, 0);
  65412. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
  65413. if( rc ){
  65414. return rc;
  65415. }
  65416. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  65417. sqlite3VdbeMemRelease(&m);
  65418. return SQLITE_OK;
  65419. }
  65420. /*
  65421. ** This routine sets the value to be returned by subsequent calls to
  65422. ** sqlite3_changes() on the database handle 'db'.
  65423. */
  65424. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  65425. assert( sqlite3_mutex_held(db->mutex) );
  65426. db->nChange = nChange;
  65427. db->nTotalChange += nChange;
  65428. }
  65429. /*
  65430. ** Set a flag in the vdbe to update the change counter when it is finalised
  65431. ** or reset.
  65432. */
  65433. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  65434. v->changeCntOn = 1;
  65435. }
  65436. /*
  65437. ** Mark every prepared statement associated with a database connection
  65438. ** as expired.
  65439. **
  65440. ** An expired statement means that recompilation of the statement is
  65441. ** recommend. Statements expire when things happen that make their
  65442. ** programs obsolete. Removing user-defined functions or collating
  65443. ** sequences, or changing an authorization function are the types of
  65444. ** things that make prepared statements obsolete.
  65445. */
  65446. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  65447. Vdbe *p;
  65448. for(p = db->pVdbe; p; p=p->pNext){
  65449. p->expired = 1;
  65450. }
  65451. }
  65452. /*
  65453. ** Return the database associated with the Vdbe.
  65454. */
  65455. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  65456. return v->db;
  65457. }
  65458. /*
  65459. ** Return a pointer to an sqlite3_value structure containing the value bound
  65460. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  65461. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  65462. ** constants) to the value before returning it.
  65463. **
  65464. ** The returned value must be freed by the caller using sqlite3ValueFree().
  65465. */
  65466. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  65467. assert( iVar>0 );
  65468. if( v ){
  65469. Mem *pMem = &v->aVar[iVar-1];
  65470. if( 0==(pMem->flags & MEM_Null) ){
  65471. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  65472. if( pRet ){
  65473. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  65474. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  65475. }
  65476. return pRet;
  65477. }
  65478. }
  65479. return 0;
  65480. }
  65481. /*
  65482. ** Configure SQL variable iVar so that binding a new value to it signals
  65483. ** to sqlite3_reoptimize() that re-preparing the statement may result
  65484. ** in a better query plan.
  65485. */
  65486. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  65487. assert( iVar>0 );
  65488. if( iVar>32 ){
  65489. v->expmask = 0xffffffff;
  65490. }else{
  65491. v->expmask |= ((u32)1 << (iVar-1));
  65492. }
  65493. }
  65494. #ifndef SQLITE_OMIT_VIRTUALTABLE
  65495. /*
  65496. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  65497. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  65498. ** in memory obtained from sqlite3DbMalloc).
  65499. */
  65500. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  65501. sqlite3 *db = p->db;
  65502. sqlite3DbFree(db, p->zErrMsg);
  65503. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  65504. sqlite3_free(pVtab->zErrMsg);
  65505. pVtab->zErrMsg = 0;
  65506. }
  65507. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  65508. /************** End of vdbeaux.c *********************************************/
  65509. /************** Begin file vdbeapi.c *****************************************/
  65510. /*
  65511. ** 2004 May 26
  65512. **
  65513. ** The author disclaims copyright to this source code. In place of
  65514. ** a legal notice, here is a blessing:
  65515. **
  65516. ** May you do good and not evil.
  65517. ** May you find forgiveness for yourself and forgive others.
  65518. ** May you share freely, never taking more than you give.
  65519. **
  65520. *************************************************************************
  65521. **
  65522. ** This file contains code use to implement APIs that are part of the
  65523. ** VDBE.
  65524. */
  65525. /* #include "sqliteInt.h" */
  65526. /* #include "vdbeInt.h" */
  65527. #ifndef SQLITE_OMIT_DEPRECATED
  65528. /*
  65529. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  65530. ** to be recompiled. A statement needs to be recompiled whenever the
  65531. ** execution environment changes in a way that would alter the program
  65532. ** that sqlite3_prepare() generates. For example, if new functions or
  65533. ** collating sequences are registered or if an authorizer function is
  65534. ** added or changed.
  65535. */
  65536. SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
  65537. Vdbe *p = (Vdbe*)pStmt;
  65538. return p==0 || p->expired;
  65539. }
  65540. #endif
  65541. /*
  65542. ** Check on a Vdbe to make sure it has not been finalized. Log
  65543. ** an error and return true if it has been finalized (or is otherwise
  65544. ** invalid). Return false if it is ok.
  65545. */
  65546. static int vdbeSafety(Vdbe *p){
  65547. if( p->db==0 ){
  65548. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  65549. return 1;
  65550. }else{
  65551. return 0;
  65552. }
  65553. }
  65554. static int vdbeSafetyNotNull(Vdbe *p){
  65555. if( p==0 ){
  65556. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  65557. return 1;
  65558. }else{
  65559. return vdbeSafety(p);
  65560. }
  65561. }
  65562. #ifndef SQLITE_OMIT_TRACE
  65563. /*
  65564. ** Invoke the profile callback. This routine is only called if we already
  65565. ** know that the profile callback is defined and needs to be invoked.
  65566. */
  65567. static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p){
  65568. sqlite3_int64 iNow;
  65569. assert( p->startTime>0 );
  65570. assert( db->xProfile!=0 );
  65571. assert( db->init.busy==0 );
  65572. assert( p->zSql!=0 );
  65573. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  65574. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  65575. p->startTime = 0;
  65576. }
  65577. /*
  65578. ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
  65579. ** is needed, and it invokes the callback if it is needed.
  65580. */
  65581. # define checkProfileCallback(DB,P) \
  65582. if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
  65583. #else
  65584. # define checkProfileCallback(DB,P) /*no-op*/
  65585. #endif
  65586. /*
  65587. ** The following routine destroys a virtual machine that is created by
  65588. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  65589. ** success/failure code that describes the result of executing the virtual
  65590. ** machine.
  65591. **
  65592. ** This routine sets the error code and string returned by
  65593. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  65594. */
  65595. SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
  65596. int rc;
  65597. if( pStmt==0 ){
  65598. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  65599. ** pointer is a harmless no-op. */
  65600. rc = SQLITE_OK;
  65601. }else{
  65602. Vdbe *v = (Vdbe*)pStmt;
  65603. sqlite3 *db = v->db;
  65604. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  65605. sqlite3_mutex_enter(db->mutex);
  65606. checkProfileCallback(db, v);
  65607. rc = sqlite3VdbeFinalize(v);
  65608. rc = sqlite3ApiExit(db, rc);
  65609. sqlite3LeaveMutexAndCloseZombie(db);
  65610. }
  65611. return rc;
  65612. }
  65613. /*
  65614. ** Terminate the current execution of an SQL statement and reset it
  65615. ** back to its starting state so that it can be reused. A success code from
  65616. ** the prior execution is returned.
  65617. **
  65618. ** This routine sets the error code and string returned by
  65619. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  65620. */
  65621. SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
  65622. int rc;
  65623. if( pStmt==0 ){
  65624. rc = SQLITE_OK;
  65625. }else{
  65626. Vdbe *v = (Vdbe*)pStmt;
  65627. sqlite3 *db = v->db;
  65628. sqlite3_mutex_enter(db->mutex);
  65629. checkProfileCallback(db, v);
  65630. rc = sqlite3VdbeReset(v);
  65631. sqlite3VdbeRewind(v);
  65632. assert( (rc & (db->errMask))==rc );
  65633. rc = sqlite3ApiExit(db, rc);
  65634. sqlite3_mutex_leave(db->mutex);
  65635. }
  65636. return rc;
  65637. }
  65638. /*
  65639. ** Set all the parameters in the compiled SQL statement to NULL.
  65640. */
  65641. SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  65642. int i;
  65643. int rc = SQLITE_OK;
  65644. Vdbe *p = (Vdbe*)pStmt;
  65645. #if SQLITE_THREADSAFE
  65646. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  65647. #endif
  65648. sqlite3_mutex_enter(mutex);
  65649. for(i=0; i<p->nVar; i++){
  65650. sqlite3VdbeMemRelease(&p->aVar[i]);
  65651. p->aVar[i].flags = MEM_Null;
  65652. }
  65653. if( p->isPrepareV2 && p->expmask ){
  65654. p->expired = 1;
  65655. }
  65656. sqlite3_mutex_leave(mutex);
  65657. return rc;
  65658. }
  65659. /**************************** sqlite3_value_ *******************************
  65660. ** The following routines extract information from a Mem or sqlite3_value
  65661. ** structure.
  65662. */
  65663. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
  65664. Mem *p = (Mem*)pVal;
  65665. if( p->flags & (MEM_Blob|MEM_Str) ){
  65666. if( sqlite3VdbeMemExpandBlob(p)!=SQLITE_OK ){
  65667. assert( p->flags==MEM_Null && p->z==0 );
  65668. return 0;
  65669. }
  65670. p->flags |= MEM_Blob;
  65671. return p->n ? p->z : 0;
  65672. }else{
  65673. return sqlite3_value_text(pVal);
  65674. }
  65675. }
  65676. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
  65677. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  65678. }
  65679. SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
  65680. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  65681. }
  65682. SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
  65683. return sqlite3VdbeRealValue((Mem*)pVal);
  65684. }
  65685. SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
  65686. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  65687. }
  65688. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
  65689. return sqlite3VdbeIntValue((Mem*)pVal);
  65690. }
  65691. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
  65692. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  65693. }
  65694. #ifndef SQLITE_OMIT_UTF16
  65695. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
  65696. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  65697. }
  65698. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
  65699. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  65700. }
  65701. SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
  65702. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  65703. }
  65704. #endif /* SQLITE_OMIT_UTF16 */
  65705. /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
  65706. ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
  65707. ** point number string BLOB NULL
  65708. */
  65709. SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
  65710. static const u8 aType[] = {
  65711. SQLITE_BLOB, /* 0x00 */
  65712. SQLITE_NULL, /* 0x01 */
  65713. SQLITE_TEXT, /* 0x02 */
  65714. SQLITE_NULL, /* 0x03 */
  65715. SQLITE_INTEGER, /* 0x04 */
  65716. SQLITE_NULL, /* 0x05 */
  65717. SQLITE_INTEGER, /* 0x06 */
  65718. SQLITE_NULL, /* 0x07 */
  65719. SQLITE_FLOAT, /* 0x08 */
  65720. SQLITE_NULL, /* 0x09 */
  65721. SQLITE_FLOAT, /* 0x0a */
  65722. SQLITE_NULL, /* 0x0b */
  65723. SQLITE_INTEGER, /* 0x0c */
  65724. SQLITE_NULL, /* 0x0d */
  65725. SQLITE_INTEGER, /* 0x0e */
  65726. SQLITE_NULL, /* 0x0f */
  65727. SQLITE_BLOB, /* 0x10 */
  65728. SQLITE_NULL, /* 0x11 */
  65729. SQLITE_TEXT, /* 0x12 */
  65730. SQLITE_NULL, /* 0x13 */
  65731. SQLITE_INTEGER, /* 0x14 */
  65732. SQLITE_NULL, /* 0x15 */
  65733. SQLITE_INTEGER, /* 0x16 */
  65734. SQLITE_NULL, /* 0x17 */
  65735. SQLITE_FLOAT, /* 0x18 */
  65736. SQLITE_NULL, /* 0x19 */
  65737. SQLITE_FLOAT, /* 0x1a */
  65738. SQLITE_NULL, /* 0x1b */
  65739. SQLITE_INTEGER, /* 0x1c */
  65740. SQLITE_NULL, /* 0x1d */
  65741. SQLITE_INTEGER, /* 0x1e */
  65742. SQLITE_NULL, /* 0x1f */
  65743. };
  65744. return aType[pVal->flags&MEM_AffMask];
  65745. }
  65746. /* Make a copy of an sqlite3_value object
  65747. */
  65748. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *pOrig){
  65749. sqlite3_value *pNew;
  65750. if( pOrig==0 ) return 0;
  65751. pNew = sqlite3_malloc( sizeof(*pNew) );
  65752. if( pNew==0 ) return 0;
  65753. memset(pNew, 0, sizeof(*pNew));
  65754. memcpy(pNew, pOrig, MEMCELLSIZE);
  65755. pNew->flags &= ~MEM_Dyn;
  65756. pNew->db = 0;
  65757. if( pNew->flags&(MEM_Str|MEM_Blob) ){
  65758. pNew->flags &= ~(MEM_Static|MEM_Dyn);
  65759. pNew->flags |= MEM_Ephem;
  65760. if( sqlite3VdbeMemMakeWriteable(pNew)!=SQLITE_OK ){
  65761. sqlite3ValueFree(pNew);
  65762. pNew = 0;
  65763. }
  65764. }
  65765. return pNew;
  65766. }
  65767. /* Destroy an sqlite3_value object previously obtained from
  65768. ** sqlite3_value_dup().
  65769. */
  65770. SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *pOld){
  65771. sqlite3ValueFree(pOld);
  65772. }
  65773. /**************************** sqlite3_result_ *******************************
  65774. ** The following routines are used by user-defined functions to specify
  65775. ** the function result.
  65776. **
  65777. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  65778. ** result as a string or blob but if the string or blob is too large, it
  65779. ** then sets the error code to SQLITE_TOOBIG
  65780. **
  65781. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  65782. ** on value P is not going to be used and need to be destroyed.
  65783. */
  65784. static void setResultStrOrError(
  65785. sqlite3_context *pCtx, /* Function context */
  65786. const char *z, /* String pointer */
  65787. int n, /* Bytes in string, or negative */
  65788. u8 enc, /* Encoding of z. 0 for BLOBs */
  65789. void (*xDel)(void*) /* Destructor function */
  65790. ){
  65791. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  65792. sqlite3_result_error_toobig(pCtx);
  65793. }
  65794. }
  65795. static int invokeValueDestructor(
  65796. const void *p, /* Value to destroy */
  65797. void (*xDel)(void*), /* The destructor */
  65798. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  65799. ){
  65800. assert( xDel!=SQLITE_DYNAMIC );
  65801. if( xDel==0 ){
  65802. /* noop */
  65803. }else if( xDel==SQLITE_TRANSIENT ){
  65804. /* noop */
  65805. }else{
  65806. xDel((void*)p);
  65807. }
  65808. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  65809. return SQLITE_TOOBIG;
  65810. }
  65811. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
  65812. sqlite3_context *pCtx,
  65813. const void *z,
  65814. int n,
  65815. void (*xDel)(void *)
  65816. ){
  65817. assert( n>=0 );
  65818. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65819. setResultStrOrError(pCtx, z, n, 0, xDel);
  65820. }
  65821. SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
  65822. sqlite3_context *pCtx,
  65823. const void *z,
  65824. sqlite3_uint64 n,
  65825. void (*xDel)(void *)
  65826. ){
  65827. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65828. assert( xDel!=SQLITE_DYNAMIC );
  65829. if( n>0x7fffffff ){
  65830. (void)invokeValueDestructor(z, xDel, pCtx);
  65831. }else{
  65832. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  65833. }
  65834. }
  65835. SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  65836. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65837. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  65838. }
  65839. SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  65840. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65841. pCtx->isError = SQLITE_ERROR;
  65842. pCtx->fErrorOrAux = 1;
  65843. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  65844. }
  65845. #ifndef SQLITE_OMIT_UTF16
  65846. SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  65847. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65848. pCtx->isError = SQLITE_ERROR;
  65849. pCtx->fErrorOrAux = 1;
  65850. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  65851. }
  65852. #endif
  65853. SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  65854. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65855. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  65856. }
  65857. SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  65858. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65859. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  65860. }
  65861. SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
  65862. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65863. sqlite3VdbeMemSetNull(pCtx->pOut);
  65864. }
  65865. SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
  65866. sqlite3_context *pCtx,
  65867. const char *z,
  65868. int n,
  65869. void (*xDel)(void *)
  65870. ){
  65871. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65872. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  65873. }
  65874. SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
  65875. sqlite3_context *pCtx,
  65876. const char *z,
  65877. sqlite3_uint64 n,
  65878. void (*xDel)(void *),
  65879. unsigned char enc
  65880. ){
  65881. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65882. assert( xDel!=SQLITE_DYNAMIC );
  65883. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  65884. if( n>0x7fffffff ){
  65885. (void)invokeValueDestructor(z, xDel, pCtx);
  65886. }else{
  65887. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  65888. }
  65889. }
  65890. #ifndef SQLITE_OMIT_UTF16
  65891. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
  65892. sqlite3_context *pCtx,
  65893. const void *z,
  65894. int n,
  65895. void (*xDel)(void *)
  65896. ){
  65897. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65898. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  65899. }
  65900. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
  65901. sqlite3_context *pCtx,
  65902. const void *z,
  65903. int n,
  65904. void (*xDel)(void *)
  65905. ){
  65906. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65907. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  65908. }
  65909. SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
  65910. sqlite3_context *pCtx,
  65911. const void *z,
  65912. int n,
  65913. void (*xDel)(void *)
  65914. ){
  65915. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65916. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  65917. }
  65918. #endif /* SQLITE_OMIT_UTF16 */
  65919. SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  65920. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65921. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  65922. }
  65923. SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  65924. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65925. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  65926. }
  65927. SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *pCtx, u64 n){
  65928. Mem *pOut = pCtx->pOut;
  65929. assert( sqlite3_mutex_held(pOut->db->mutex) );
  65930. if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65931. return SQLITE_TOOBIG;
  65932. }
  65933. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
  65934. return SQLITE_OK;
  65935. }
  65936. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  65937. pCtx->isError = errCode;
  65938. pCtx->fErrorOrAux = 1;
  65939. #ifdef SQLITE_DEBUG
  65940. if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
  65941. #endif
  65942. if( pCtx->pOut->flags & MEM_Null ){
  65943. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  65944. SQLITE_UTF8, SQLITE_STATIC);
  65945. }
  65946. }
  65947. /* Force an SQLITE_TOOBIG error. */
  65948. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
  65949. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65950. pCtx->isError = SQLITE_TOOBIG;
  65951. pCtx->fErrorOrAux = 1;
  65952. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  65953. SQLITE_UTF8, SQLITE_STATIC);
  65954. }
  65955. /* An SQLITE_NOMEM error. */
  65956. SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
  65957. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  65958. sqlite3VdbeMemSetNull(pCtx->pOut);
  65959. pCtx->isError = SQLITE_NOMEM;
  65960. pCtx->fErrorOrAux = 1;
  65961. pCtx->pOut->db->mallocFailed = 1;
  65962. }
  65963. /*
  65964. ** This function is called after a transaction has been committed. It
  65965. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  65966. */
  65967. static int doWalCallbacks(sqlite3 *db){
  65968. int rc = SQLITE_OK;
  65969. #ifndef SQLITE_OMIT_WAL
  65970. int i;
  65971. for(i=0; i<db->nDb; i++){
  65972. Btree *pBt = db->aDb[i].pBt;
  65973. if( pBt ){
  65974. int nEntry;
  65975. sqlite3BtreeEnter(pBt);
  65976. nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  65977. sqlite3BtreeLeave(pBt);
  65978. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  65979. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  65980. }
  65981. }
  65982. }
  65983. #endif
  65984. return rc;
  65985. }
  65986. /*
  65987. ** Execute the statement pStmt, either until a row of data is ready, the
  65988. ** statement is completely executed or an error occurs.
  65989. **
  65990. ** This routine implements the bulk of the logic behind the sqlite_step()
  65991. ** API. The only thing omitted is the automatic recompile if a
  65992. ** schema change has occurred. That detail is handled by the
  65993. ** outer sqlite3_step() wrapper procedure.
  65994. */
  65995. static int sqlite3Step(Vdbe *p){
  65996. sqlite3 *db;
  65997. int rc;
  65998. assert(p);
  65999. if( p->magic!=VDBE_MAGIC_RUN ){
  66000. /* We used to require that sqlite3_reset() be called before retrying
  66001. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  66002. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  66003. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  66004. ** This "automatic-reset" change is not technically an incompatibility,
  66005. ** since any application that receives an SQLITE_MISUSE is broken by
  66006. ** definition.
  66007. **
  66008. ** Nevertheless, some published applications that were originally written
  66009. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  66010. ** returns, and those were broken by the automatic-reset change. As a
  66011. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  66012. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  66013. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  66014. ** or SQLITE_BUSY error.
  66015. */
  66016. #ifdef SQLITE_OMIT_AUTORESET
  66017. if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
  66018. sqlite3_reset((sqlite3_stmt*)p);
  66019. }else{
  66020. return SQLITE_MISUSE_BKPT;
  66021. }
  66022. #else
  66023. sqlite3_reset((sqlite3_stmt*)p);
  66024. #endif
  66025. }
  66026. /* Check that malloc() has not failed. If it has, return early. */
  66027. db = p->db;
  66028. if( db->mallocFailed ){
  66029. p->rc = SQLITE_NOMEM;
  66030. return SQLITE_NOMEM;
  66031. }
  66032. if( p->pc<=0 && p->expired ){
  66033. p->rc = SQLITE_SCHEMA;
  66034. rc = SQLITE_ERROR;
  66035. goto end_of_step;
  66036. }
  66037. if( p->pc<0 ){
  66038. /* If there are no other statements currently running, then
  66039. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  66040. ** from interrupting a statement that has not yet started.
  66041. */
  66042. if( db->nVdbeActive==0 ){
  66043. db->u1.isInterrupted = 0;
  66044. }
  66045. assert( db->nVdbeWrite>0 || db->autoCommit==0
  66046. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  66047. );
  66048. #ifndef SQLITE_OMIT_TRACE
  66049. if( db->xProfile && !db->init.busy && p->zSql ){
  66050. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  66051. }else{
  66052. assert( p->startTime==0 );
  66053. }
  66054. #endif
  66055. db->nVdbeActive++;
  66056. if( p->readOnly==0 ) db->nVdbeWrite++;
  66057. if( p->bIsReader ) db->nVdbeRead++;
  66058. p->pc = 0;
  66059. }
  66060. #ifdef SQLITE_DEBUG
  66061. p->rcApp = SQLITE_OK;
  66062. #endif
  66063. #ifndef SQLITE_OMIT_EXPLAIN
  66064. if( p->explain ){
  66065. rc = sqlite3VdbeList(p);
  66066. }else
  66067. #endif /* SQLITE_OMIT_EXPLAIN */
  66068. {
  66069. db->nVdbeExec++;
  66070. rc = sqlite3VdbeExec(p);
  66071. db->nVdbeExec--;
  66072. }
  66073. #ifndef SQLITE_OMIT_TRACE
  66074. /* If the statement completed successfully, invoke the profile callback */
  66075. if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
  66076. #endif
  66077. if( rc==SQLITE_DONE ){
  66078. assert( p->rc==SQLITE_OK );
  66079. p->rc = doWalCallbacks(db);
  66080. if( p->rc!=SQLITE_OK ){
  66081. rc = SQLITE_ERROR;
  66082. }
  66083. }
  66084. db->errCode = rc;
  66085. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  66086. p->rc = SQLITE_NOMEM;
  66087. }
  66088. end_of_step:
  66089. /* At this point local variable rc holds the value that should be
  66090. ** returned if this statement was compiled using the legacy
  66091. ** sqlite3_prepare() interface. According to the docs, this can only
  66092. ** be one of the values in the first assert() below. Variable p->rc
  66093. ** contains the value that would be returned if sqlite3_finalize()
  66094. ** were called on statement p.
  66095. */
  66096. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  66097. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  66098. );
  66099. assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
  66100. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  66101. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  66102. ** error has occurred, then return the error code in p->rc to the
  66103. ** caller. Set the error code in the database handle to the same value.
  66104. */
  66105. rc = sqlite3VdbeTransferError(p);
  66106. }
  66107. return (rc&db->errMask);
  66108. }
  66109. /*
  66110. ** This is the top-level implementation of sqlite3_step(). Call
  66111. ** sqlite3Step() to do most of the work. If a schema error occurs,
  66112. ** call sqlite3Reprepare() and try again.
  66113. */
  66114. SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
  66115. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  66116. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  66117. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  66118. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  66119. sqlite3 *db; /* The database connection */
  66120. if( vdbeSafetyNotNull(v) ){
  66121. return SQLITE_MISUSE_BKPT;
  66122. }
  66123. db = v->db;
  66124. sqlite3_mutex_enter(db->mutex);
  66125. v->doingRerun = 0;
  66126. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  66127. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  66128. int savedPc = v->pc;
  66129. rc2 = rc = sqlite3Reprepare(v);
  66130. if( rc!=SQLITE_OK) break;
  66131. sqlite3_reset(pStmt);
  66132. if( savedPc>=0 ) v->doingRerun = 1;
  66133. assert( v->expired==0 );
  66134. }
  66135. if( rc2!=SQLITE_OK ){
  66136. /* This case occurs after failing to recompile an sql statement.
  66137. ** The error message from the SQL compiler has already been loaded
  66138. ** into the database handle. This block copies the error message
  66139. ** from the database handle into the statement and sets the statement
  66140. ** program counter to 0 to ensure that when the statement is
  66141. ** finalized or reset the parser error message is available via
  66142. ** sqlite3_errmsg() and sqlite3_errcode().
  66143. */
  66144. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  66145. sqlite3DbFree(db, v->zErrMsg);
  66146. if( !db->mallocFailed ){
  66147. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  66148. v->rc = rc2;
  66149. } else {
  66150. v->zErrMsg = 0;
  66151. v->rc = rc = SQLITE_NOMEM;
  66152. }
  66153. }
  66154. rc = sqlite3ApiExit(db, rc);
  66155. sqlite3_mutex_leave(db->mutex);
  66156. return rc;
  66157. }
  66158. /*
  66159. ** Extract the user data from a sqlite3_context structure and return a
  66160. ** pointer to it.
  66161. */
  66162. SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
  66163. assert( p && p->pFunc );
  66164. return p->pFunc->pUserData;
  66165. }
  66166. /*
  66167. ** Extract the user data from a sqlite3_context structure and return a
  66168. ** pointer to it.
  66169. **
  66170. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  66171. ** returns a copy of the pointer to the database connection (the 1st
  66172. ** parameter) of the sqlite3_create_function() and
  66173. ** sqlite3_create_function16() routines that originally registered the
  66174. ** application defined function.
  66175. */
  66176. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
  66177. assert( p && p->pFunc );
  66178. return p->pOut->db;
  66179. }
  66180. /*
  66181. ** Return the current time for a statement. If the current time
  66182. ** is requested more than once within the same run of a single prepared
  66183. ** statement, the exact same time is returned for each invocation regardless
  66184. ** of the amount of time that elapses between invocations. In other words,
  66185. ** the time returned is always the time of the first call.
  66186. */
  66187. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  66188. int rc;
  66189. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  66190. sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
  66191. assert( p->pVdbe!=0 );
  66192. #else
  66193. sqlite3_int64 iTime = 0;
  66194. sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
  66195. #endif
  66196. if( *piTime==0 ){
  66197. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
  66198. if( rc ) *piTime = 0;
  66199. }
  66200. return *piTime;
  66201. }
  66202. /*
  66203. ** The following is the implementation of an SQL function that always
  66204. ** fails with an error message stating that the function is used in the
  66205. ** wrong context. The sqlite3_overload_function() API might construct
  66206. ** SQL function that use this routine so that the functions will exist
  66207. ** for name resolution but are actually overloaded by the xFindFunction
  66208. ** method of virtual tables.
  66209. */
  66210. SQLITE_PRIVATE void sqlite3InvalidFunction(
  66211. sqlite3_context *context, /* The function calling context */
  66212. int NotUsed, /* Number of arguments to the function */
  66213. sqlite3_value **NotUsed2 /* Value of each argument */
  66214. ){
  66215. const char *zName = context->pFunc->zName;
  66216. char *zErr;
  66217. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  66218. zErr = sqlite3_mprintf(
  66219. "unable to use function %s in the requested context", zName);
  66220. sqlite3_result_error(context, zErr, -1);
  66221. sqlite3_free(zErr);
  66222. }
  66223. /*
  66224. ** Create a new aggregate context for p and return a pointer to
  66225. ** its pMem->z element.
  66226. */
  66227. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  66228. Mem *pMem = p->pMem;
  66229. assert( (pMem->flags & MEM_Agg)==0 );
  66230. if( nByte<=0 ){
  66231. sqlite3VdbeMemSetNull(pMem);
  66232. pMem->z = 0;
  66233. }else{
  66234. sqlite3VdbeMemClearAndResize(pMem, nByte);
  66235. pMem->flags = MEM_Agg;
  66236. pMem->u.pDef = p->pFunc;
  66237. if( pMem->z ){
  66238. memset(pMem->z, 0, nByte);
  66239. }
  66240. }
  66241. return (void*)pMem->z;
  66242. }
  66243. /*
  66244. ** Allocate or return the aggregate context for a user function. A new
  66245. ** context is allocated on the first call. Subsequent calls return the
  66246. ** same context that was returned on prior calls.
  66247. */
  66248. SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  66249. assert( p && p->pFunc && p->pFunc->xStep );
  66250. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  66251. testcase( nByte<0 );
  66252. if( (p->pMem->flags & MEM_Agg)==0 ){
  66253. return createAggContext(p, nByte);
  66254. }else{
  66255. return (void*)p->pMem->z;
  66256. }
  66257. }
  66258. /*
  66259. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  66260. ** the user-function defined by pCtx.
  66261. */
  66262. SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  66263. AuxData *pAuxData;
  66264. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66265. #if SQLITE_ENABLE_STAT3_OR_STAT4
  66266. if( pCtx->pVdbe==0 ) return 0;
  66267. #else
  66268. assert( pCtx->pVdbe!=0 );
  66269. #endif
  66270. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  66271. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  66272. }
  66273. return (pAuxData ? pAuxData->pAux : 0);
  66274. }
  66275. /*
  66276. ** Set the auxiliary data pointer and delete function, for the iArg'th
  66277. ** argument to the user-function defined by pCtx. Any previous value is
  66278. ** deleted by calling the delete function specified when it was set.
  66279. */
  66280. SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
  66281. sqlite3_context *pCtx,
  66282. int iArg,
  66283. void *pAux,
  66284. void (*xDelete)(void*)
  66285. ){
  66286. AuxData *pAuxData;
  66287. Vdbe *pVdbe = pCtx->pVdbe;
  66288. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  66289. if( iArg<0 ) goto failed;
  66290. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  66291. if( pVdbe==0 ) goto failed;
  66292. #else
  66293. assert( pVdbe!=0 );
  66294. #endif
  66295. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  66296. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  66297. }
  66298. if( pAuxData==0 ){
  66299. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  66300. if( !pAuxData ) goto failed;
  66301. pAuxData->iOp = pCtx->iOp;
  66302. pAuxData->iArg = iArg;
  66303. pAuxData->pNext = pVdbe->pAuxData;
  66304. pVdbe->pAuxData = pAuxData;
  66305. if( pCtx->fErrorOrAux==0 ){
  66306. pCtx->isError = 0;
  66307. pCtx->fErrorOrAux = 1;
  66308. }
  66309. }else if( pAuxData->xDelete ){
  66310. pAuxData->xDelete(pAuxData->pAux);
  66311. }
  66312. pAuxData->pAux = pAux;
  66313. pAuxData->xDelete = xDelete;
  66314. return;
  66315. failed:
  66316. if( xDelete ){
  66317. xDelete(pAux);
  66318. }
  66319. }
  66320. #ifndef SQLITE_OMIT_DEPRECATED
  66321. /*
  66322. ** Return the number of times the Step function of an aggregate has been
  66323. ** called.
  66324. **
  66325. ** This function is deprecated. Do not use it for new code. It is
  66326. ** provide only to avoid breaking legacy code. New aggregate function
  66327. ** implementations should keep their own counts within their aggregate
  66328. ** context.
  66329. */
  66330. SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
  66331. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  66332. return p->pMem->n;
  66333. }
  66334. #endif
  66335. /*
  66336. ** Return the number of columns in the result set for the statement pStmt.
  66337. */
  66338. SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
  66339. Vdbe *pVm = (Vdbe *)pStmt;
  66340. return pVm ? pVm->nResColumn : 0;
  66341. }
  66342. /*
  66343. ** Return the number of values available from the current row of the
  66344. ** currently executing statement pStmt.
  66345. */
  66346. SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
  66347. Vdbe *pVm = (Vdbe *)pStmt;
  66348. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  66349. return pVm->nResColumn;
  66350. }
  66351. /*
  66352. ** Return a pointer to static memory containing an SQL NULL value.
  66353. */
  66354. static const Mem *columnNullValue(void){
  66355. /* Even though the Mem structure contains an element
  66356. ** of type i64, on certain architectures (x86) with certain compiler
  66357. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  66358. ** instead of an 8-byte one. This all works fine, except that when
  66359. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  66360. ** that a Mem structure is located on an 8-byte boundary. To prevent
  66361. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  66362. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  66363. ** __attribute__((aligned(8))) macro. */
  66364. static const Mem nullMem
  66365. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  66366. __attribute__((aligned(8)))
  66367. #endif
  66368. = {
  66369. /* .u = */ {0},
  66370. /* .flags = */ MEM_Null,
  66371. /* .enc = */ 0,
  66372. /* .n = */ 0,
  66373. /* .z = */ 0,
  66374. /* .zMalloc = */ 0,
  66375. /* .szMalloc = */ 0,
  66376. /* .iPadding1 = */ 0,
  66377. /* .db = */ 0,
  66378. /* .xDel = */ 0,
  66379. #ifdef SQLITE_DEBUG
  66380. /* .pScopyFrom = */ 0,
  66381. /* .pFiller = */ 0,
  66382. #endif
  66383. };
  66384. return &nullMem;
  66385. }
  66386. /*
  66387. ** Check to see if column iCol of the given statement is valid. If
  66388. ** it is, return a pointer to the Mem for the value of that column.
  66389. ** If iCol is not valid, return a pointer to a Mem which has a value
  66390. ** of NULL.
  66391. */
  66392. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  66393. Vdbe *pVm;
  66394. Mem *pOut;
  66395. pVm = (Vdbe *)pStmt;
  66396. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  66397. sqlite3_mutex_enter(pVm->db->mutex);
  66398. pOut = &pVm->pResultSet[i];
  66399. }else{
  66400. if( pVm && ALWAYS(pVm->db) ){
  66401. sqlite3_mutex_enter(pVm->db->mutex);
  66402. sqlite3Error(pVm->db, SQLITE_RANGE);
  66403. }
  66404. pOut = (Mem*)columnNullValue();
  66405. }
  66406. return pOut;
  66407. }
  66408. /*
  66409. ** This function is called after invoking an sqlite3_value_XXX function on a
  66410. ** column value (i.e. a value returned by evaluating an SQL expression in the
  66411. ** select list of a SELECT statement) that may cause a malloc() failure. If
  66412. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  66413. ** code of statement pStmt set to SQLITE_NOMEM.
  66414. **
  66415. ** Specifically, this is called from within:
  66416. **
  66417. ** sqlite3_column_int()
  66418. ** sqlite3_column_int64()
  66419. ** sqlite3_column_text()
  66420. ** sqlite3_column_text16()
  66421. ** sqlite3_column_real()
  66422. ** sqlite3_column_bytes()
  66423. ** sqlite3_column_bytes16()
  66424. ** sqiite3_column_blob()
  66425. */
  66426. static void columnMallocFailure(sqlite3_stmt *pStmt)
  66427. {
  66428. /* If malloc() failed during an encoding conversion within an
  66429. ** sqlite3_column_XXX API, then set the return code of the statement to
  66430. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  66431. ** and _finalize() will return NOMEM.
  66432. */
  66433. Vdbe *p = (Vdbe *)pStmt;
  66434. if( p ){
  66435. p->rc = sqlite3ApiExit(p->db, p->rc);
  66436. sqlite3_mutex_leave(p->db->mutex);
  66437. }
  66438. }
  66439. /**************************** sqlite3_column_ *******************************
  66440. ** The following routines are used to access elements of the current row
  66441. ** in the result set.
  66442. */
  66443. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  66444. const void *val;
  66445. val = sqlite3_value_blob( columnMem(pStmt,i) );
  66446. /* Even though there is no encoding conversion, value_blob() might
  66447. ** need to call malloc() to expand the result of a zeroblob()
  66448. ** expression.
  66449. */
  66450. columnMallocFailure(pStmt);
  66451. return val;
  66452. }
  66453. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  66454. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  66455. columnMallocFailure(pStmt);
  66456. return val;
  66457. }
  66458. SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  66459. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  66460. columnMallocFailure(pStmt);
  66461. return val;
  66462. }
  66463. SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  66464. double val = sqlite3_value_double( columnMem(pStmt,i) );
  66465. columnMallocFailure(pStmt);
  66466. return val;
  66467. }
  66468. SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  66469. int val = sqlite3_value_int( columnMem(pStmt,i) );
  66470. columnMallocFailure(pStmt);
  66471. return val;
  66472. }
  66473. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  66474. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  66475. columnMallocFailure(pStmt);
  66476. return val;
  66477. }
  66478. SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  66479. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  66480. columnMallocFailure(pStmt);
  66481. return val;
  66482. }
  66483. SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  66484. Mem *pOut = columnMem(pStmt, i);
  66485. if( pOut->flags&MEM_Static ){
  66486. pOut->flags &= ~MEM_Static;
  66487. pOut->flags |= MEM_Ephem;
  66488. }
  66489. columnMallocFailure(pStmt);
  66490. return (sqlite3_value *)pOut;
  66491. }
  66492. #ifndef SQLITE_OMIT_UTF16
  66493. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  66494. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  66495. columnMallocFailure(pStmt);
  66496. return val;
  66497. }
  66498. #endif /* SQLITE_OMIT_UTF16 */
  66499. SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  66500. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  66501. columnMallocFailure(pStmt);
  66502. return iType;
  66503. }
  66504. /*
  66505. ** Convert the N-th element of pStmt->pColName[] into a string using
  66506. ** xFunc() then return that string. If N is out of range, return 0.
  66507. **
  66508. ** There are up to 5 names for each column. useType determines which
  66509. ** name is returned. Here are the names:
  66510. **
  66511. ** 0 The column name as it should be displayed for output
  66512. ** 1 The datatype name for the column
  66513. ** 2 The name of the database that the column derives from
  66514. ** 3 The name of the table that the column derives from
  66515. ** 4 The name of the table column that the result column derives from
  66516. **
  66517. ** If the result is not a simple column reference (if it is an expression
  66518. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  66519. */
  66520. static const void *columnName(
  66521. sqlite3_stmt *pStmt,
  66522. int N,
  66523. const void *(*xFunc)(Mem*),
  66524. int useType
  66525. ){
  66526. const void *ret;
  66527. Vdbe *p;
  66528. int n;
  66529. sqlite3 *db;
  66530. #ifdef SQLITE_ENABLE_API_ARMOR
  66531. if( pStmt==0 ){
  66532. (void)SQLITE_MISUSE_BKPT;
  66533. return 0;
  66534. }
  66535. #endif
  66536. ret = 0;
  66537. p = (Vdbe *)pStmt;
  66538. db = p->db;
  66539. assert( db!=0 );
  66540. n = sqlite3_column_count(pStmt);
  66541. if( N<n && N>=0 ){
  66542. N += useType*n;
  66543. sqlite3_mutex_enter(db->mutex);
  66544. assert( db->mallocFailed==0 );
  66545. ret = xFunc(&p->aColName[N]);
  66546. /* A malloc may have failed inside of the xFunc() call. If this
  66547. ** is the case, clear the mallocFailed flag and return NULL.
  66548. */
  66549. if( db->mallocFailed ){
  66550. db->mallocFailed = 0;
  66551. ret = 0;
  66552. }
  66553. sqlite3_mutex_leave(db->mutex);
  66554. }
  66555. return ret;
  66556. }
  66557. /*
  66558. ** Return the name of the Nth column of the result set returned by SQL
  66559. ** statement pStmt.
  66560. */
  66561. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  66562. return columnName(
  66563. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  66564. }
  66565. #ifndef SQLITE_OMIT_UTF16
  66566. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  66567. return columnName(
  66568. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  66569. }
  66570. #endif
  66571. /*
  66572. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  66573. ** not define OMIT_DECLTYPE.
  66574. */
  66575. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  66576. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  66577. and SQLITE_ENABLE_COLUMN_METADATA"
  66578. #endif
  66579. #ifndef SQLITE_OMIT_DECLTYPE
  66580. /*
  66581. ** Return the column declaration type (if applicable) of the 'i'th column
  66582. ** of the result set of SQL statement pStmt.
  66583. */
  66584. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  66585. return columnName(
  66586. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  66587. }
  66588. #ifndef SQLITE_OMIT_UTF16
  66589. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  66590. return columnName(
  66591. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  66592. }
  66593. #endif /* SQLITE_OMIT_UTF16 */
  66594. #endif /* SQLITE_OMIT_DECLTYPE */
  66595. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  66596. /*
  66597. ** Return the name of the database from which a result column derives.
  66598. ** NULL is returned if the result column is an expression or constant or
  66599. ** anything else which is not an unambiguous reference to a database column.
  66600. */
  66601. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  66602. return columnName(
  66603. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  66604. }
  66605. #ifndef SQLITE_OMIT_UTF16
  66606. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  66607. return columnName(
  66608. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  66609. }
  66610. #endif /* SQLITE_OMIT_UTF16 */
  66611. /*
  66612. ** Return the name of the table from which a result column derives.
  66613. ** NULL is returned if the result column is an expression or constant or
  66614. ** anything else which is not an unambiguous reference to a database column.
  66615. */
  66616. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  66617. return columnName(
  66618. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  66619. }
  66620. #ifndef SQLITE_OMIT_UTF16
  66621. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  66622. return columnName(
  66623. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  66624. }
  66625. #endif /* SQLITE_OMIT_UTF16 */
  66626. /*
  66627. ** Return the name of the table column from which a result column derives.
  66628. ** NULL is returned if the result column is an expression or constant or
  66629. ** anything else which is not an unambiguous reference to a database column.
  66630. */
  66631. SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  66632. return columnName(
  66633. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  66634. }
  66635. #ifndef SQLITE_OMIT_UTF16
  66636. SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  66637. return columnName(
  66638. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  66639. }
  66640. #endif /* SQLITE_OMIT_UTF16 */
  66641. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  66642. /******************************* sqlite3_bind_ ***************************
  66643. **
  66644. ** Routines used to attach values to wildcards in a compiled SQL statement.
  66645. */
  66646. /*
  66647. ** Unbind the value bound to variable i in virtual machine p. This is the
  66648. ** the same as binding a NULL value to the column. If the "i" parameter is
  66649. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  66650. **
  66651. ** A successful evaluation of this routine acquires the mutex on p.
  66652. ** the mutex is released if any kind of error occurs.
  66653. **
  66654. ** The error code stored in database p->db is overwritten with the return
  66655. ** value in any case.
  66656. */
  66657. static int vdbeUnbind(Vdbe *p, int i){
  66658. Mem *pVar;
  66659. if( vdbeSafetyNotNull(p) ){
  66660. return SQLITE_MISUSE_BKPT;
  66661. }
  66662. sqlite3_mutex_enter(p->db->mutex);
  66663. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  66664. sqlite3Error(p->db, SQLITE_MISUSE);
  66665. sqlite3_mutex_leave(p->db->mutex);
  66666. sqlite3_log(SQLITE_MISUSE,
  66667. "bind on a busy prepared statement: [%s]", p->zSql);
  66668. return SQLITE_MISUSE_BKPT;
  66669. }
  66670. if( i<1 || i>p->nVar ){
  66671. sqlite3Error(p->db, SQLITE_RANGE);
  66672. sqlite3_mutex_leave(p->db->mutex);
  66673. return SQLITE_RANGE;
  66674. }
  66675. i--;
  66676. pVar = &p->aVar[i];
  66677. sqlite3VdbeMemRelease(pVar);
  66678. pVar->flags = MEM_Null;
  66679. sqlite3Error(p->db, SQLITE_OK);
  66680. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  66681. ** binding a new value to this variable invalidates the current query plan.
  66682. **
  66683. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  66684. ** parameter in the WHERE clause might influence the choice of query plan
  66685. ** for a statement, then the statement will be automatically recompiled,
  66686. ** as if there had been a schema change, on the first sqlite3_step() call
  66687. ** following any change to the bindings of that parameter.
  66688. */
  66689. if( p->isPrepareV2 &&
  66690. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  66691. ){
  66692. p->expired = 1;
  66693. }
  66694. return SQLITE_OK;
  66695. }
  66696. /*
  66697. ** Bind a text or BLOB value.
  66698. */
  66699. static int bindText(
  66700. sqlite3_stmt *pStmt, /* The statement to bind against */
  66701. int i, /* Index of the parameter to bind */
  66702. const void *zData, /* Pointer to the data to be bound */
  66703. int nData, /* Number of bytes of data to be bound */
  66704. void (*xDel)(void*), /* Destructor for the data */
  66705. u8 encoding /* Encoding for the data */
  66706. ){
  66707. Vdbe *p = (Vdbe *)pStmt;
  66708. Mem *pVar;
  66709. int rc;
  66710. rc = vdbeUnbind(p, i);
  66711. if( rc==SQLITE_OK ){
  66712. if( zData!=0 ){
  66713. pVar = &p->aVar[i-1];
  66714. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  66715. if( rc==SQLITE_OK && encoding!=0 ){
  66716. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  66717. }
  66718. sqlite3Error(p->db, rc);
  66719. rc = sqlite3ApiExit(p->db, rc);
  66720. }
  66721. sqlite3_mutex_leave(p->db->mutex);
  66722. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  66723. xDel((void*)zData);
  66724. }
  66725. return rc;
  66726. }
  66727. /*
  66728. ** Bind a blob value to an SQL statement variable.
  66729. */
  66730. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
  66731. sqlite3_stmt *pStmt,
  66732. int i,
  66733. const void *zData,
  66734. int nData,
  66735. void (*xDel)(void*)
  66736. ){
  66737. return bindText(pStmt, i, zData, nData, xDel, 0);
  66738. }
  66739. SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
  66740. sqlite3_stmt *pStmt,
  66741. int i,
  66742. const void *zData,
  66743. sqlite3_uint64 nData,
  66744. void (*xDel)(void*)
  66745. ){
  66746. assert( xDel!=SQLITE_DYNAMIC );
  66747. if( nData>0x7fffffff ){
  66748. return invokeValueDestructor(zData, xDel, 0);
  66749. }else{
  66750. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  66751. }
  66752. }
  66753. SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  66754. int rc;
  66755. Vdbe *p = (Vdbe *)pStmt;
  66756. rc = vdbeUnbind(p, i);
  66757. if( rc==SQLITE_OK ){
  66758. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  66759. sqlite3_mutex_leave(p->db->mutex);
  66760. }
  66761. return rc;
  66762. }
  66763. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  66764. return sqlite3_bind_int64(p, i, (i64)iValue);
  66765. }
  66766. SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  66767. int rc;
  66768. Vdbe *p = (Vdbe *)pStmt;
  66769. rc = vdbeUnbind(p, i);
  66770. if( rc==SQLITE_OK ){
  66771. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  66772. sqlite3_mutex_leave(p->db->mutex);
  66773. }
  66774. return rc;
  66775. }
  66776. SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  66777. int rc;
  66778. Vdbe *p = (Vdbe*)pStmt;
  66779. rc = vdbeUnbind(p, i);
  66780. if( rc==SQLITE_OK ){
  66781. sqlite3_mutex_leave(p->db->mutex);
  66782. }
  66783. return rc;
  66784. }
  66785. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(
  66786. sqlite3_stmt *pStmt,
  66787. int i,
  66788. const char *zData,
  66789. int nData,
  66790. void (*xDel)(void*)
  66791. ){
  66792. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  66793. }
  66794. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(
  66795. sqlite3_stmt *pStmt,
  66796. int i,
  66797. const char *zData,
  66798. sqlite3_uint64 nData,
  66799. void (*xDel)(void*),
  66800. unsigned char enc
  66801. ){
  66802. assert( xDel!=SQLITE_DYNAMIC );
  66803. if( nData>0x7fffffff ){
  66804. return invokeValueDestructor(zData, xDel, 0);
  66805. }else{
  66806. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  66807. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  66808. }
  66809. }
  66810. #ifndef SQLITE_OMIT_UTF16
  66811. SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
  66812. sqlite3_stmt *pStmt,
  66813. int i,
  66814. const void *zData,
  66815. int nData,
  66816. void (*xDel)(void*)
  66817. ){
  66818. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  66819. }
  66820. #endif /* SQLITE_OMIT_UTF16 */
  66821. SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  66822. int rc;
  66823. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  66824. case SQLITE_INTEGER: {
  66825. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  66826. break;
  66827. }
  66828. case SQLITE_FLOAT: {
  66829. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  66830. break;
  66831. }
  66832. case SQLITE_BLOB: {
  66833. if( pValue->flags & MEM_Zero ){
  66834. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  66835. }else{
  66836. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  66837. }
  66838. break;
  66839. }
  66840. case SQLITE_TEXT: {
  66841. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  66842. pValue->enc);
  66843. break;
  66844. }
  66845. default: {
  66846. rc = sqlite3_bind_null(pStmt, i);
  66847. break;
  66848. }
  66849. }
  66850. return rc;
  66851. }
  66852. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  66853. int rc;
  66854. Vdbe *p = (Vdbe *)pStmt;
  66855. rc = vdbeUnbind(p, i);
  66856. if( rc==SQLITE_OK ){
  66857. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  66858. sqlite3_mutex_leave(p->db->mutex);
  66859. }
  66860. return rc;
  66861. }
  66862. SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
  66863. int rc;
  66864. Vdbe *p = (Vdbe *)pStmt;
  66865. sqlite3_mutex_enter(p->db->mutex);
  66866. if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66867. rc = SQLITE_TOOBIG;
  66868. }else{
  66869. assert( (n & 0x7FFFFFFF)==n );
  66870. rc = sqlite3_bind_zeroblob(pStmt, i, n);
  66871. }
  66872. rc = sqlite3ApiExit(p->db, rc);
  66873. sqlite3_mutex_leave(p->db->mutex);
  66874. return rc;
  66875. }
  66876. /*
  66877. ** Return the number of wildcards that can be potentially bound to.
  66878. ** This routine is added to support DBD::SQLite.
  66879. */
  66880. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  66881. Vdbe *p = (Vdbe*)pStmt;
  66882. return p ? p->nVar : 0;
  66883. }
  66884. /*
  66885. ** Return the name of a wildcard parameter. Return NULL if the index
  66886. ** is out of range or if the wildcard is unnamed.
  66887. **
  66888. ** The result is always UTF-8.
  66889. */
  66890. SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  66891. Vdbe *p = (Vdbe*)pStmt;
  66892. if( p==0 || i<1 || i>p->nzVar ){
  66893. return 0;
  66894. }
  66895. return p->azVar[i-1];
  66896. }
  66897. /*
  66898. ** Given a wildcard parameter name, return the index of the variable
  66899. ** with that name. If there is no variable with the given name,
  66900. ** return 0.
  66901. */
  66902. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  66903. int i;
  66904. if( p==0 ){
  66905. return 0;
  66906. }
  66907. if( zName ){
  66908. for(i=0; i<p->nzVar; i++){
  66909. const char *z = p->azVar[i];
  66910. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  66911. return i+1;
  66912. }
  66913. }
  66914. }
  66915. return 0;
  66916. }
  66917. SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  66918. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  66919. }
  66920. /*
  66921. ** Transfer all bindings from the first statement over to the second.
  66922. */
  66923. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  66924. Vdbe *pFrom = (Vdbe*)pFromStmt;
  66925. Vdbe *pTo = (Vdbe*)pToStmt;
  66926. int i;
  66927. assert( pTo->db==pFrom->db );
  66928. assert( pTo->nVar==pFrom->nVar );
  66929. sqlite3_mutex_enter(pTo->db->mutex);
  66930. for(i=0; i<pFrom->nVar; i++){
  66931. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  66932. }
  66933. sqlite3_mutex_leave(pTo->db->mutex);
  66934. return SQLITE_OK;
  66935. }
  66936. #ifndef SQLITE_OMIT_DEPRECATED
  66937. /*
  66938. ** Deprecated external interface. Internal/core SQLite code
  66939. ** should call sqlite3TransferBindings.
  66940. **
  66941. ** It is misuse to call this routine with statements from different
  66942. ** database connections. But as this is a deprecated interface, we
  66943. ** will not bother to check for that condition.
  66944. **
  66945. ** If the two statements contain a different number of bindings, then
  66946. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  66947. ** SQLITE_OK is returned.
  66948. */
  66949. SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  66950. Vdbe *pFrom = (Vdbe*)pFromStmt;
  66951. Vdbe *pTo = (Vdbe*)pToStmt;
  66952. if( pFrom->nVar!=pTo->nVar ){
  66953. return SQLITE_ERROR;
  66954. }
  66955. if( pTo->isPrepareV2 && pTo->expmask ){
  66956. pTo->expired = 1;
  66957. }
  66958. if( pFrom->isPrepareV2 && pFrom->expmask ){
  66959. pFrom->expired = 1;
  66960. }
  66961. return sqlite3TransferBindings(pFromStmt, pToStmt);
  66962. }
  66963. #endif
  66964. /*
  66965. ** Return the sqlite3* database handle to which the prepared statement given
  66966. ** in the argument belongs. This is the same database handle that was
  66967. ** the first argument to the sqlite3_prepare() that was used to create
  66968. ** the statement in the first place.
  66969. */
  66970. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
  66971. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  66972. }
  66973. /*
  66974. ** Return true if the prepared statement is guaranteed to not modify the
  66975. ** database.
  66976. */
  66977. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  66978. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  66979. }
  66980. /*
  66981. ** Return true if the prepared statement is in need of being reset.
  66982. */
  66983. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  66984. Vdbe *v = (Vdbe*)pStmt;
  66985. return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
  66986. }
  66987. /*
  66988. ** Return a pointer to the next prepared statement after pStmt associated
  66989. ** with database connection pDb. If pStmt is NULL, return the first
  66990. ** prepared statement for the database connection. Return NULL if there
  66991. ** are no more.
  66992. */
  66993. SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  66994. sqlite3_stmt *pNext;
  66995. #ifdef SQLITE_ENABLE_API_ARMOR
  66996. if( !sqlite3SafetyCheckOk(pDb) ){
  66997. (void)SQLITE_MISUSE_BKPT;
  66998. return 0;
  66999. }
  67000. #endif
  67001. sqlite3_mutex_enter(pDb->mutex);
  67002. if( pStmt==0 ){
  67003. pNext = (sqlite3_stmt*)pDb->pVdbe;
  67004. }else{
  67005. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  67006. }
  67007. sqlite3_mutex_leave(pDb->mutex);
  67008. return pNext;
  67009. }
  67010. /*
  67011. ** Return the value of a status counter for a prepared statement
  67012. */
  67013. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  67014. Vdbe *pVdbe = (Vdbe*)pStmt;
  67015. u32 v;
  67016. #ifdef SQLITE_ENABLE_API_ARMOR
  67017. if( !pStmt ){
  67018. (void)SQLITE_MISUSE_BKPT;
  67019. return 0;
  67020. }
  67021. #endif
  67022. v = pVdbe->aCounter[op];
  67023. if( resetFlag ) pVdbe->aCounter[op] = 0;
  67024. return (int)v;
  67025. }
  67026. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  67027. /*
  67028. ** Return status data for a single loop within query pStmt.
  67029. */
  67030. SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
  67031. sqlite3_stmt *pStmt, /* Prepared statement being queried */
  67032. int idx, /* Index of loop to report on */
  67033. int iScanStatusOp, /* Which metric to return */
  67034. void *pOut /* OUT: Write the answer here */
  67035. ){
  67036. Vdbe *p = (Vdbe*)pStmt;
  67037. ScanStatus *pScan;
  67038. if( idx<0 || idx>=p->nScan ) return 1;
  67039. pScan = &p->aScan[idx];
  67040. switch( iScanStatusOp ){
  67041. case SQLITE_SCANSTAT_NLOOP: {
  67042. *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
  67043. break;
  67044. }
  67045. case SQLITE_SCANSTAT_NVISIT: {
  67046. *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
  67047. break;
  67048. }
  67049. case SQLITE_SCANSTAT_EST: {
  67050. double r = 1.0;
  67051. LogEst x = pScan->nEst;
  67052. while( x<100 ){
  67053. x += 10;
  67054. r *= 0.5;
  67055. }
  67056. *(double*)pOut = r*sqlite3LogEstToInt(x);
  67057. break;
  67058. }
  67059. case SQLITE_SCANSTAT_NAME: {
  67060. *(const char**)pOut = pScan->zName;
  67061. break;
  67062. }
  67063. case SQLITE_SCANSTAT_EXPLAIN: {
  67064. if( pScan->addrExplain ){
  67065. *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
  67066. }else{
  67067. *(const char**)pOut = 0;
  67068. }
  67069. break;
  67070. }
  67071. case SQLITE_SCANSTAT_SELECTID: {
  67072. if( pScan->addrExplain ){
  67073. *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
  67074. }else{
  67075. *(int*)pOut = -1;
  67076. }
  67077. break;
  67078. }
  67079. default: {
  67080. return 1;
  67081. }
  67082. }
  67083. return 0;
  67084. }
  67085. /*
  67086. ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
  67087. */
  67088. SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
  67089. Vdbe *p = (Vdbe*)pStmt;
  67090. memset(p->anExec, 0, p->nOp * sizeof(i64));
  67091. }
  67092. #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
  67093. /************** End of vdbeapi.c *********************************************/
  67094. /************** Begin file vdbetrace.c ***************************************/
  67095. /*
  67096. ** 2009 November 25
  67097. **
  67098. ** The author disclaims copyright to this source code. In place of
  67099. ** a legal notice, here is a blessing:
  67100. **
  67101. ** May you do good and not evil.
  67102. ** May you find forgiveness for yourself and forgive others.
  67103. ** May you share freely, never taking more than you give.
  67104. **
  67105. *************************************************************************
  67106. **
  67107. ** This file contains code used to insert the values of host parameters
  67108. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  67109. **
  67110. ** The Vdbe parse-tree explainer is also found here.
  67111. */
  67112. /* #include "sqliteInt.h" */
  67113. /* #include "vdbeInt.h" */
  67114. #ifndef SQLITE_OMIT_TRACE
  67115. /*
  67116. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  67117. ** bytes in this text up to but excluding the first character in
  67118. ** a host parameter. If the text contains no host parameters, return
  67119. ** the total number of bytes in the text.
  67120. */
  67121. static int findNextHostParameter(const char *zSql, int *pnToken){
  67122. int tokenType;
  67123. int nTotal = 0;
  67124. int n;
  67125. *pnToken = 0;
  67126. while( zSql[0] ){
  67127. n = sqlite3GetToken((u8*)zSql, &tokenType);
  67128. assert( n>0 && tokenType!=TK_ILLEGAL );
  67129. if( tokenType==TK_VARIABLE ){
  67130. *pnToken = n;
  67131. break;
  67132. }
  67133. nTotal += n;
  67134. zSql += n;
  67135. }
  67136. return nTotal;
  67137. }
  67138. /*
  67139. ** This function returns a pointer to a nul-terminated string in memory
  67140. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  67141. ** string contains a copy of zRawSql but with host parameters expanded to
  67142. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  67143. ** then the returned string holds a copy of zRawSql with "-- " prepended
  67144. ** to each line of text.
  67145. **
  67146. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  67147. ** then long strings and blobs are truncated to that many bytes. This
  67148. ** can be used to prevent unreasonably large trace strings when dealing
  67149. ** with large (multi-megabyte) strings and blobs.
  67150. **
  67151. ** The calling function is responsible for making sure the memory returned
  67152. ** is eventually freed.
  67153. **
  67154. ** ALGORITHM: Scan the input string looking for host parameters in any of
  67155. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  67156. ** string literals, quoted identifier names, and comments. For text forms,
  67157. ** the host parameter index is found by scanning the prepared
  67158. ** statement for the corresponding OP_Variable opcode. Once the host
  67159. ** parameter index is known, locate the value in p->aVar[]. Then render
  67160. ** the value as a literal in place of the host parameter name.
  67161. */
  67162. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  67163. Vdbe *p, /* The prepared statement being evaluated */
  67164. const char *zRawSql /* Raw text of the SQL statement */
  67165. ){
  67166. sqlite3 *db; /* The database connection */
  67167. int idx = 0; /* Index of a host parameter */
  67168. int nextIndex = 1; /* Index of next ? host parameter */
  67169. int n; /* Length of a token prefix */
  67170. int nToken; /* Length of the parameter token */
  67171. int i; /* Loop counter */
  67172. Mem *pVar; /* Value of a host parameter */
  67173. StrAccum out; /* Accumulate the output here */
  67174. char zBase[100]; /* Initial working space */
  67175. db = p->db;
  67176. sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
  67177. db->aLimit[SQLITE_LIMIT_LENGTH]);
  67178. if( db->nVdbeExec>1 ){
  67179. while( *zRawSql ){
  67180. const char *zStart = zRawSql;
  67181. while( *(zRawSql++)!='\n' && *zRawSql );
  67182. sqlite3StrAccumAppend(&out, "-- ", 3);
  67183. assert( (zRawSql - zStart) > 0 );
  67184. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  67185. }
  67186. }else if( p->nVar==0 ){
  67187. sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
  67188. }else{
  67189. while( zRawSql[0] ){
  67190. n = findNextHostParameter(zRawSql, &nToken);
  67191. assert( n>0 );
  67192. sqlite3StrAccumAppend(&out, zRawSql, n);
  67193. zRawSql += n;
  67194. assert( zRawSql[0] || nToken==0 );
  67195. if( nToken==0 ) break;
  67196. if( zRawSql[0]=='?' ){
  67197. if( nToken>1 ){
  67198. assert( sqlite3Isdigit(zRawSql[1]) );
  67199. sqlite3GetInt32(&zRawSql[1], &idx);
  67200. }else{
  67201. idx = nextIndex;
  67202. }
  67203. }else{
  67204. assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
  67205. zRawSql[0]=='@' || zRawSql[0]=='#' );
  67206. testcase( zRawSql[0]==':' );
  67207. testcase( zRawSql[0]=='$' );
  67208. testcase( zRawSql[0]=='@' );
  67209. testcase( zRawSql[0]=='#' );
  67210. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  67211. assert( idx>0 );
  67212. }
  67213. zRawSql += nToken;
  67214. nextIndex = idx + 1;
  67215. assert( idx>0 && idx<=p->nVar );
  67216. pVar = &p->aVar[idx-1];
  67217. if( pVar->flags & MEM_Null ){
  67218. sqlite3StrAccumAppend(&out, "NULL", 4);
  67219. }else if( pVar->flags & MEM_Int ){
  67220. sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
  67221. }else if( pVar->flags & MEM_Real ){
  67222. sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
  67223. }else if( pVar->flags & MEM_Str ){
  67224. int nOut; /* Number of bytes of the string text to include in output */
  67225. #ifndef SQLITE_OMIT_UTF16
  67226. u8 enc = ENC(db);
  67227. Mem utf8;
  67228. if( enc!=SQLITE_UTF8 ){
  67229. memset(&utf8, 0, sizeof(utf8));
  67230. utf8.db = db;
  67231. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  67232. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  67233. pVar = &utf8;
  67234. }
  67235. #endif
  67236. nOut = pVar->n;
  67237. #ifdef SQLITE_TRACE_SIZE_LIMIT
  67238. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  67239. nOut = SQLITE_TRACE_SIZE_LIMIT;
  67240. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  67241. }
  67242. #endif
  67243. sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
  67244. #ifdef SQLITE_TRACE_SIZE_LIMIT
  67245. if( nOut<pVar->n ){
  67246. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  67247. }
  67248. #endif
  67249. #ifndef SQLITE_OMIT_UTF16
  67250. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  67251. #endif
  67252. }else if( pVar->flags & MEM_Zero ){
  67253. sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
  67254. }else{
  67255. int nOut; /* Number of bytes of the blob to include in output */
  67256. assert( pVar->flags & MEM_Blob );
  67257. sqlite3StrAccumAppend(&out, "x'", 2);
  67258. nOut = pVar->n;
  67259. #ifdef SQLITE_TRACE_SIZE_LIMIT
  67260. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  67261. #endif
  67262. for(i=0; i<nOut; i++){
  67263. sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
  67264. }
  67265. sqlite3StrAccumAppend(&out, "'", 1);
  67266. #ifdef SQLITE_TRACE_SIZE_LIMIT
  67267. if( nOut<pVar->n ){
  67268. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  67269. }
  67270. #endif
  67271. }
  67272. }
  67273. }
  67274. return sqlite3StrAccumFinish(&out);
  67275. }
  67276. #endif /* #ifndef SQLITE_OMIT_TRACE */
  67277. /************** End of vdbetrace.c *******************************************/
  67278. /************** Begin file vdbe.c ********************************************/
  67279. /*
  67280. ** 2001 September 15
  67281. **
  67282. ** The author disclaims copyright to this source code. In place of
  67283. ** a legal notice, here is a blessing:
  67284. **
  67285. ** May you do good and not evil.
  67286. ** May you find forgiveness for yourself and forgive others.
  67287. ** May you share freely, never taking more than you give.
  67288. **
  67289. *************************************************************************
  67290. ** The code in this file implements the function that runs the
  67291. ** bytecode of a prepared statement.
  67292. **
  67293. ** Various scripts scan this source file in order to generate HTML
  67294. ** documentation, headers files, or other derived files. The formatting
  67295. ** of the code in this file is, therefore, important. See other comments
  67296. ** in this file for details. If in doubt, do not deviate from existing
  67297. ** commenting and indentation practices when changing or adding code.
  67298. */
  67299. /* #include "sqliteInt.h" */
  67300. /* #include "vdbeInt.h" */
  67301. /*
  67302. ** Invoke this macro on memory cells just prior to changing the
  67303. ** value of the cell. This macro verifies that shallow copies are
  67304. ** not misused. A shallow copy of a string or blob just copies a
  67305. ** pointer to the string or blob, not the content. If the original
  67306. ** is changed while the copy is still in use, the string or blob might
  67307. ** be changed out from under the copy. This macro verifies that nothing
  67308. ** like that ever happens.
  67309. */
  67310. #ifdef SQLITE_DEBUG
  67311. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  67312. #else
  67313. # define memAboutToChange(P,M)
  67314. #endif
  67315. /*
  67316. ** The following global variable is incremented every time a cursor
  67317. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  67318. ** procedures use this information to make sure that indices are
  67319. ** working correctly. This variable has no function other than to
  67320. ** help verify the correct operation of the library.
  67321. */
  67322. #ifdef SQLITE_TEST
  67323. SQLITE_API int sqlite3_search_count = 0;
  67324. #endif
  67325. /*
  67326. ** When this global variable is positive, it gets decremented once before
  67327. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  67328. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  67329. **
  67330. ** This facility is used for testing purposes only. It does not function
  67331. ** in an ordinary build.
  67332. */
  67333. #ifdef SQLITE_TEST
  67334. SQLITE_API int sqlite3_interrupt_count = 0;
  67335. #endif
  67336. /*
  67337. ** The next global variable is incremented each type the OP_Sort opcode
  67338. ** is executed. The test procedures use this information to make sure that
  67339. ** sorting is occurring or not occurring at appropriate times. This variable
  67340. ** has no function other than to help verify the correct operation of the
  67341. ** library.
  67342. */
  67343. #ifdef SQLITE_TEST
  67344. SQLITE_API int sqlite3_sort_count = 0;
  67345. #endif
  67346. /*
  67347. ** The next global variable records the size of the largest MEM_Blob
  67348. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  67349. ** use this information to make sure that the zero-blob functionality
  67350. ** is working correctly. This variable has no function other than to
  67351. ** help verify the correct operation of the library.
  67352. */
  67353. #ifdef SQLITE_TEST
  67354. SQLITE_API int sqlite3_max_blobsize = 0;
  67355. static void updateMaxBlobsize(Mem *p){
  67356. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  67357. sqlite3_max_blobsize = p->n;
  67358. }
  67359. }
  67360. #endif
  67361. /*
  67362. ** The next global variable is incremented each time the OP_Found opcode
  67363. ** is executed. This is used to test whether or not the foreign key
  67364. ** operation implemented using OP_FkIsZero is working. This variable
  67365. ** has no function other than to help verify the correct operation of the
  67366. ** library.
  67367. */
  67368. #ifdef SQLITE_TEST
  67369. SQLITE_API int sqlite3_found_count = 0;
  67370. #endif
  67371. /*
  67372. ** Test a register to see if it exceeds the current maximum blob size.
  67373. ** If it does, record the new maximum blob size.
  67374. */
  67375. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  67376. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  67377. #else
  67378. # define UPDATE_MAX_BLOBSIZE(P)
  67379. #endif
  67380. /*
  67381. ** Invoke the VDBE coverage callback, if that callback is defined. This
  67382. ** feature is used for test suite validation only and does not appear an
  67383. ** production builds.
  67384. **
  67385. ** M is an integer, 2 or 3, that indices how many different ways the
  67386. ** branch can go. It is usually 2. "I" is the direction the branch
  67387. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  67388. ** second alternative branch is taken.
  67389. **
  67390. ** iSrcLine is the source code line (from the __LINE__ macro) that
  67391. ** generated the VDBE instruction. This instrumentation assumes that all
  67392. ** source code is in a single file (the amalgamation). Special values 1
  67393. ** and 2 for the iSrcLine parameter mean that this particular branch is
  67394. ** always taken or never taken, respectively.
  67395. */
  67396. #if !defined(SQLITE_VDBE_COVERAGE)
  67397. # define VdbeBranchTaken(I,M)
  67398. #else
  67399. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  67400. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  67401. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  67402. M = iSrcLine;
  67403. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  67404. ** VdbeCoverageNeverTaken() */
  67405. assert( (M & I)==I );
  67406. }else{
  67407. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  67408. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  67409. iSrcLine,I,M);
  67410. }
  67411. }
  67412. #endif
  67413. /*
  67414. ** Convert the given register into a string if it isn't one
  67415. ** already. Return non-zero if a malloc() fails.
  67416. */
  67417. #define Stringify(P, enc) \
  67418. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  67419. { goto no_mem; }
  67420. /*
  67421. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  67422. ** a pointer to a dynamically allocated string where some other entity
  67423. ** is responsible for deallocating that string. Because the register
  67424. ** does not control the string, it might be deleted without the register
  67425. ** knowing it.
  67426. **
  67427. ** This routine converts an ephemeral string into a dynamically allocated
  67428. ** string that the register itself controls. In other words, it
  67429. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  67430. */
  67431. #define Deephemeralize(P) \
  67432. if( ((P)->flags&MEM_Ephem)!=0 \
  67433. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  67434. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  67435. #define isSorter(x) ((x)->pSorter!=0)
  67436. /*
  67437. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  67438. ** if we run out of memory.
  67439. */
  67440. static VdbeCursor *allocateCursor(
  67441. Vdbe *p, /* The virtual machine */
  67442. int iCur, /* Index of the new VdbeCursor */
  67443. int nField, /* Number of fields in the table or index */
  67444. int iDb, /* Database the cursor belongs to, or -1 */
  67445. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  67446. ){
  67447. /* Find the memory cell that will be used to store the blob of memory
  67448. ** required for this VdbeCursor structure. It is convenient to use a
  67449. ** vdbe memory cell to manage the memory allocation required for a
  67450. ** VdbeCursor structure for the following reasons:
  67451. **
  67452. ** * Sometimes cursor numbers are used for a couple of different
  67453. ** purposes in a vdbe program. The different uses might require
  67454. ** different sized allocations. Memory cells provide growable
  67455. ** allocations.
  67456. **
  67457. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  67458. ** be freed lazily via the sqlite3_release_memory() API. This
  67459. ** minimizes the number of malloc calls made by the system.
  67460. **
  67461. ** Memory cells for cursors are allocated at the top of the address
  67462. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  67463. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  67464. */
  67465. Mem *pMem = &p->aMem[p->nMem-iCur];
  67466. int nByte;
  67467. VdbeCursor *pCx = 0;
  67468. nByte =
  67469. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  67470. (isBtreeCursor?sqlite3BtreeCursorSize():0);
  67471. assert( iCur<p->nCursor );
  67472. if( p->apCsr[iCur] ){
  67473. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  67474. p->apCsr[iCur] = 0;
  67475. }
  67476. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  67477. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  67478. memset(pCx, 0, sizeof(VdbeCursor));
  67479. pCx->iDb = iDb;
  67480. pCx->nField = nField;
  67481. pCx->aOffset = &pCx->aType[nField];
  67482. if( isBtreeCursor ){
  67483. pCx->pCursor = (BtCursor*)
  67484. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  67485. sqlite3BtreeCursorZero(pCx->pCursor);
  67486. }
  67487. }
  67488. return pCx;
  67489. }
  67490. /*
  67491. ** Try to convert a value into a numeric representation if we can
  67492. ** do so without loss of information. In other words, if the string
  67493. ** looks like a number, convert it into a number. If it does not
  67494. ** look like a number, leave it alone.
  67495. **
  67496. ** If the bTryForInt flag is true, then extra effort is made to give
  67497. ** an integer representation. Strings that look like floating point
  67498. ** values but which have no fractional component (example: '48.00')
  67499. ** will have a MEM_Int representation when bTryForInt is true.
  67500. **
  67501. ** If bTryForInt is false, then if the input string contains a decimal
  67502. ** point or exponential notation, the result is only MEM_Real, even
  67503. ** if there is an exact integer representation of the quantity.
  67504. */
  67505. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  67506. double rValue;
  67507. i64 iValue;
  67508. u8 enc = pRec->enc;
  67509. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  67510. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  67511. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  67512. pRec->u.i = iValue;
  67513. pRec->flags |= MEM_Int;
  67514. }else{
  67515. pRec->u.r = rValue;
  67516. pRec->flags |= MEM_Real;
  67517. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  67518. }
  67519. }
  67520. /*
  67521. ** Processing is determine by the affinity parameter:
  67522. **
  67523. ** SQLITE_AFF_INTEGER:
  67524. ** SQLITE_AFF_REAL:
  67525. ** SQLITE_AFF_NUMERIC:
  67526. ** Try to convert pRec to an integer representation or a
  67527. ** floating-point representation if an integer representation
  67528. ** is not possible. Note that the integer representation is
  67529. ** always preferred, even if the affinity is REAL, because
  67530. ** an integer representation is more space efficient on disk.
  67531. **
  67532. ** SQLITE_AFF_TEXT:
  67533. ** Convert pRec to a text representation.
  67534. **
  67535. ** SQLITE_AFF_BLOB:
  67536. ** No-op. pRec is unchanged.
  67537. */
  67538. static void applyAffinity(
  67539. Mem *pRec, /* The value to apply affinity to */
  67540. char affinity, /* The affinity to be applied */
  67541. u8 enc /* Use this text encoding */
  67542. ){
  67543. if( affinity>=SQLITE_AFF_NUMERIC ){
  67544. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  67545. || affinity==SQLITE_AFF_NUMERIC );
  67546. if( (pRec->flags & MEM_Int)==0 ){
  67547. if( (pRec->flags & MEM_Real)==0 ){
  67548. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  67549. }else{
  67550. sqlite3VdbeIntegerAffinity(pRec);
  67551. }
  67552. }
  67553. }else if( affinity==SQLITE_AFF_TEXT ){
  67554. /* Only attempt the conversion to TEXT if there is an integer or real
  67555. ** representation (blob and NULL do not get converted) but no string
  67556. ** representation.
  67557. */
  67558. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  67559. sqlite3VdbeMemStringify(pRec, enc, 1);
  67560. }
  67561. pRec->flags &= ~(MEM_Real|MEM_Int);
  67562. }
  67563. }
  67564. /*
  67565. ** Try to convert the type of a function argument or a result column
  67566. ** into a numeric representation. Use either INTEGER or REAL whichever
  67567. ** is appropriate. But only do the conversion if it is possible without
  67568. ** loss of information and return the revised type of the argument.
  67569. */
  67570. SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
  67571. int eType = sqlite3_value_type(pVal);
  67572. if( eType==SQLITE_TEXT ){
  67573. Mem *pMem = (Mem*)pVal;
  67574. applyNumericAffinity(pMem, 0);
  67575. eType = sqlite3_value_type(pVal);
  67576. }
  67577. return eType;
  67578. }
  67579. /*
  67580. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  67581. ** not the internal Mem* type.
  67582. */
  67583. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  67584. sqlite3_value *pVal,
  67585. u8 affinity,
  67586. u8 enc
  67587. ){
  67588. applyAffinity((Mem *)pVal, affinity, enc);
  67589. }
  67590. /*
  67591. ** pMem currently only holds a string type (or maybe a BLOB that we can
  67592. ** interpret as a string if we want to). Compute its corresponding
  67593. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  67594. ** accordingly.
  67595. */
  67596. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  67597. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  67598. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  67599. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  67600. return 0;
  67601. }
  67602. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  67603. return MEM_Int;
  67604. }
  67605. return MEM_Real;
  67606. }
  67607. /*
  67608. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  67609. ** none.
  67610. **
  67611. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  67612. ** But it does set pMem->u.r and pMem->u.i appropriately.
  67613. */
  67614. static u16 numericType(Mem *pMem){
  67615. if( pMem->flags & (MEM_Int|MEM_Real) ){
  67616. return pMem->flags & (MEM_Int|MEM_Real);
  67617. }
  67618. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  67619. return computeNumericType(pMem);
  67620. }
  67621. return 0;
  67622. }
  67623. #ifdef SQLITE_DEBUG
  67624. /*
  67625. ** Write a nice string representation of the contents of cell pMem
  67626. ** into buffer zBuf, length nBuf.
  67627. */
  67628. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  67629. char *zCsr = zBuf;
  67630. int f = pMem->flags;
  67631. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  67632. if( f&MEM_Blob ){
  67633. int i;
  67634. char c;
  67635. if( f & MEM_Dyn ){
  67636. c = 'z';
  67637. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  67638. }else if( f & MEM_Static ){
  67639. c = 't';
  67640. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  67641. }else if( f & MEM_Ephem ){
  67642. c = 'e';
  67643. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  67644. }else{
  67645. c = 's';
  67646. }
  67647. sqlite3_snprintf(100, zCsr, "%c", c);
  67648. zCsr += sqlite3Strlen30(zCsr);
  67649. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  67650. zCsr += sqlite3Strlen30(zCsr);
  67651. for(i=0; i<16 && i<pMem->n; i++){
  67652. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  67653. zCsr += sqlite3Strlen30(zCsr);
  67654. }
  67655. for(i=0; i<16 && i<pMem->n; i++){
  67656. char z = pMem->z[i];
  67657. if( z<32 || z>126 ) *zCsr++ = '.';
  67658. else *zCsr++ = z;
  67659. }
  67660. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  67661. zCsr += sqlite3Strlen30(zCsr);
  67662. if( f & MEM_Zero ){
  67663. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  67664. zCsr += sqlite3Strlen30(zCsr);
  67665. }
  67666. *zCsr = '\0';
  67667. }else if( f & MEM_Str ){
  67668. int j, k;
  67669. zBuf[0] = ' ';
  67670. if( f & MEM_Dyn ){
  67671. zBuf[1] = 'z';
  67672. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  67673. }else if( f & MEM_Static ){
  67674. zBuf[1] = 't';
  67675. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  67676. }else if( f & MEM_Ephem ){
  67677. zBuf[1] = 'e';
  67678. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  67679. }else{
  67680. zBuf[1] = 's';
  67681. }
  67682. k = 2;
  67683. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  67684. k += sqlite3Strlen30(&zBuf[k]);
  67685. zBuf[k++] = '[';
  67686. for(j=0; j<15 && j<pMem->n; j++){
  67687. u8 c = pMem->z[j];
  67688. if( c>=0x20 && c<0x7f ){
  67689. zBuf[k++] = c;
  67690. }else{
  67691. zBuf[k++] = '.';
  67692. }
  67693. }
  67694. zBuf[k++] = ']';
  67695. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  67696. k += sqlite3Strlen30(&zBuf[k]);
  67697. zBuf[k++] = 0;
  67698. }
  67699. }
  67700. #endif
  67701. #ifdef SQLITE_DEBUG
  67702. /*
  67703. ** Print the value of a register for tracing purposes:
  67704. */
  67705. static void memTracePrint(Mem *p){
  67706. if( p->flags & MEM_Undefined ){
  67707. printf(" undefined");
  67708. }else if( p->flags & MEM_Null ){
  67709. printf(" NULL");
  67710. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  67711. printf(" si:%lld", p->u.i);
  67712. }else if( p->flags & MEM_Int ){
  67713. printf(" i:%lld", p->u.i);
  67714. #ifndef SQLITE_OMIT_FLOATING_POINT
  67715. }else if( p->flags & MEM_Real ){
  67716. printf(" r:%g", p->u.r);
  67717. #endif
  67718. }else if( p->flags & MEM_RowSet ){
  67719. printf(" (rowset)");
  67720. }else{
  67721. char zBuf[200];
  67722. sqlite3VdbeMemPrettyPrint(p, zBuf);
  67723. printf(" %s", zBuf);
  67724. }
  67725. }
  67726. static void registerTrace(int iReg, Mem *p){
  67727. printf("REG[%d] = ", iReg);
  67728. memTracePrint(p);
  67729. printf("\n");
  67730. }
  67731. #endif
  67732. #ifdef SQLITE_DEBUG
  67733. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  67734. #else
  67735. # define REGISTER_TRACE(R,M)
  67736. #endif
  67737. #ifdef VDBE_PROFILE
  67738. /*
  67739. ** hwtime.h contains inline assembler code for implementing
  67740. ** high-performance timing routines.
  67741. */
  67742. /************** Include hwtime.h in the middle of vdbe.c *********************/
  67743. /************** Begin file hwtime.h ******************************************/
  67744. /*
  67745. ** 2008 May 27
  67746. **
  67747. ** The author disclaims copyright to this source code. In place of
  67748. ** a legal notice, here is a blessing:
  67749. **
  67750. ** May you do good and not evil.
  67751. ** May you find forgiveness for yourself and forgive others.
  67752. ** May you share freely, never taking more than you give.
  67753. **
  67754. ******************************************************************************
  67755. **
  67756. ** This file contains inline asm code for retrieving "high-performance"
  67757. ** counters for x86 class CPUs.
  67758. */
  67759. #ifndef _HWTIME_H_
  67760. #define _HWTIME_H_
  67761. /*
  67762. ** The following routine only works on pentium-class (or newer) processors.
  67763. ** It uses the RDTSC opcode to read the cycle count value out of the
  67764. ** processor and returns that value. This can be used for high-res
  67765. ** profiling.
  67766. */
  67767. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  67768. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  67769. #if defined(__GNUC__)
  67770. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  67771. unsigned int lo, hi;
  67772. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  67773. return (sqlite_uint64)hi << 32 | lo;
  67774. }
  67775. #elif defined(_MSC_VER)
  67776. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  67777. __asm {
  67778. rdtsc
  67779. ret ; return value at EDX:EAX
  67780. }
  67781. }
  67782. #endif
  67783. #elif (defined(__GNUC__) && defined(__x86_64__))
  67784. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  67785. unsigned long val;
  67786. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  67787. return val;
  67788. }
  67789. #elif (defined(__GNUC__) && defined(__ppc__))
  67790. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  67791. unsigned long long retval;
  67792. unsigned long junk;
  67793. __asm__ __volatile__ ("\n\
  67794. 1: mftbu %1\n\
  67795. mftb %L0\n\
  67796. mftbu %0\n\
  67797. cmpw %0,%1\n\
  67798. bne 1b"
  67799. : "=r" (retval), "=r" (junk));
  67800. return retval;
  67801. }
  67802. #else
  67803. #error Need implementation of sqlite3Hwtime() for your platform.
  67804. /*
  67805. ** To compile without implementing sqlite3Hwtime() for your platform,
  67806. ** you can remove the above #error and use the following
  67807. ** stub function. You will lose timing support for many
  67808. ** of the debugging and testing utilities, but it should at
  67809. ** least compile and run.
  67810. */
  67811. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  67812. #endif
  67813. #endif /* !defined(_HWTIME_H_) */
  67814. /************** End of hwtime.h **********************************************/
  67815. /************** Continuing where we left off in vdbe.c ***********************/
  67816. #endif
  67817. #ifndef NDEBUG
  67818. /*
  67819. ** This function is only called from within an assert() expression. It
  67820. ** checks that the sqlite3.nTransaction variable is correctly set to
  67821. ** the number of non-transaction savepoints currently in the
  67822. ** linked list starting at sqlite3.pSavepoint.
  67823. **
  67824. ** Usage:
  67825. **
  67826. ** assert( checkSavepointCount(db) );
  67827. */
  67828. static int checkSavepointCount(sqlite3 *db){
  67829. int n = 0;
  67830. Savepoint *p;
  67831. for(p=db->pSavepoint; p; p=p->pNext) n++;
  67832. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  67833. return 1;
  67834. }
  67835. #endif
  67836. /*
  67837. ** Return the register of pOp->p2 after first preparing it to be
  67838. ** overwritten with an integer value.
  67839. */
  67840. static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
  67841. Mem *pOut;
  67842. assert( pOp->p2>0 );
  67843. assert( pOp->p2<=(p->nMem-p->nCursor) );
  67844. pOut = &p->aMem[pOp->p2];
  67845. memAboutToChange(p, pOut);
  67846. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  67847. pOut->flags = MEM_Int;
  67848. return pOut;
  67849. }
  67850. /*
  67851. ** Execute as much of a VDBE program as we can.
  67852. ** This is the core of sqlite3_step().
  67853. */
  67854. SQLITE_PRIVATE int sqlite3VdbeExec(
  67855. Vdbe *p /* The VDBE */
  67856. ){
  67857. Op *aOp = p->aOp; /* Copy of p->aOp */
  67858. Op *pOp = aOp; /* Current operation */
  67859. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  67860. Op *pOrigOp; /* Value of pOp at the top of the loop */
  67861. #endif
  67862. int rc = SQLITE_OK; /* Value to return */
  67863. sqlite3 *db = p->db; /* The database */
  67864. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  67865. u8 encoding = ENC(db); /* The database encoding */
  67866. int iCompare = 0; /* Result of last OP_Compare operation */
  67867. unsigned nVmStep = 0; /* Number of virtual machine steps */
  67868. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  67869. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  67870. #endif
  67871. Mem *aMem = p->aMem; /* Copy of p->aMem */
  67872. Mem *pIn1 = 0; /* 1st input operand */
  67873. Mem *pIn2 = 0; /* 2nd input operand */
  67874. Mem *pIn3 = 0; /* 3rd input operand */
  67875. Mem *pOut = 0; /* Output operand */
  67876. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  67877. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  67878. #ifdef VDBE_PROFILE
  67879. u64 start; /* CPU clock count at start of opcode */
  67880. #endif
  67881. /*** INSERT STACK UNION HERE ***/
  67882. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  67883. sqlite3VdbeEnter(p);
  67884. if( p->rc==SQLITE_NOMEM ){
  67885. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  67886. ** sqlite3_column_text16() failed. */
  67887. goto no_mem;
  67888. }
  67889. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  67890. assert( p->bIsReader || p->readOnly!=0 );
  67891. p->rc = SQLITE_OK;
  67892. p->iCurrentTime = 0;
  67893. assert( p->explain==0 );
  67894. p->pResultSet = 0;
  67895. db->busyHandler.nBusy = 0;
  67896. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  67897. sqlite3VdbeIOTraceSql(p);
  67898. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  67899. if( db->xProgress ){
  67900. u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  67901. assert( 0 < db->nProgressOps );
  67902. nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
  67903. }
  67904. #endif
  67905. #ifdef SQLITE_DEBUG
  67906. sqlite3BeginBenignMalloc();
  67907. if( p->pc==0
  67908. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  67909. ){
  67910. int i;
  67911. int once = 1;
  67912. sqlite3VdbePrintSql(p);
  67913. if( p->db->flags & SQLITE_VdbeListing ){
  67914. printf("VDBE Program Listing:\n");
  67915. for(i=0; i<p->nOp; i++){
  67916. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  67917. }
  67918. }
  67919. if( p->db->flags & SQLITE_VdbeEQP ){
  67920. for(i=0; i<p->nOp; i++){
  67921. if( aOp[i].opcode==OP_Explain ){
  67922. if( once ) printf("VDBE Query Plan:\n");
  67923. printf("%s\n", aOp[i].p4.z);
  67924. once = 0;
  67925. }
  67926. }
  67927. }
  67928. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  67929. }
  67930. sqlite3EndBenignMalloc();
  67931. #endif
  67932. for(pOp=&aOp[p->pc]; rc==SQLITE_OK; pOp++){
  67933. assert( pOp>=aOp && pOp<&aOp[p->nOp]);
  67934. if( db->mallocFailed ) goto no_mem;
  67935. #ifdef VDBE_PROFILE
  67936. start = sqlite3Hwtime();
  67937. #endif
  67938. nVmStep++;
  67939. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  67940. if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
  67941. #endif
  67942. /* Only allow tracing if SQLITE_DEBUG is defined.
  67943. */
  67944. #ifdef SQLITE_DEBUG
  67945. if( db->flags & SQLITE_VdbeTrace ){
  67946. sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
  67947. }
  67948. #endif
  67949. /* Check to see if we need to simulate an interrupt. This only happens
  67950. ** if we have a special test build.
  67951. */
  67952. #ifdef SQLITE_TEST
  67953. if( sqlite3_interrupt_count>0 ){
  67954. sqlite3_interrupt_count--;
  67955. if( sqlite3_interrupt_count==0 ){
  67956. sqlite3_interrupt(db);
  67957. }
  67958. }
  67959. #endif
  67960. /* Sanity checking on other operands */
  67961. #ifdef SQLITE_DEBUG
  67962. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  67963. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  67964. assert( pOp->p1>0 );
  67965. assert( pOp->p1<=(p->nMem-p->nCursor) );
  67966. assert( memIsValid(&aMem[pOp->p1]) );
  67967. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  67968. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  67969. }
  67970. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  67971. assert( pOp->p2>0 );
  67972. assert( pOp->p2<=(p->nMem-p->nCursor) );
  67973. assert( memIsValid(&aMem[pOp->p2]) );
  67974. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  67975. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  67976. }
  67977. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  67978. assert( pOp->p3>0 );
  67979. assert( pOp->p3<=(p->nMem-p->nCursor) );
  67980. assert( memIsValid(&aMem[pOp->p3]) );
  67981. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  67982. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  67983. }
  67984. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  67985. assert( pOp->p2>0 );
  67986. assert( pOp->p2<=(p->nMem-p->nCursor) );
  67987. memAboutToChange(p, &aMem[pOp->p2]);
  67988. }
  67989. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  67990. assert( pOp->p3>0 );
  67991. assert( pOp->p3<=(p->nMem-p->nCursor) );
  67992. memAboutToChange(p, &aMem[pOp->p3]);
  67993. }
  67994. #endif
  67995. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  67996. pOrigOp = pOp;
  67997. #endif
  67998. switch( pOp->opcode ){
  67999. /*****************************************************************************
  68000. ** What follows is a massive switch statement where each case implements a
  68001. ** separate instruction in the virtual machine. If we follow the usual
  68002. ** indentation conventions, each case should be indented by 6 spaces. But
  68003. ** that is a lot of wasted space on the left margin. So the code within
  68004. ** the switch statement will break with convention and be flush-left. Another
  68005. ** big comment (similar to this one) will mark the point in the code where
  68006. ** we transition back to normal indentation.
  68007. **
  68008. ** The formatting of each case is important. The makefile for SQLite
  68009. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  68010. ** file looking for lines that begin with "case OP_". The opcodes.h files
  68011. ** will be filled with #defines that give unique integer values to each
  68012. ** opcode and the opcodes.c file is filled with an array of strings where
  68013. ** each string is the symbolic name for the corresponding opcode. If the
  68014. ** case statement is followed by a comment of the form "/# same as ... #/"
  68015. ** that comment is used to determine the particular value of the opcode.
  68016. **
  68017. ** Other keywords in the comment that follows each case are used to
  68018. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  68019. ** Keywords include: in1, in2, in3, out2, out3. See
  68020. ** the mkopcodeh.awk script for additional information.
  68021. **
  68022. ** Documentation about VDBE opcodes is generated by scanning this file
  68023. ** for lines of that contain "Opcode:". That line and all subsequent
  68024. ** comment lines are used in the generation of the opcode.html documentation
  68025. ** file.
  68026. **
  68027. ** SUMMARY:
  68028. **
  68029. ** Formatting is important to scripts that scan this file.
  68030. ** Do not deviate from the formatting style currently in use.
  68031. **
  68032. *****************************************************************************/
  68033. /* Opcode: Goto * P2 * * *
  68034. **
  68035. ** An unconditional jump to address P2.
  68036. ** The next instruction executed will be
  68037. ** the one at index P2 from the beginning of
  68038. ** the program.
  68039. **
  68040. ** The P1 parameter is not actually used by this opcode. However, it
  68041. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  68042. ** that this Goto is the bottom of a loop and that the lines from P2 down
  68043. ** to the current line should be indented for EXPLAIN output.
  68044. */
  68045. case OP_Goto: { /* jump */
  68046. jump_to_p2_and_check_for_interrupt:
  68047. pOp = &aOp[pOp->p2 - 1];
  68048. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  68049. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  68050. ** completion. Check to see if sqlite3_interrupt() has been called
  68051. ** or if the progress callback needs to be invoked.
  68052. **
  68053. ** This code uses unstructured "goto" statements and does not look clean.
  68054. ** But that is not due to sloppy coding habits. The code is written this
  68055. ** way for performance, to avoid having to run the interrupt and progress
  68056. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  68057. ** faster according to "valgrind --tool=cachegrind" */
  68058. check_for_interrupt:
  68059. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  68060. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  68061. /* Call the progress callback if it is configured and the required number
  68062. ** of VDBE ops have been executed (either since this invocation of
  68063. ** sqlite3VdbeExec() or since last time the progress callback was called).
  68064. ** If the progress callback returns non-zero, exit the virtual machine with
  68065. ** a return code SQLITE_ABORT.
  68066. */
  68067. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  68068. assert( db->nProgressOps!=0 );
  68069. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  68070. if( db->xProgress(db->pProgressArg) ){
  68071. rc = SQLITE_INTERRUPT;
  68072. goto vdbe_error_halt;
  68073. }
  68074. }
  68075. #endif
  68076. break;
  68077. }
  68078. /* Opcode: Gosub P1 P2 * * *
  68079. **
  68080. ** Write the current address onto register P1
  68081. ** and then jump to address P2.
  68082. */
  68083. case OP_Gosub: { /* jump */
  68084. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  68085. pIn1 = &aMem[pOp->p1];
  68086. assert( VdbeMemDynamic(pIn1)==0 );
  68087. memAboutToChange(p, pIn1);
  68088. pIn1->flags = MEM_Int;
  68089. pIn1->u.i = (int)(pOp-aOp);
  68090. REGISTER_TRACE(pOp->p1, pIn1);
  68091. /* Most jump operations do a goto to this spot in order to update
  68092. ** the pOp pointer. */
  68093. jump_to_p2:
  68094. pOp = &aOp[pOp->p2 - 1];
  68095. break;
  68096. }
  68097. /* Opcode: Return P1 * * * *
  68098. **
  68099. ** Jump to the next instruction after the address in register P1. After
  68100. ** the jump, register P1 becomes undefined.
  68101. */
  68102. case OP_Return: { /* in1 */
  68103. pIn1 = &aMem[pOp->p1];
  68104. assert( pIn1->flags==MEM_Int );
  68105. pOp = &aOp[pIn1->u.i];
  68106. pIn1->flags = MEM_Undefined;
  68107. break;
  68108. }
  68109. /* Opcode: InitCoroutine P1 P2 P3 * *
  68110. **
  68111. ** Set up register P1 so that it will Yield to the coroutine
  68112. ** located at address P3.
  68113. **
  68114. ** If P2!=0 then the coroutine implementation immediately follows
  68115. ** this opcode. So jump over the coroutine implementation to
  68116. ** address P2.
  68117. **
  68118. ** See also: EndCoroutine
  68119. */
  68120. case OP_InitCoroutine: { /* jump */
  68121. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  68122. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  68123. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  68124. pOut = &aMem[pOp->p1];
  68125. assert( !VdbeMemDynamic(pOut) );
  68126. pOut->u.i = pOp->p3 - 1;
  68127. pOut->flags = MEM_Int;
  68128. if( pOp->p2 ) goto jump_to_p2;
  68129. break;
  68130. }
  68131. /* Opcode: EndCoroutine P1 * * * *
  68132. **
  68133. ** The instruction at the address in register P1 is a Yield.
  68134. ** Jump to the P2 parameter of that Yield.
  68135. ** After the jump, register P1 becomes undefined.
  68136. **
  68137. ** See also: InitCoroutine
  68138. */
  68139. case OP_EndCoroutine: { /* in1 */
  68140. VdbeOp *pCaller;
  68141. pIn1 = &aMem[pOp->p1];
  68142. assert( pIn1->flags==MEM_Int );
  68143. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  68144. pCaller = &aOp[pIn1->u.i];
  68145. assert( pCaller->opcode==OP_Yield );
  68146. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  68147. pOp = &aOp[pCaller->p2 - 1];
  68148. pIn1->flags = MEM_Undefined;
  68149. break;
  68150. }
  68151. /* Opcode: Yield P1 P2 * * *
  68152. **
  68153. ** Swap the program counter with the value in register P1. This
  68154. ** has the effect of yielding to a coroutine.
  68155. **
  68156. ** If the coroutine that is launched by this instruction ends with
  68157. ** Yield or Return then continue to the next instruction. But if
  68158. ** the coroutine launched by this instruction ends with
  68159. ** EndCoroutine, then jump to P2 rather than continuing with the
  68160. ** next instruction.
  68161. **
  68162. ** See also: InitCoroutine
  68163. */
  68164. case OP_Yield: { /* in1, jump */
  68165. int pcDest;
  68166. pIn1 = &aMem[pOp->p1];
  68167. assert( VdbeMemDynamic(pIn1)==0 );
  68168. pIn1->flags = MEM_Int;
  68169. pcDest = (int)pIn1->u.i;
  68170. pIn1->u.i = (int)(pOp - aOp);
  68171. REGISTER_TRACE(pOp->p1, pIn1);
  68172. pOp = &aOp[pcDest];
  68173. break;
  68174. }
  68175. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  68176. ** Synopsis: if r[P3]=null halt
  68177. **
  68178. ** Check the value in register P3. If it is NULL then Halt using
  68179. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  68180. ** value in register P3 is not NULL, then this routine is a no-op.
  68181. ** The P5 parameter should be 1.
  68182. */
  68183. case OP_HaltIfNull: { /* in3 */
  68184. pIn3 = &aMem[pOp->p3];
  68185. if( (pIn3->flags & MEM_Null)==0 ) break;
  68186. /* Fall through into OP_Halt */
  68187. }
  68188. /* Opcode: Halt P1 P2 * P4 P5
  68189. **
  68190. ** Exit immediately. All open cursors, etc are closed
  68191. ** automatically.
  68192. **
  68193. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  68194. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  68195. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  68196. ** whether or not to rollback the current transaction. Do not rollback
  68197. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  68198. ** then back out all changes that have occurred during this execution of the
  68199. ** VDBE, but do not rollback the transaction.
  68200. **
  68201. ** If P4 is not null then it is an error message string.
  68202. **
  68203. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  68204. **
  68205. ** 0: (no change)
  68206. ** 1: NOT NULL contraint failed: P4
  68207. ** 2: UNIQUE constraint failed: P4
  68208. ** 3: CHECK constraint failed: P4
  68209. ** 4: FOREIGN KEY constraint failed: P4
  68210. **
  68211. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  68212. ** omitted.
  68213. **
  68214. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  68215. ** every program. So a jump past the last instruction of the program
  68216. ** is the same as executing Halt.
  68217. */
  68218. case OP_Halt: {
  68219. const char *zType;
  68220. const char *zLogFmt;
  68221. VdbeFrame *pFrame;
  68222. int pcx;
  68223. pcx = (int)(pOp - aOp);
  68224. if( pOp->p1==SQLITE_OK && p->pFrame ){
  68225. /* Halt the sub-program. Return control to the parent frame. */
  68226. pFrame = p->pFrame;
  68227. p->pFrame = pFrame->pParent;
  68228. p->nFrame--;
  68229. sqlite3VdbeSetChanges(db, p->nChange);
  68230. pcx = sqlite3VdbeFrameRestore(pFrame);
  68231. lastRowid = db->lastRowid;
  68232. if( pOp->p2==OE_Ignore ){
  68233. /* Instruction pcx is the OP_Program that invoked the sub-program
  68234. ** currently being halted. If the p2 instruction of this OP_Halt
  68235. ** instruction is set to OE_Ignore, then the sub-program is throwing
  68236. ** an IGNORE exception. In this case jump to the address specified
  68237. ** as the p2 of the calling OP_Program. */
  68238. pcx = p->aOp[pcx].p2-1;
  68239. }
  68240. aOp = p->aOp;
  68241. aMem = p->aMem;
  68242. pOp = &aOp[pcx];
  68243. break;
  68244. }
  68245. p->rc = pOp->p1;
  68246. p->errorAction = (u8)pOp->p2;
  68247. p->pc = pcx;
  68248. if( p->rc ){
  68249. if( pOp->p5 ){
  68250. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  68251. "FOREIGN KEY" };
  68252. assert( pOp->p5>=1 && pOp->p5<=4 );
  68253. testcase( pOp->p5==1 );
  68254. testcase( pOp->p5==2 );
  68255. testcase( pOp->p5==3 );
  68256. testcase( pOp->p5==4 );
  68257. zType = azType[pOp->p5-1];
  68258. }else{
  68259. zType = 0;
  68260. }
  68261. assert( zType!=0 || pOp->p4.z!=0 );
  68262. zLogFmt = "abort at %d in [%s]: %s";
  68263. if( zType && pOp->p4.z ){
  68264. sqlite3VdbeError(p, "%s constraint failed: %s", zType, pOp->p4.z);
  68265. }else if( pOp->p4.z ){
  68266. sqlite3VdbeError(p, "%s", pOp->p4.z);
  68267. }else{
  68268. sqlite3VdbeError(p, "%s constraint failed", zType);
  68269. }
  68270. sqlite3_log(pOp->p1, zLogFmt, pcx, p->zSql, p->zErrMsg);
  68271. }
  68272. rc = sqlite3VdbeHalt(p);
  68273. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  68274. if( rc==SQLITE_BUSY ){
  68275. p->rc = rc = SQLITE_BUSY;
  68276. }else{
  68277. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  68278. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  68279. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  68280. }
  68281. goto vdbe_return;
  68282. }
  68283. /* Opcode: Integer P1 P2 * * *
  68284. ** Synopsis: r[P2]=P1
  68285. **
  68286. ** The 32-bit integer value P1 is written into register P2.
  68287. */
  68288. case OP_Integer: { /* out2 */
  68289. pOut = out2Prerelease(p, pOp);
  68290. pOut->u.i = pOp->p1;
  68291. break;
  68292. }
  68293. /* Opcode: Int64 * P2 * P4 *
  68294. ** Synopsis: r[P2]=P4
  68295. **
  68296. ** P4 is a pointer to a 64-bit integer value.
  68297. ** Write that value into register P2.
  68298. */
  68299. case OP_Int64: { /* out2 */
  68300. pOut = out2Prerelease(p, pOp);
  68301. assert( pOp->p4.pI64!=0 );
  68302. pOut->u.i = *pOp->p4.pI64;
  68303. break;
  68304. }
  68305. #ifndef SQLITE_OMIT_FLOATING_POINT
  68306. /* Opcode: Real * P2 * P4 *
  68307. ** Synopsis: r[P2]=P4
  68308. **
  68309. ** P4 is a pointer to a 64-bit floating point value.
  68310. ** Write that value into register P2.
  68311. */
  68312. case OP_Real: { /* same as TK_FLOAT, out2 */
  68313. pOut = out2Prerelease(p, pOp);
  68314. pOut->flags = MEM_Real;
  68315. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  68316. pOut->u.r = *pOp->p4.pReal;
  68317. break;
  68318. }
  68319. #endif
  68320. /* Opcode: String8 * P2 * P4 *
  68321. ** Synopsis: r[P2]='P4'
  68322. **
  68323. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  68324. ** into a String opcode before it is executed for the first time. During
  68325. ** this transformation, the length of string P4 is computed and stored
  68326. ** as the P1 parameter.
  68327. */
  68328. case OP_String8: { /* same as TK_STRING, out2 */
  68329. assert( pOp->p4.z!=0 );
  68330. pOut = out2Prerelease(p, pOp);
  68331. pOp->opcode = OP_String;
  68332. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  68333. #ifndef SQLITE_OMIT_UTF16
  68334. if( encoding!=SQLITE_UTF8 ){
  68335. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  68336. if( rc==SQLITE_TOOBIG ) goto too_big;
  68337. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  68338. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  68339. assert( VdbeMemDynamic(pOut)==0 );
  68340. pOut->szMalloc = 0;
  68341. pOut->flags |= MEM_Static;
  68342. if( pOp->p4type==P4_DYNAMIC ){
  68343. sqlite3DbFree(db, pOp->p4.z);
  68344. }
  68345. pOp->p4type = P4_DYNAMIC;
  68346. pOp->p4.z = pOut->z;
  68347. pOp->p1 = pOut->n;
  68348. }
  68349. #endif
  68350. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68351. goto too_big;
  68352. }
  68353. /* Fall through to the next case, OP_String */
  68354. }
  68355. /* Opcode: String P1 P2 P3 P4 P5
  68356. ** Synopsis: r[P2]='P4' (len=P1)
  68357. **
  68358. ** The string value P4 of length P1 (bytes) is stored in register P2.
  68359. **
  68360. ** If P5!=0 and the content of register P3 is greater than zero, then
  68361. ** the datatype of the register P2 is converted to BLOB. The content is
  68362. ** the same sequence of bytes, it is merely interpreted as a BLOB instead
  68363. ** of a string, as if it had been CAST.
  68364. */
  68365. case OP_String: { /* out2 */
  68366. assert( pOp->p4.z!=0 );
  68367. pOut = out2Prerelease(p, pOp);
  68368. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  68369. pOut->z = pOp->p4.z;
  68370. pOut->n = pOp->p1;
  68371. pOut->enc = encoding;
  68372. UPDATE_MAX_BLOBSIZE(pOut);
  68373. if( pOp->p5 ){
  68374. assert( pOp->p3>0 );
  68375. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68376. pIn3 = &aMem[pOp->p3];
  68377. assert( pIn3->flags & MEM_Int );
  68378. if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
  68379. }
  68380. break;
  68381. }
  68382. /* Opcode: Null P1 P2 P3 * *
  68383. ** Synopsis: r[P2..P3]=NULL
  68384. **
  68385. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  68386. ** NULL into register P3 and every register in between P2 and P3. If P3
  68387. ** is less than P2 (typically P3 is zero) then only register P2 is
  68388. ** set to NULL.
  68389. **
  68390. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  68391. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  68392. ** OP_Ne or OP_Eq.
  68393. */
  68394. case OP_Null: { /* out2 */
  68395. int cnt;
  68396. u16 nullFlag;
  68397. pOut = out2Prerelease(p, pOp);
  68398. cnt = pOp->p3-pOp->p2;
  68399. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68400. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  68401. while( cnt>0 ){
  68402. pOut++;
  68403. memAboutToChange(p, pOut);
  68404. sqlite3VdbeMemSetNull(pOut);
  68405. pOut->flags = nullFlag;
  68406. cnt--;
  68407. }
  68408. break;
  68409. }
  68410. /* Opcode: SoftNull P1 * * * *
  68411. ** Synopsis: r[P1]=NULL
  68412. **
  68413. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  68414. ** instruction, but do not free any string or blob memory associated with
  68415. ** the register, so that if the value was a string or blob that was
  68416. ** previously copied using OP_SCopy, the copies will continue to be valid.
  68417. */
  68418. case OP_SoftNull: {
  68419. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  68420. pOut = &aMem[pOp->p1];
  68421. pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
  68422. break;
  68423. }
  68424. /* Opcode: Blob P1 P2 * P4 *
  68425. ** Synopsis: r[P2]=P4 (len=P1)
  68426. **
  68427. ** P4 points to a blob of data P1 bytes long. Store this
  68428. ** blob in register P2.
  68429. */
  68430. case OP_Blob: { /* out2 */
  68431. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  68432. pOut = out2Prerelease(p, pOp);
  68433. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  68434. pOut->enc = encoding;
  68435. UPDATE_MAX_BLOBSIZE(pOut);
  68436. break;
  68437. }
  68438. /* Opcode: Variable P1 P2 * P4 *
  68439. ** Synopsis: r[P2]=parameter(P1,P4)
  68440. **
  68441. ** Transfer the values of bound parameter P1 into register P2
  68442. **
  68443. ** If the parameter is named, then its name appears in P4.
  68444. ** The P4 value is used by sqlite3_bind_parameter_name().
  68445. */
  68446. case OP_Variable: { /* out2 */
  68447. Mem *pVar; /* Value being transferred */
  68448. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  68449. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  68450. pVar = &p->aVar[pOp->p1 - 1];
  68451. if( sqlite3VdbeMemTooBig(pVar) ){
  68452. goto too_big;
  68453. }
  68454. pOut = out2Prerelease(p, pOp);
  68455. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  68456. UPDATE_MAX_BLOBSIZE(pOut);
  68457. break;
  68458. }
  68459. /* Opcode: Move P1 P2 P3 * *
  68460. ** Synopsis: r[P2@P3]=r[P1@P3]
  68461. **
  68462. ** Move the P3 values in register P1..P1+P3-1 over into
  68463. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  68464. ** left holding a NULL. It is an error for register ranges
  68465. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  68466. ** for P3 to be less than 1.
  68467. */
  68468. case OP_Move: {
  68469. int n; /* Number of registers left to copy */
  68470. int p1; /* Register to copy from */
  68471. int p2; /* Register to copy to */
  68472. n = pOp->p3;
  68473. p1 = pOp->p1;
  68474. p2 = pOp->p2;
  68475. assert( n>0 && p1>0 && p2>0 );
  68476. assert( p1+n<=p2 || p2+n<=p1 );
  68477. pIn1 = &aMem[p1];
  68478. pOut = &aMem[p2];
  68479. do{
  68480. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  68481. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  68482. assert( memIsValid(pIn1) );
  68483. memAboutToChange(p, pOut);
  68484. sqlite3VdbeMemMove(pOut, pIn1);
  68485. #ifdef SQLITE_DEBUG
  68486. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
  68487. pOut->pScopyFrom += pOp->p2 - p1;
  68488. }
  68489. #endif
  68490. Deephemeralize(pOut);
  68491. REGISTER_TRACE(p2++, pOut);
  68492. pIn1++;
  68493. pOut++;
  68494. }while( --n );
  68495. break;
  68496. }
  68497. /* Opcode: Copy P1 P2 P3 * *
  68498. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  68499. **
  68500. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  68501. **
  68502. ** This instruction makes a deep copy of the value. A duplicate
  68503. ** is made of any string or blob constant. See also OP_SCopy.
  68504. */
  68505. case OP_Copy: {
  68506. int n;
  68507. n = pOp->p3;
  68508. pIn1 = &aMem[pOp->p1];
  68509. pOut = &aMem[pOp->p2];
  68510. assert( pOut!=pIn1 );
  68511. while( 1 ){
  68512. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  68513. Deephemeralize(pOut);
  68514. #ifdef SQLITE_DEBUG
  68515. pOut->pScopyFrom = 0;
  68516. #endif
  68517. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  68518. if( (n--)==0 ) break;
  68519. pOut++;
  68520. pIn1++;
  68521. }
  68522. break;
  68523. }
  68524. /* Opcode: SCopy P1 P2 * * *
  68525. ** Synopsis: r[P2]=r[P1]
  68526. **
  68527. ** Make a shallow copy of register P1 into register P2.
  68528. **
  68529. ** This instruction makes a shallow copy of the value. If the value
  68530. ** is a string or blob, then the copy is only a pointer to the
  68531. ** original and hence if the original changes so will the copy.
  68532. ** Worse, if the original is deallocated, the copy becomes invalid.
  68533. ** Thus the program must guarantee that the original will not change
  68534. ** during the lifetime of the copy. Use OP_Copy to make a complete
  68535. ** copy.
  68536. */
  68537. case OP_SCopy: { /* out2 */
  68538. pIn1 = &aMem[pOp->p1];
  68539. pOut = &aMem[pOp->p2];
  68540. assert( pOut!=pIn1 );
  68541. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  68542. #ifdef SQLITE_DEBUG
  68543. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  68544. #endif
  68545. break;
  68546. }
  68547. /* Opcode: ResultRow P1 P2 * * *
  68548. ** Synopsis: output=r[P1@P2]
  68549. **
  68550. ** The registers P1 through P1+P2-1 contain a single row of
  68551. ** results. This opcode causes the sqlite3_step() call to terminate
  68552. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  68553. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  68554. ** the result row.
  68555. */
  68556. case OP_ResultRow: {
  68557. Mem *pMem;
  68558. int i;
  68559. assert( p->nResColumn==pOp->p2 );
  68560. assert( pOp->p1>0 );
  68561. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  68562. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  68563. /* Run the progress counter just before returning.
  68564. */
  68565. if( db->xProgress!=0
  68566. && nVmStep>=nProgressLimit
  68567. && db->xProgress(db->pProgressArg)!=0
  68568. ){
  68569. rc = SQLITE_INTERRUPT;
  68570. goto vdbe_error_halt;
  68571. }
  68572. #endif
  68573. /* If this statement has violated immediate foreign key constraints, do
  68574. ** not return the number of rows modified. And do not RELEASE the statement
  68575. ** transaction. It needs to be rolled back. */
  68576. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  68577. assert( db->flags&SQLITE_CountRows );
  68578. assert( p->usesStmtJournal );
  68579. break;
  68580. }
  68581. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  68582. ** DML statements invoke this opcode to return the number of rows
  68583. ** modified to the user. This is the only way that a VM that
  68584. ** opens a statement transaction may invoke this opcode.
  68585. **
  68586. ** In case this is such a statement, close any statement transaction
  68587. ** opened by this VM before returning control to the user. This is to
  68588. ** ensure that statement-transactions are always nested, not overlapping.
  68589. ** If the open statement-transaction is not closed here, then the user
  68590. ** may step another VM that opens its own statement transaction. This
  68591. ** may lead to overlapping statement transactions.
  68592. **
  68593. ** The statement transaction is never a top-level transaction. Hence
  68594. ** the RELEASE call below can never fail.
  68595. */
  68596. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  68597. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  68598. if( NEVER(rc!=SQLITE_OK) ){
  68599. break;
  68600. }
  68601. /* Invalidate all ephemeral cursor row caches */
  68602. p->cacheCtr = (p->cacheCtr + 2)|1;
  68603. /* Make sure the results of the current row are \000 terminated
  68604. ** and have an assigned type. The results are de-ephemeralized as
  68605. ** a side effect.
  68606. */
  68607. pMem = p->pResultSet = &aMem[pOp->p1];
  68608. for(i=0; i<pOp->p2; i++){
  68609. assert( memIsValid(&pMem[i]) );
  68610. Deephemeralize(&pMem[i]);
  68611. assert( (pMem[i].flags & MEM_Ephem)==0
  68612. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  68613. sqlite3VdbeMemNulTerminate(&pMem[i]);
  68614. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  68615. }
  68616. if( db->mallocFailed ) goto no_mem;
  68617. /* Return SQLITE_ROW
  68618. */
  68619. p->pc = (int)(pOp - aOp) + 1;
  68620. rc = SQLITE_ROW;
  68621. goto vdbe_return;
  68622. }
  68623. /* Opcode: Concat P1 P2 P3 * *
  68624. ** Synopsis: r[P3]=r[P2]+r[P1]
  68625. **
  68626. ** Add the text in register P1 onto the end of the text in
  68627. ** register P2 and store the result in register P3.
  68628. ** If either the P1 or P2 text are NULL then store NULL in P3.
  68629. **
  68630. ** P3 = P2 || P1
  68631. **
  68632. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  68633. ** if P3 is the same register as P2, the implementation is able
  68634. ** to avoid a memcpy().
  68635. */
  68636. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  68637. i64 nByte;
  68638. pIn1 = &aMem[pOp->p1];
  68639. pIn2 = &aMem[pOp->p2];
  68640. pOut = &aMem[pOp->p3];
  68641. assert( pIn1!=pOut );
  68642. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  68643. sqlite3VdbeMemSetNull(pOut);
  68644. break;
  68645. }
  68646. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  68647. Stringify(pIn1, encoding);
  68648. Stringify(pIn2, encoding);
  68649. nByte = pIn1->n + pIn2->n;
  68650. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68651. goto too_big;
  68652. }
  68653. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  68654. goto no_mem;
  68655. }
  68656. MemSetTypeFlag(pOut, MEM_Str);
  68657. if( pOut!=pIn2 ){
  68658. memcpy(pOut->z, pIn2->z, pIn2->n);
  68659. }
  68660. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  68661. pOut->z[nByte]=0;
  68662. pOut->z[nByte+1] = 0;
  68663. pOut->flags |= MEM_Term;
  68664. pOut->n = (int)nByte;
  68665. pOut->enc = encoding;
  68666. UPDATE_MAX_BLOBSIZE(pOut);
  68667. break;
  68668. }
  68669. /* Opcode: Add P1 P2 P3 * *
  68670. ** Synopsis: r[P3]=r[P1]+r[P2]
  68671. **
  68672. ** Add the value in register P1 to the value in register P2
  68673. ** and store the result in register P3.
  68674. ** If either input is NULL, the result is NULL.
  68675. */
  68676. /* Opcode: Multiply P1 P2 P3 * *
  68677. ** Synopsis: r[P3]=r[P1]*r[P2]
  68678. **
  68679. **
  68680. ** Multiply the value in register P1 by the value in register P2
  68681. ** and store the result in register P3.
  68682. ** If either input is NULL, the result is NULL.
  68683. */
  68684. /* Opcode: Subtract P1 P2 P3 * *
  68685. ** Synopsis: r[P3]=r[P2]-r[P1]
  68686. **
  68687. ** Subtract the value in register P1 from the value in register P2
  68688. ** and store the result in register P3.
  68689. ** If either input is NULL, the result is NULL.
  68690. */
  68691. /* Opcode: Divide P1 P2 P3 * *
  68692. ** Synopsis: r[P3]=r[P2]/r[P1]
  68693. **
  68694. ** Divide the value in register P1 by the value in register P2
  68695. ** and store the result in register P3 (P3=P2/P1). If the value in
  68696. ** register P1 is zero, then the result is NULL. If either input is
  68697. ** NULL, the result is NULL.
  68698. */
  68699. /* Opcode: Remainder P1 P2 P3 * *
  68700. ** Synopsis: r[P3]=r[P2]%r[P1]
  68701. **
  68702. ** Compute the remainder after integer register P2 is divided by
  68703. ** register P1 and store the result in register P3.
  68704. ** If the value in register P1 is zero the result is NULL.
  68705. ** If either operand is NULL, the result is NULL.
  68706. */
  68707. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  68708. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  68709. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  68710. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  68711. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  68712. char bIntint; /* Started out as two integer operands */
  68713. u16 flags; /* Combined MEM_* flags from both inputs */
  68714. u16 type1; /* Numeric type of left operand */
  68715. u16 type2; /* Numeric type of right operand */
  68716. i64 iA; /* Integer value of left operand */
  68717. i64 iB; /* Integer value of right operand */
  68718. double rA; /* Real value of left operand */
  68719. double rB; /* Real value of right operand */
  68720. pIn1 = &aMem[pOp->p1];
  68721. type1 = numericType(pIn1);
  68722. pIn2 = &aMem[pOp->p2];
  68723. type2 = numericType(pIn2);
  68724. pOut = &aMem[pOp->p3];
  68725. flags = pIn1->flags | pIn2->flags;
  68726. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  68727. if( (type1 & type2 & MEM_Int)!=0 ){
  68728. iA = pIn1->u.i;
  68729. iB = pIn2->u.i;
  68730. bIntint = 1;
  68731. switch( pOp->opcode ){
  68732. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  68733. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  68734. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  68735. case OP_Divide: {
  68736. if( iA==0 ) goto arithmetic_result_is_null;
  68737. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  68738. iB /= iA;
  68739. break;
  68740. }
  68741. default: {
  68742. if( iA==0 ) goto arithmetic_result_is_null;
  68743. if( iA==-1 ) iA = 1;
  68744. iB %= iA;
  68745. break;
  68746. }
  68747. }
  68748. pOut->u.i = iB;
  68749. MemSetTypeFlag(pOut, MEM_Int);
  68750. }else{
  68751. bIntint = 0;
  68752. fp_math:
  68753. rA = sqlite3VdbeRealValue(pIn1);
  68754. rB = sqlite3VdbeRealValue(pIn2);
  68755. switch( pOp->opcode ){
  68756. case OP_Add: rB += rA; break;
  68757. case OP_Subtract: rB -= rA; break;
  68758. case OP_Multiply: rB *= rA; break;
  68759. case OP_Divide: {
  68760. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  68761. if( rA==(double)0 ) goto arithmetic_result_is_null;
  68762. rB /= rA;
  68763. break;
  68764. }
  68765. default: {
  68766. iA = (i64)rA;
  68767. iB = (i64)rB;
  68768. if( iA==0 ) goto arithmetic_result_is_null;
  68769. if( iA==-1 ) iA = 1;
  68770. rB = (double)(iB % iA);
  68771. break;
  68772. }
  68773. }
  68774. #ifdef SQLITE_OMIT_FLOATING_POINT
  68775. pOut->u.i = rB;
  68776. MemSetTypeFlag(pOut, MEM_Int);
  68777. #else
  68778. if( sqlite3IsNaN(rB) ){
  68779. goto arithmetic_result_is_null;
  68780. }
  68781. pOut->u.r = rB;
  68782. MemSetTypeFlag(pOut, MEM_Real);
  68783. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  68784. sqlite3VdbeIntegerAffinity(pOut);
  68785. }
  68786. #endif
  68787. }
  68788. break;
  68789. arithmetic_result_is_null:
  68790. sqlite3VdbeMemSetNull(pOut);
  68791. break;
  68792. }
  68793. /* Opcode: CollSeq P1 * * P4
  68794. **
  68795. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  68796. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  68797. ** be returned. This is used by the built-in min(), max() and nullif()
  68798. ** functions.
  68799. **
  68800. ** If P1 is not zero, then it is a register that a subsequent min() or
  68801. ** max() aggregate will set to 1 if the current row is not the minimum or
  68802. ** maximum. The P1 register is initialized to 0 by this instruction.
  68803. **
  68804. ** The interface used by the implementation of the aforementioned functions
  68805. ** to retrieve the collation sequence set by this opcode is not available
  68806. ** publicly. Only built-in functions have access to this feature.
  68807. */
  68808. case OP_CollSeq: {
  68809. assert( pOp->p4type==P4_COLLSEQ );
  68810. if( pOp->p1 ){
  68811. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  68812. }
  68813. break;
  68814. }
  68815. /* Opcode: Function0 P1 P2 P3 P4 P5
  68816. ** Synopsis: r[P3]=func(r[P2@P5])
  68817. **
  68818. ** Invoke a user function (P4 is a pointer to a FuncDef object that
  68819. ** defines the function) with P5 arguments taken from register P2 and
  68820. ** successors. The result of the function is stored in register P3.
  68821. ** Register P3 must not be one of the function inputs.
  68822. **
  68823. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  68824. ** function was determined to be constant at compile time. If the first
  68825. ** argument was constant then bit 0 of P1 is set. This is used to determine
  68826. ** whether meta data associated with a user function argument using the
  68827. ** sqlite3_set_auxdata() API may be safely retained until the next
  68828. ** invocation of this opcode.
  68829. **
  68830. ** See also: Function, AggStep, AggFinal
  68831. */
  68832. /* Opcode: Function P1 P2 P3 P4 P5
  68833. ** Synopsis: r[P3]=func(r[P2@P5])
  68834. **
  68835. ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
  68836. ** contains a pointer to the function to be run) with P5 arguments taken
  68837. ** from register P2 and successors. The result of the function is stored
  68838. ** in register P3. Register P3 must not be one of the function inputs.
  68839. **
  68840. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  68841. ** function was determined to be constant at compile time. If the first
  68842. ** argument was constant then bit 0 of P1 is set. This is used to determine
  68843. ** whether meta data associated with a user function argument using the
  68844. ** sqlite3_set_auxdata() API may be safely retained until the next
  68845. ** invocation of this opcode.
  68846. **
  68847. ** SQL functions are initially coded as OP_Function0 with P4 pointing
  68848. ** to a FuncDef object. But on first evaluation, the P4 operand is
  68849. ** automatically converted into an sqlite3_context object and the operation
  68850. ** changed to this OP_Function opcode. In this way, the initialization of
  68851. ** the sqlite3_context object occurs only once, rather than once for each
  68852. ** evaluation of the function.
  68853. **
  68854. ** See also: Function0, AggStep, AggFinal
  68855. */
  68856. case OP_Function0: {
  68857. int n;
  68858. sqlite3_context *pCtx;
  68859. assert( pOp->p4type==P4_FUNCDEF );
  68860. n = pOp->p5;
  68861. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  68862. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  68863. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  68864. pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  68865. if( pCtx==0 ) goto no_mem;
  68866. pCtx->pOut = 0;
  68867. pCtx->pFunc = pOp->p4.pFunc;
  68868. pCtx->iOp = (int)(pOp - aOp);
  68869. pCtx->pVdbe = p;
  68870. pCtx->argc = n;
  68871. pOp->p4type = P4_FUNCCTX;
  68872. pOp->p4.pCtx = pCtx;
  68873. pOp->opcode = OP_Function;
  68874. /* Fall through into OP_Function */
  68875. }
  68876. case OP_Function: {
  68877. int i;
  68878. sqlite3_context *pCtx;
  68879. assert( pOp->p4type==P4_FUNCCTX );
  68880. pCtx = pOp->p4.pCtx;
  68881. /* If this function is inside of a trigger, the register array in aMem[]
  68882. ** might change from one evaluation to the next. The next block of code
  68883. ** checks to see if the register array has changed, and if so it
  68884. ** reinitializes the relavant parts of the sqlite3_context object */
  68885. pOut = &aMem[pOp->p3];
  68886. if( pCtx->pOut != pOut ){
  68887. pCtx->pOut = pOut;
  68888. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  68889. }
  68890. memAboutToChange(p, pCtx->pOut);
  68891. #ifdef SQLITE_DEBUG
  68892. for(i=0; i<pCtx->argc; i++){
  68893. assert( memIsValid(pCtx->argv[i]) );
  68894. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  68895. }
  68896. #endif
  68897. MemSetTypeFlag(pCtx->pOut, MEM_Null);
  68898. pCtx->fErrorOrAux = 0;
  68899. db->lastRowid = lastRowid;
  68900. (*pCtx->pFunc->xFunc)(pCtx, pCtx->argc, pCtx->argv); /* IMP: R-24505-23230 */
  68901. lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
  68902. /* If the function returned an error, throw an exception */
  68903. if( pCtx->fErrorOrAux ){
  68904. if( pCtx->isError ){
  68905. sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
  68906. rc = pCtx->isError;
  68907. }
  68908. sqlite3VdbeDeleteAuxData(p, pCtx->iOp, pOp->p1);
  68909. }
  68910. /* Copy the result of the function into register P3 */
  68911. if( pOut->flags & (MEM_Str|MEM_Blob) ){
  68912. sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
  68913. if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
  68914. }
  68915. REGISTER_TRACE(pOp->p3, pCtx->pOut);
  68916. UPDATE_MAX_BLOBSIZE(pCtx->pOut);
  68917. break;
  68918. }
  68919. /* Opcode: BitAnd P1 P2 P3 * *
  68920. ** Synopsis: r[P3]=r[P1]&r[P2]
  68921. **
  68922. ** Take the bit-wise AND of the values in register P1 and P2 and
  68923. ** store the result in register P3.
  68924. ** If either input is NULL, the result is NULL.
  68925. */
  68926. /* Opcode: BitOr P1 P2 P3 * *
  68927. ** Synopsis: r[P3]=r[P1]|r[P2]
  68928. **
  68929. ** Take the bit-wise OR of the values in register P1 and P2 and
  68930. ** store the result in register P3.
  68931. ** If either input is NULL, the result is NULL.
  68932. */
  68933. /* Opcode: ShiftLeft P1 P2 P3 * *
  68934. ** Synopsis: r[P3]=r[P2]<<r[P1]
  68935. **
  68936. ** Shift the integer value in register P2 to the left by the
  68937. ** number of bits specified by the integer in register P1.
  68938. ** Store the result in register P3.
  68939. ** If either input is NULL, the result is NULL.
  68940. */
  68941. /* Opcode: ShiftRight P1 P2 P3 * *
  68942. ** Synopsis: r[P3]=r[P2]>>r[P1]
  68943. **
  68944. ** Shift the integer value in register P2 to the right by the
  68945. ** number of bits specified by the integer in register P1.
  68946. ** Store the result in register P3.
  68947. ** If either input is NULL, the result is NULL.
  68948. */
  68949. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  68950. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  68951. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  68952. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  68953. i64 iA;
  68954. u64 uA;
  68955. i64 iB;
  68956. u8 op;
  68957. pIn1 = &aMem[pOp->p1];
  68958. pIn2 = &aMem[pOp->p2];
  68959. pOut = &aMem[pOp->p3];
  68960. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  68961. sqlite3VdbeMemSetNull(pOut);
  68962. break;
  68963. }
  68964. iA = sqlite3VdbeIntValue(pIn2);
  68965. iB = sqlite3VdbeIntValue(pIn1);
  68966. op = pOp->opcode;
  68967. if( op==OP_BitAnd ){
  68968. iA &= iB;
  68969. }else if( op==OP_BitOr ){
  68970. iA |= iB;
  68971. }else if( iB!=0 ){
  68972. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  68973. /* If shifting by a negative amount, shift in the other direction */
  68974. if( iB<0 ){
  68975. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  68976. op = 2*OP_ShiftLeft + 1 - op;
  68977. iB = iB>(-64) ? -iB : 64;
  68978. }
  68979. if( iB>=64 ){
  68980. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  68981. }else{
  68982. memcpy(&uA, &iA, sizeof(uA));
  68983. if( op==OP_ShiftLeft ){
  68984. uA <<= iB;
  68985. }else{
  68986. uA >>= iB;
  68987. /* Sign-extend on a right shift of a negative number */
  68988. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  68989. }
  68990. memcpy(&iA, &uA, sizeof(iA));
  68991. }
  68992. }
  68993. pOut->u.i = iA;
  68994. MemSetTypeFlag(pOut, MEM_Int);
  68995. break;
  68996. }
  68997. /* Opcode: AddImm P1 P2 * * *
  68998. ** Synopsis: r[P1]=r[P1]+P2
  68999. **
  69000. ** Add the constant P2 to the value in register P1.
  69001. ** The result is always an integer.
  69002. **
  69003. ** To force any register to be an integer, just add 0.
  69004. */
  69005. case OP_AddImm: { /* in1 */
  69006. pIn1 = &aMem[pOp->p1];
  69007. memAboutToChange(p, pIn1);
  69008. sqlite3VdbeMemIntegerify(pIn1);
  69009. pIn1->u.i += pOp->p2;
  69010. break;
  69011. }
  69012. /* Opcode: MustBeInt P1 P2 * * *
  69013. **
  69014. ** Force the value in register P1 to be an integer. If the value
  69015. ** in P1 is not an integer and cannot be converted into an integer
  69016. ** without data loss, then jump immediately to P2, or if P2==0
  69017. ** raise an SQLITE_MISMATCH exception.
  69018. */
  69019. case OP_MustBeInt: { /* jump, in1 */
  69020. pIn1 = &aMem[pOp->p1];
  69021. if( (pIn1->flags & MEM_Int)==0 ){
  69022. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  69023. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  69024. if( (pIn1->flags & MEM_Int)==0 ){
  69025. if( pOp->p2==0 ){
  69026. rc = SQLITE_MISMATCH;
  69027. goto abort_due_to_error;
  69028. }else{
  69029. goto jump_to_p2;
  69030. }
  69031. }
  69032. }
  69033. MemSetTypeFlag(pIn1, MEM_Int);
  69034. break;
  69035. }
  69036. #ifndef SQLITE_OMIT_FLOATING_POINT
  69037. /* Opcode: RealAffinity P1 * * * *
  69038. **
  69039. ** If register P1 holds an integer convert it to a real value.
  69040. **
  69041. ** This opcode is used when extracting information from a column that
  69042. ** has REAL affinity. Such column values may still be stored as
  69043. ** integers, for space efficiency, but after extraction we want them
  69044. ** to have only a real value.
  69045. */
  69046. case OP_RealAffinity: { /* in1 */
  69047. pIn1 = &aMem[pOp->p1];
  69048. if( pIn1->flags & MEM_Int ){
  69049. sqlite3VdbeMemRealify(pIn1);
  69050. }
  69051. break;
  69052. }
  69053. #endif
  69054. #ifndef SQLITE_OMIT_CAST
  69055. /* Opcode: Cast P1 P2 * * *
  69056. ** Synopsis: affinity(r[P1])
  69057. **
  69058. ** Force the value in register P1 to be the type defined by P2.
  69059. **
  69060. ** <ul>
  69061. ** <li value="97"> TEXT
  69062. ** <li value="98"> BLOB
  69063. ** <li value="99"> NUMERIC
  69064. ** <li value="100"> INTEGER
  69065. ** <li value="101"> REAL
  69066. ** </ul>
  69067. **
  69068. ** A NULL value is not changed by this routine. It remains NULL.
  69069. */
  69070. case OP_Cast: { /* in1 */
  69071. assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
  69072. testcase( pOp->p2==SQLITE_AFF_TEXT );
  69073. testcase( pOp->p2==SQLITE_AFF_BLOB );
  69074. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  69075. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  69076. testcase( pOp->p2==SQLITE_AFF_REAL );
  69077. pIn1 = &aMem[pOp->p1];
  69078. memAboutToChange(p, pIn1);
  69079. rc = ExpandBlob(pIn1);
  69080. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  69081. UPDATE_MAX_BLOBSIZE(pIn1);
  69082. break;
  69083. }
  69084. #endif /* SQLITE_OMIT_CAST */
  69085. /* Opcode: Lt P1 P2 P3 P4 P5
  69086. ** Synopsis: if r[P1]<r[P3] goto P2
  69087. **
  69088. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  69089. ** jump to address P2.
  69090. **
  69091. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  69092. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  69093. ** bit is clear then fall through if either operand is NULL.
  69094. **
  69095. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  69096. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  69097. ** to coerce both inputs according to this affinity before the
  69098. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  69099. ** affinity is used. Note that the affinity conversions are stored
  69100. ** back into the input registers P1 and P3. So this opcode can cause
  69101. ** persistent changes to registers P1 and P3.
  69102. **
  69103. ** Once any conversions have taken place, and neither value is NULL,
  69104. ** the values are compared. If both values are blobs then memcmp() is
  69105. ** used to determine the results of the comparison. If both values
  69106. ** are text, then the appropriate collating function specified in
  69107. ** P4 is used to do the comparison. If P4 is not specified then
  69108. ** memcmp() is used to compare text string. If both values are
  69109. ** numeric, then a numeric comparison is used. If the two values
  69110. ** are of different types, then numbers are considered less than
  69111. ** strings and strings are considered less than blobs.
  69112. **
  69113. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  69114. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  69115. **
  69116. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  69117. ** equal to one another, provided that they do not have their MEM_Cleared
  69118. ** bit set.
  69119. */
  69120. /* Opcode: Ne P1 P2 P3 P4 P5
  69121. ** Synopsis: if r[P1]!=r[P3] goto P2
  69122. **
  69123. ** This works just like the Lt opcode except that the jump is taken if
  69124. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  69125. ** additional information.
  69126. **
  69127. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  69128. ** true or false and is never NULL. If both operands are NULL then the result
  69129. ** of comparison is false. If either operand is NULL then the result is true.
  69130. ** If neither operand is NULL the result is the same as it would be if
  69131. ** the SQLITE_NULLEQ flag were omitted from P5.
  69132. */
  69133. /* Opcode: Eq P1 P2 P3 P4 P5
  69134. ** Synopsis: if r[P1]==r[P3] goto P2
  69135. **
  69136. ** This works just like the Lt opcode except that the jump is taken if
  69137. ** the operands in registers P1 and P3 are equal.
  69138. ** See the Lt opcode for additional information.
  69139. **
  69140. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  69141. ** true or false and is never NULL. If both operands are NULL then the result
  69142. ** of comparison is true. If either operand is NULL then the result is false.
  69143. ** If neither operand is NULL the result is the same as it would be if
  69144. ** the SQLITE_NULLEQ flag were omitted from P5.
  69145. */
  69146. /* Opcode: Le P1 P2 P3 P4 P5
  69147. ** Synopsis: if r[P1]<=r[P3] goto P2
  69148. **
  69149. ** This works just like the Lt opcode except that the jump is taken if
  69150. ** the content of register P3 is less than or equal to the content of
  69151. ** register P1. See the Lt opcode for additional information.
  69152. */
  69153. /* Opcode: Gt P1 P2 P3 P4 P5
  69154. ** Synopsis: if r[P1]>r[P3] goto P2
  69155. **
  69156. ** This works just like the Lt opcode except that the jump is taken if
  69157. ** the content of register P3 is greater than the content of
  69158. ** register P1. See the Lt opcode for additional information.
  69159. */
  69160. /* Opcode: Ge P1 P2 P3 P4 P5
  69161. ** Synopsis: if r[P1]>=r[P3] goto P2
  69162. **
  69163. ** This works just like the Lt opcode except that the jump is taken if
  69164. ** the content of register P3 is greater than or equal to the content of
  69165. ** register P1. See the Lt opcode for additional information.
  69166. */
  69167. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  69168. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  69169. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  69170. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  69171. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  69172. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  69173. int res; /* Result of the comparison of pIn1 against pIn3 */
  69174. char affinity; /* Affinity to use for comparison */
  69175. u16 flags1; /* Copy of initial value of pIn1->flags */
  69176. u16 flags3; /* Copy of initial value of pIn3->flags */
  69177. pIn1 = &aMem[pOp->p1];
  69178. pIn3 = &aMem[pOp->p3];
  69179. flags1 = pIn1->flags;
  69180. flags3 = pIn3->flags;
  69181. if( (flags1 | flags3)&MEM_Null ){
  69182. /* One or both operands are NULL */
  69183. if( pOp->p5 & SQLITE_NULLEQ ){
  69184. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  69185. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  69186. ** or not both operands are null.
  69187. */
  69188. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  69189. assert( (flags1 & MEM_Cleared)==0 );
  69190. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  69191. if( (flags1&MEM_Null)!=0
  69192. && (flags3&MEM_Null)!=0
  69193. && (flags3&MEM_Cleared)==0
  69194. ){
  69195. res = 0; /* Results are equal */
  69196. }else{
  69197. res = 1; /* Results are not equal */
  69198. }
  69199. }else{
  69200. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  69201. ** then the result is always NULL.
  69202. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  69203. */
  69204. if( pOp->p5 & SQLITE_STOREP2 ){
  69205. pOut = &aMem[pOp->p2];
  69206. MemSetTypeFlag(pOut, MEM_Null);
  69207. REGISTER_TRACE(pOp->p2, pOut);
  69208. }else{
  69209. VdbeBranchTaken(2,3);
  69210. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  69211. goto jump_to_p2;
  69212. }
  69213. }
  69214. break;
  69215. }
  69216. }else{
  69217. /* Neither operand is NULL. Do a comparison. */
  69218. affinity = pOp->p5 & SQLITE_AFF_MASK;
  69219. if( affinity>=SQLITE_AFF_NUMERIC ){
  69220. if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  69221. applyNumericAffinity(pIn1,0);
  69222. }
  69223. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  69224. applyNumericAffinity(pIn3,0);
  69225. }
  69226. }else if( affinity==SQLITE_AFF_TEXT ){
  69227. if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
  69228. testcase( pIn1->flags & MEM_Int );
  69229. testcase( pIn1->flags & MEM_Real );
  69230. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  69231. testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
  69232. flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
  69233. }
  69234. if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
  69235. testcase( pIn3->flags & MEM_Int );
  69236. testcase( pIn3->flags & MEM_Real );
  69237. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  69238. testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
  69239. flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
  69240. }
  69241. }
  69242. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  69243. if( pIn1->flags & MEM_Zero ){
  69244. sqlite3VdbeMemExpandBlob(pIn1);
  69245. flags1 &= ~MEM_Zero;
  69246. }
  69247. if( pIn3->flags & MEM_Zero ){
  69248. sqlite3VdbeMemExpandBlob(pIn3);
  69249. flags3 &= ~MEM_Zero;
  69250. }
  69251. if( db->mallocFailed ) goto no_mem;
  69252. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  69253. }
  69254. switch( pOp->opcode ){
  69255. case OP_Eq: res = res==0; break;
  69256. case OP_Ne: res = res!=0; break;
  69257. case OP_Lt: res = res<0; break;
  69258. case OP_Le: res = res<=0; break;
  69259. case OP_Gt: res = res>0; break;
  69260. default: res = res>=0; break;
  69261. }
  69262. /* Undo any changes made by applyAffinity() to the input registers. */
  69263. assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
  69264. pIn1->flags = flags1;
  69265. assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
  69266. pIn3->flags = flags3;
  69267. if( pOp->p5 & SQLITE_STOREP2 ){
  69268. pOut = &aMem[pOp->p2];
  69269. memAboutToChange(p, pOut);
  69270. MemSetTypeFlag(pOut, MEM_Int);
  69271. pOut->u.i = res;
  69272. REGISTER_TRACE(pOp->p2, pOut);
  69273. }else{
  69274. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  69275. if( res ){
  69276. goto jump_to_p2;
  69277. }
  69278. }
  69279. break;
  69280. }
  69281. /* Opcode: Permutation * * * P4 *
  69282. **
  69283. ** Set the permutation used by the OP_Compare operator to be the array
  69284. ** of integers in P4.
  69285. **
  69286. ** The permutation is only valid until the next OP_Compare that has
  69287. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  69288. ** occur immediately prior to the OP_Compare.
  69289. */
  69290. case OP_Permutation: {
  69291. assert( pOp->p4type==P4_INTARRAY );
  69292. assert( pOp->p4.ai );
  69293. aPermute = pOp->p4.ai;
  69294. break;
  69295. }
  69296. /* Opcode: Compare P1 P2 P3 P4 P5
  69297. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  69298. **
  69299. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  69300. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  69301. ** the comparison for use by the next OP_Jump instruct.
  69302. **
  69303. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  69304. ** determined by the most recent OP_Permutation operator. If the
  69305. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  69306. ** order.
  69307. **
  69308. ** P4 is a KeyInfo structure that defines collating sequences and sort
  69309. ** orders for the comparison. The permutation applies to registers
  69310. ** only. The KeyInfo elements are used sequentially.
  69311. **
  69312. ** The comparison is a sort comparison, so NULLs compare equal,
  69313. ** NULLs are less than numbers, numbers are less than strings,
  69314. ** and strings are less than blobs.
  69315. */
  69316. case OP_Compare: {
  69317. int n;
  69318. int i;
  69319. int p1;
  69320. int p2;
  69321. const KeyInfo *pKeyInfo;
  69322. int idx;
  69323. CollSeq *pColl; /* Collating sequence to use on this term */
  69324. int bRev; /* True for DESCENDING sort order */
  69325. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  69326. n = pOp->p3;
  69327. pKeyInfo = pOp->p4.pKeyInfo;
  69328. assert( n>0 );
  69329. assert( pKeyInfo!=0 );
  69330. p1 = pOp->p1;
  69331. p2 = pOp->p2;
  69332. #if SQLITE_DEBUG
  69333. if( aPermute ){
  69334. int k, mx = 0;
  69335. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  69336. assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
  69337. assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
  69338. }else{
  69339. assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
  69340. assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
  69341. }
  69342. #endif /* SQLITE_DEBUG */
  69343. for(i=0; i<n; i++){
  69344. idx = aPermute ? aPermute[i] : i;
  69345. assert( memIsValid(&aMem[p1+idx]) );
  69346. assert( memIsValid(&aMem[p2+idx]) );
  69347. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  69348. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  69349. assert( i<pKeyInfo->nField );
  69350. pColl = pKeyInfo->aColl[i];
  69351. bRev = pKeyInfo->aSortOrder[i];
  69352. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  69353. if( iCompare ){
  69354. if( bRev ) iCompare = -iCompare;
  69355. break;
  69356. }
  69357. }
  69358. aPermute = 0;
  69359. break;
  69360. }
  69361. /* Opcode: Jump P1 P2 P3 * *
  69362. **
  69363. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  69364. ** in the most recent OP_Compare instruction the P1 vector was less than
  69365. ** equal to, or greater than the P2 vector, respectively.
  69366. */
  69367. case OP_Jump: { /* jump */
  69368. if( iCompare<0 ){
  69369. VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
  69370. }else if( iCompare==0 ){
  69371. VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
  69372. }else{
  69373. VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
  69374. }
  69375. break;
  69376. }
  69377. /* Opcode: And P1 P2 P3 * *
  69378. ** Synopsis: r[P3]=(r[P1] && r[P2])
  69379. **
  69380. ** Take the logical AND of the values in registers P1 and P2 and
  69381. ** write the result into register P3.
  69382. **
  69383. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  69384. ** the other input is NULL. A NULL and true or two NULLs give
  69385. ** a NULL output.
  69386. */
  69387. /* Opcode: Or P1 P2 P3 * *
  69388. ** Synopsis: r[P3]=(r[P1] || r[P2])
  69389. **
  69390. ** Take the logical OR of the values in register P1 and P2 and
  69391. ** store the answer in register P3.
  69392. **
  69393. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  69394. ** even if the other input is NULL. A NULL and false or two NULLs
  69395. ** give a NULL output.
  69396. */
  69397. case OP_And: /* same as TK_AND, in1, in2, out3 */
  69398. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  69399. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  69400. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  69401. pIn1 = &aMem[pOp->p1];
  69402. if( pIn1->flags & MEM_Null ){
  69403. v1 = 2;
  69404. }else{
  69405. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  69406. }
  69407. pIn2 = &aMem[pOp->p2];
  69408. if( pIn2->flags & MEM_Null ){
  69409. v2 = 2;
  69410. }else{
  69411. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  69412. }
  69413. if( pOp->opcode==OP_And ){
  69414. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  69415. v1 = and_logic[v1*3+v2];
  69416. }else{
  69417. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  69418. v1 = or_logic[v1*3+v2];
  69419. }
  69420. pOut = &aMem[pOp->p3];
  69421. if( v1==2 ){
  69422. MemSetTypeFlag(pOut, MEM_Null);
  69423. }else{
  69424. pOut->u.i = v1;
  69425. MemSetTypeFlag(pOut, MEM_Int);
  69426. }
  69427. break;
  69428. }
  69429. /* Opcode: Not P1 P2 * * *
  69430. ** Synopsis: r[P2]= !r[P1]
  69431. **
  69432. ** Interpret the value in register P1 as a boolean value. Store the
  69433. ** boolean complement in register P2. If the value in register P1 is
  69434. ** NULL, then a NULL is stored in P2.
  69435. */
  69436. case OP_Not: { /* same as TK_NOT, in1, out2 */
  69437. pIn1 = &aMem[pOp->p1];
  69438. pOut = &aMem[pOp->p2];
  69439. sqlite3VdbeMemSetNull(pOut);
  69440. if( (pIn1->flags & MEM_Null)==0 ){
  69441. pOut->flags = MEM_Int;
  69442. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  69443. }
  69444. break;
  69445. }
  69446. /* Opcode: BitNot P1 P2 * * *
  69447. ** Synopsis: r[P1]= ~r[P1]
  69448. **
  69449. ** Interpret the content of register P1 as an integer. Store the
  69450. ** ones-complement of the P1 value into register P2. If P1 holds
  69451. ** a NULL then store a NULL in P2.
  69452. */
  69453. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  69454. pIn1 = &aMem[pOp->p1];
  69455. pOut = &aMem[pOp->p2];
  69456. sqlite3VdbeMemSetNull(pOut);
  69457. if( (pIn1->flags & MEM_Null)==0 ){
  69458. pOut->flags = MEM_Int;
  69459. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  69460. }
  69461. break;
  69462. }
  69463. /* Opcode: Once P1 P2 * * *
  69464. **
  69465. ** Check the "once" flag number P1. If it is set, jump to instruction P2.
  69466. ** Otherwise, set the flag and fall through to the next instruction.
  69467. ** In other words, this opcode causes all following opcodes up through P2
  69468. ** (but not including P2) to run just once and to be skipped on subsequent
  69469. ** times through the loop.
  69470. **
  69471. ** All "once" flags are initially cleared whenever a prepared statement
  69472. ** first begins to run.
  69473. */
  69474. case OP_Once: { /* jump */
  69475. assert( pOp->p1<p->nOnceFlag );
  69476. VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  69477. if( p->aOnceFlag[pOp->p1] ){
  69478. goto jump_to_p2;
  69479. }else{
  69480. p->aOnceFlag[pOp->p1] = 1;
  69481. }
  69482. break;
  69483. }
  69484. /* Opcode: If P1 P2 P3 * *
  69485. **
  69486. ** Jump to P2 if the value in register P1 is true. The value
  69487. ** is considered true if it is numeric and non-zero. If the value
  69488. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  69489. */
  69490. /* Opcode: IfNot P1 P2 P3 * *
  69491. **
  69492. ** Jump to P2 if the value in register P1 is False. The value
  69493. ** is considered false if it has a numeric value of zero. If the value
  69494. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  69495. */
  69496. case OP_If: /* jump, in1 */
  69497. case OP_IfNot: { /* jump, in1 */
  69498. int c;
  69499. pIn1 = &aMem[pOp->p1];
  69500. if( pIn1->flags & MEM_Null ){
  69501. c = pOp->p3;
  69502. }else{
  69503. #ifdef SQLITE_OMIT_FLOATING_POINT
  69504. c = sqlite3VdbeIntValue(pIn1)!=0;
  69505. #else
  69506. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  69507. #endif
  69508. if( pOp->opcode==OP_IfNot ) c = !c;
  69509. }
  69510. VdbeBranchTaken(c!=0, 2);
  69511. if( c ){
  69512. goto jump_to_p2;
  69513. }
  69514. break;
  69515. }
  69516. /* Opcode: IsNull P1 P2 * * *
  69517. ** Synopsis: if r[P1]==NULL goto P2
  69518. **
  69519. ** Jump to P2 if the value in register P1 is NULL.
  69520. */
  69521. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  69522. pIn1 = &aMem[pOp->p1];
  69523. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  69524. if( (pIn1->flags & MEM_Null)!=0 ){
  69525. goto jump_to_p2;
  69526. }
  69527. break;
  69528. }
  69529. /* Opcode: NotNull P1 P2 * * *
  69530. ** Synopsis: if r[P1]!=NULL goto P2
  69531. **
  69532. ** Jump to P2 if the value in register P1 is not NULL.
  69533. */
  69534. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  69535. pIn1 = &aMem[pOp->p1];
  69536. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  69537. if( (pIn1->flags & MEM_Null)==0 ){
  69538. goto jump_to_p2;
  69539. }
  69540. break;
  69541. }
  69542. /* Opcode: Column P1 P2 P3 P4 P5
  69543. ** Synopsis: r[P3]=PX
  69544. **
  69545. ** Interpret the data that cursor P1 points to as a structure built using
  69546. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  69547. ** information about the format of the data.) Extract the P2-th column
  69548. ** from this record. If there are less that (P2+1)
  69549. ** values in the record, extract a NULL.
  69550. **
  69551. ** The value extracted is stored in register P3.
  69552. **
  69553. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  69554. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  69555. ** the result.
  69556. **
  69557. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  69558. ** then the cache of the cursor is reset prior to extracting the column.
  69559. ** The first OP_Column against a pseudo-table after the value of the content
  69560. ** register has changed should have this bit set.
  69561. **
  69562. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  69563. ** the result is guaranteed to only be used as the argument of a length()
  69564. ** or typeof() function, respectively. The loading of large blobs can be
  69565. ** skipped for length() and all content loading can be skipped for typeof().
  69566. */
  69567. case OP_Column: {
  69568. i64 payloadSize64; /* Number of bytes in the record */
  69569. int p2; /* column number to retrieve */
  69570. VdbeCursor *pC; /* The VDBE cursor */
  69571. BtCursor *pCrsr; /* The BTree cursor */
  69572. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  69573. int len; /* The length of the serialized data for the column */
  69574. int i; /* Loop counter */
  69575. Mem *pDest; /* Where to write the extracted value */
  69576. Mem sMem; /* For storing the record being decoded */
  69577. const u8 *zData; /* Part of the record being decoded */
  69578. const u8 *zHdr; /* Next unparsed byte of the header */
  69579. const u8 *zEndHdr; /* Pointer to first byte after the header */
  69580. u32 offset; /* Offset into the data */
  69581. u32 szField; /* Number of bytes in the content of a field */
  69582. u32 avail; /* Number of bytes of available data */
  69583. u32 t; /* A type code from the record header */
  69584. u16 fx; /* pDest->flags value */
  69585. Mem *pReg; /* PseudoTable input register */
  69586. p2 = pOp->p2;
  69587. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69588. pDest = &aMem[pOp->p3];
  69589. memAboutToChange(p, pDest);
  69590. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69591. pC = p->apCsr[pOp->p1];
  69592. assert( pC!=0 );
  69593. assert( p2<pC->nField );
  69594. aOffset = pC->aOffset;
  69595. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69596. assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
  69597. #endif
  69598. pCrsr = pC->pCursor;
  69599. assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
  69600. assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
  69601. /* If the cursor cache is stale, bring it up-to-date */
  69602. rc = sqlite3VdbeCursorMoveto(pC);
  69603. if( rc ) goto abort_due_to_error;
  69604. if( pC->cacheStatus!=p->cacheCtr ){
  69605. if( pC->nullRow ){
  69606. if( pCrsr==0 ){
  69607. assert( pC->pseudoTableReg>0 );
  69608. pReg = &aMem[pC->pseudoTableReg];
  69609. assert( pReg->flags & MEM_Blob );
  69610. assert( memIsValid(pReg) );
  69611. pC->payloadSize = pC->szRow = avail = pReg->n;
  69612. pC->aRow = (u8*)pReg->z;
  69613. }else{
  69614. sqlite3VdbeMemSetNull(pDest);
  69615. goto op_column_out;
  69616. }
  69617. }else{
  69618. assert( pCrsr );
  69619. if( pC->isTable==0 ){
  69620. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  69621. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  69622. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  69623. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  69624. ** payload size, so it is impossible for payloadSize64 to be
  69625. ** larger than 32 bits. */
  69626. assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
  69627. pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
  69628. pC->payloadSize = (u32)payloadSize64;
  69629. }else{
  69630. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  69631. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
  69632. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  69633. pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
  69634. }
  69635. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  69636. if( pC->payloadSize <= (u32)avail ){
  69637. pC->szRow = pC->payloadSize;
  69638. }else{
  69639. pC->szRow = avail;
  69640. }
  69641. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  69642. goto too_big;
  69643. }
  69644. }
  69645. pC->cacheStatus = p->cacheCtr;
  69646. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  69647. pC->nHdrParsed = 0;
  69648. aOffset[0] = offset;
  69649. /* Make sure a corrupt database has not given us an oversize header.
  69650. ** Do this now to avoid an oversize memory allocation.
  69651. **
  69652. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  69653. ** types use so much data space that there can only be 4096 and 32 of
  69654. ** them, respectively. So the maximum header length results from a
  69655. ** 3-byte type for each of the maximum of 32768 columns plus three
  69656. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  69657. */
  69658. if( offset > 98307 || offset > pC->payloadSize ){
  69659. rc = SQLITE_CORRUPT_BKPT;
  69660. goto op_column_error;
  69661. }
  69662. if( avail<offset ){
  69663. /* pC->aRow does not have to hold the entire row, but it does at least
  69664. ** need to cover the header of the record. If pC->aRow does not contain
  69665. ** the complete header, then set it to zero, forcing the header to be
  69666. ** dynamically allocated. */
  69667. pC->aRow = 0;
  69668. pC->szRow = 0;
  69669. }
  69670. /* The following goto is an optimization. It can be omitted and
  69671. ** everything will still work. But OP_Column is measurably faster
  69672. ** by skipping the subsequent conditional, which is always true.
  69673. */
  69674. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  69675. goto op_column_read_header;
  69676. }
  69677. /* Make sure at least the first p2+1 entries of the header have been
  69678. ** parsed and valid information is in aOffset[] and pC->aType[].
  69679. */
  69680. if( pC->nHdrParsed<=p2 ){
  69681. /* If there is more header available for parsing in the record, try
  69682. ** to extract additional fields up through the p2+1-th field
  69683. */
  69684. op_column_read_header:
  69685. if( pC->iHdrOffset<aOffset[0] ){
  69686. /* Make sure zData points to enough of the record to cover the header. */
  69687. if( pC->aRow==0 ){
  69688. memset(&sMem, 0, sizeof(sMem));
  69689. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
  69690. !pC->isTable, &sMem);
  69691. if( rc!=SQLITE_OK ){
  69692. goto op_column_error;
  69693. }
  69694. zData = (u8*)sMem.z;
  69695. }else{
  69696. zData = pC->aRow;
  69697. }
  69698. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  69699. i = pC->nHdrParsed;
  69700. offset = aOffset[i];
  69701. zHdr = zData + pC->iHdrOffset;
  69702. zEndHdr = zData + aOffset[0];
  69703. assert( i<=p2 && zHdr<zEndHdr );
  69704. do{
  69705. if( zHdr[0]<0x80 ){
  69706. t = zHdr[0];
  69707. zHdr++;
  69708. }else{
  69709. zHdr += sqlite3GetVarint32(zHdr, &t);
  69710. }
  69711. pC->aType[i] = t;
  69712. szField = sqlite3VdbeSerialTypeLen(t);
  69713. offset += szField;
  69714. if( offset<szField ){ /* True if offset overflows */
  69715. zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  69716. break;
  69717. }
  69718. i++;
  69719. aOffset[i] = offset;
  69720. }while( i<=p2 && zHdr<zEndHdr );
  69721. pC->nHdrParsed = i;
  69722. pC->iHdrOffset = (u32)(zHdr - zData);
  69723. if( pC->aRow==0 ){
  69724. sqlite3VdbeMemRelease(&sMem);
  69725. sMem.flags = MEM_Null;
  69726. }
  69727. /* The record is corrupt if any of the following are true:
  69728. ** (1) the bytes of the header extend past the declared header size
  69729. ** (zHdr>zEndHdr)
  69730. ** (2) the entire header was used but not all data was used
  69731. ** (zHdr==zEndHdr && offset!=pC->payloadSize)
  69732. ** (3) the end of the data extends beyond the end of the record.
  69733. ** (offset > pC->payloadSize)
  69734. */
  69735. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
  69736. || (offset > pC->payloadSize)
  69737. ){
  69738. rc = SQLITE_CORRUPT_BKPT;
  69739. goto op_column_error;
  69740. }
  69741. }
  69742. /* If after trying to extract new entries from the header, nHdrParsed is
  69743. ** still not up to p2, that means that the record has fewer than p2
  69744. ** columns. So the result will be either the default value or a NULL.
  69745. */
  69746. if( pC->nHdrParsed<=p2 ){
  69747. if( pOp->p4type==P4_MEM ){
  69748. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  69749. }else{
  69750. sqlite3VdbeMemSetNull(pDest);
  69751. }
  69752. goto op_column_out;
  69753. }
  69754. }
  69755. /* Extract the content for the p2+1-th column. Control can only
  69756. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  69757. ** all valid.
  69758. */
  69759. assert( p2<pC->nHdrParsed );
  69760. assert( rc==SQLITE_OK );
  69761. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  69762. if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
  69763. t = pC->aType[p2];
  69764. if( pC->szRow>=aOffset[p2+1] ){
  69765. /* This is the common case where the desired content fits on the original
  69766. ** page - where the content is not on an overflow page */
  69767. sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
  69768. }else{
  69769. /* This branch happens only when content is on overflow pages */
  69770. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  69771. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  69772. || (len = sqlite3VdbeSerialTypeLen(t))==0
  69773. ){
  69774. /* Content is irrelevant for
  69775. ** 1. the typeof() function,
  69776. ** 2. the length(X) function if X is a blob, and
  69777. ** 3. if the content length is zero.
  69778. ** So we might as well use bogus content rather than reading
  69779. ** content from disk. NULL will work for the value for strings
  69780. ** and blobs and whatever is in the payloadSize64 variable
  69781. ** will work for everything else. */
  69782. sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
  69783. }else{
  69784. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
  69785. pDest);
  69786. if( rc!=SQLITE_OK ){
  69787. goto op_column_error;
  69788. }
  69789. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  69790. pDest->flags &= ~MEM_Ephem;
  69791. }
  69792. }
  69793. pDest->enc = encoding;
  69794. op_column_out:
  69795. /* If the column value is an ephemeral string, go ahead and persist
  69796. ** that string in case the cursor moves before the column value is
  69797. ** used. The following code does the equivalent of Deephemeralize()
  69798. ** but does it faster. */
  69799. if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
  69800. fx = pDest->flags & (MEM_Str|MEM_Blob);
  69801. assert( fx!=0 );
  69802. zData = (const u8*)pDest->z;
  69803. len = pDest->n;
  69804. if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
  69805. memcpy(pDest->z, zData, len);
  69806. pDest->z[len] = 0;
  69807. pDest->z[len+1] = 0;
  69808. pDest->flags = fx|MEM_Term;
  69809. }
  69810. op_column_error:
  69811. UPDATE_MAX_BLOBSIZE(pDest);
  69812. REGISTER_TRACE(pOp->p3, pDest);
  69813. break;
  69814. }
  69815. /* Opcode: Affinity P1 P2 * P4 *
  69816. ** Synopsis: affinity(r[P1@P2])
  69817. **
  69818. ** Apply affinities to a range of P2 registers starting with P1.
  69819. **
  69820. ** P4 is a string that is P2 characters long. The nth character of the
  69821. ** string indicates the column affinity that should be used for the nth
  69822. ** memory cell in the range.
  69823. */
  69824. case OP_Affinity: {
  69825. const char *zAffinity; /* The affinity to be applied */
  69826. char cAff; /* A single character of affinity */
  69827. zAffinity = pOp->p4.z;
  69828. assert( zAffinity!=0 );
  69829. assert( zAffinity[pOp->p2]==0 );
  69830. pIn1 = &aMem[pOp->p1];
  69831. while( (cAff = *(zAffinity++))!=0 ){
  69832. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  69833. assert( memIsValid(pIn1) );
  69834. applyAffinity(pIn1, cAff, encoding);
  69835. pIn1++;
  69836. }
  69837. break;
  69838. }
  69839. /* Opcode: MakeRecord P1 P2 P3 P4 *
  69840. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  69841. **
  69842. ** Convert P2 registers beginning with P1 into the [record format]
  69843. ** use as a data record in a database table or as a key
  69844. ** in an index. The OP_Column opcode can decode the record later.
  69845. **
  69846. ** P4 may be a string that is P2 characters long. The nth character of the
  69847. ** string indicates the column affinity that should be used for the nth
  69848. ** field of the index key.
  69849. **
  69850. ** The mapping from character to affinity is given by the SQLITE_AFF_
  69851. ** macros defined in sqliteInt.h.
  69852. **
  69853. ** If P4 is NULL then all index fields have the affinity BLOB.
  69854. */
  69855. case OP_MakeRecord: {
  69856. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  69857. Mem *pRec; /* The new record */
  69858. u64 nData; /* Number of bytes of data space */
  69859. int nHdr; /* Number of bytes of header space */
  69860. i64 nByte; /* Data space required for this record */
  69861. i64 nZero; /* Number of zero bytes at the end of the record */
  69862. int nVarint; /* Number of bytes in a varint */
  69863. u32 serial_type; /* Type field */
  69864. Mem *pData0; /* First field to be combined into the record */
  69865. Mem *pLast; /* Last field of the record */
  69866. int nField; /* Number of fields in the record */
  69867. char *zAffinity; /* The affinity string for the record */
  69868. int file_format; /* File format to use for encoding */
  69869. int i; /* Space used in zNewRecord[] header */
  69870. int j; /* Space used in zNewRecord[] content */
  69871. int len; /* Length of a field */
  69872. /* Assuming the record contains N fields, the record format looks
  69873. ** like this:
  69874. **
  69875. ** ------------------------------------------------------------------------
  69876. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  69877. ** ------------------------------------------------------------------------
  69878. **
  69879. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  69880. ** and so forth.
  69881. **
  69882. ** Each type field is a varint representing the serial type of the
  69883. ** corresponding data element (see sqlite3VdbeSerialType()). The
  69884. ** hdr-size field is also a varint which is the offset from the beginning
  69885. ** of the record to data0.
  69886. */
  69887. nData = 0; /* Number of bytes of data space */
  69888. nHdr = 0; /* Number of bytes of header space */
  69889. nZero = 0; /* Number of zero bytes at the end of the record */
  69890. nField = pOp->p1;
  69891. zAffinity = pOp->p4.z;
  69892. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
  69893. pData0 = &aMem[nField];
  69894. nField = pOp->p2;
  69895. pLast = &pData0[nField-1];
  69896. file_format = p->minWriteFileFormat;
  69897. /* Identify the output register */
  69898. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  69899. pOut = &aMem[pOp->p3];
  69900. memAboutToChange(p, pOut);
  69901. /* Apply the requested affinity to all inputs
  69902. */
  69903. assert( pData0<=pLast );
  69904. if( zAffinity ){
  69905. pRec = pData0;
  69906. do{
  69907. applyAffinity(pRec++, *(zAffinity++), encoding);
  69908. assert( zAffinity[0]==0 || pRec<=pLast );
  69909. }while( zAffinity[0] );
  69910. }
  69911. /* Loop through the elements that will make up the record to figure
  69912. ** out how much space is required for the new record.
  69913. */
  69914. pRec = pLast;
  69915. do{
  69916. assert( memIsValid(pRec) );
  69917. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
  69918. len = sqlite3VdbeSerialTypeLen(serial_type);
  69919. if( pRec->flags & MEM_Zero ){
  69920. if( nData ){
  69921. if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
  69922. }else{
  69923. nZero += pRec->u.nZero;
  69924. len -= pRec->u.nZero;
  69925. }
  69926. }
  69927. nData += len;
  69928. testcase( serial_type==127 );
  69929. testcase( serial_type==128 );
  69930. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  69931. }while( (--pRec)>=pData0 );
  69932. /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
  69933. ** which determines the total number of bytes in the header. The varint
  69934. ** value is the size of the header in bytes including the size varint
  69935. ** itself. */
  69936. testcase( nHdr==126 );
  69937. testcase( nHdr==127 );
  69938. if( nHdr<=126 ){
  69939. /* The common case */
  69940. nHdr += 1;
  69941. }else{
  69942. /* Rare case of a really large header */
  69943. nVarint = sqlite3VarintLen(nHdr);
  69944. nHdr += nVarint;
  69945. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  69946. }
  69947. nByte = nHdr+nData;
  69948. if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  69949. goto too_big;
  69950. }
  69951. /* Make sure the output register has a buffer large enough to store
  69952. ** the new record. The output register (pOp->p3) is not allowed to
  69953. ** be one of the input registers (because the following call to
  69954. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  69955. */
  69956. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  69957. goto no_mem;
  69958. }
  69959. zNewRecord = (u8 *)pOut->z;
  69960. /* Write the record */
  69961. i = putVarint32(zNewRecord, nHdr);
  69962. j = nHdr;
  69963. assert( pData0<=pLast );
  69964. pRec = pData0;
  69965. do{
  69966. serial_type = pRec->uTemp;
  69967. /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
  69968. ** additional varints, one per column. */
  69969. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  69970. /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
  69971. ** immediately follow the header. */
  69972. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  69973. }while( (++pRec)<=pLast );
  69974. assert( i==nHdr );
  69975. assert( j==nByte );
  69976. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69977. pOut->n = (int)nByte;
  69978. pOut->flags = MEM_Blob;
  69979. if( nZero ){
  69980. pOut->u.nZero = nZero;
  69981. pOut->flags |= MEM_Zero;
  69982. }
  69983. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  69984. REGISTER_TRACE(pOp->p3, pOut);
  69985. UPDATE_MAX_BLOBSIZE(pOut);
  69986. break;
  69987. }
  69988. /* Opcode: Count P1 P2 * * *
  69989. ** Synopsis: r[P2]=count()
  69990. **
  69991. ** Store the number of entries (an integer value) in the table or index
  69992. ** opened by cursor P1 in register P2
  69993. */
  69994. #ifndef SQLITE_OMIT_BTREECOUNT
  69995. case OP_Count: { /* out2 */
  69996. i64 nEntry;
  69997. BtCursor *pCrsr;
  69998. pCrsr = p->apCsr[pOp->p1]->pCursor;
  69999. assert( pCrsr );
  70000. nEntry = 0; /* Not needed. Only used to silence a warning. */
  70001. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  70002. pOut = out2Prerelease(p, pOp);
  70003. pOut->u.i = nEntry;
  70004. break;
  70005. }
  70006. #endif
  70007. /* Opcode: Savepoint P1 * * P4 *
  70008. **
  70009. ** Open, release or rollback the savepoint named by parameter P4, depending
  70010. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  70011. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  70012. */
  70013. case OP_Savepoint: {
  70014. int p1; /* Value of P1 operand */
  70015. char *zName; /* Name of savepoint */
  70016. int nName;
  70017. Savepoint *pNew;
  70018. Savepoint *pSavepoint;
  70019. Savepoint *pTmp;
  70020. int iSavepoint;
  70021. int ii;
  70022. p1 = pOp->p1;
  70023. zName = pOp->p4.z;
  70024. /* Assert that the p1 parameter is valid. Also that if there is no open
  70025. ** transaction, then there cannot be any savepoints.
  70026. */
  70027. assert( db->pSavepoint==0 || db->autoCommit==0 );
  70028. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  70029. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  70030. assert( checkSavepointCount(db) );
  70031. assert( p->bIsReader );
  70032. if( p1==SAVEPOINT_BEGIN ){
  70033. if( db->nVdbeWrite>0 ){
  70034. /* A new savepoint cannot be created if there are active write
  70035. ** statements (i.e. open read/write incremental blob handles).
  70036. */
  70037. sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
  70038. rc = SQLITE_BUSY;
  70039. }else{
  70040. nName = sqlite3Strlen30(zName);
  70041. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70042. /* This call is Ok even if this savepoint is actually a transaction
  70043. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  70044. ** If this is a transaction savepoint being opened, it is guaranteed
  70045. ** that the db->aVTrans[] array is empty. */
  70046. assert( db->autoCommit==0 || db->nVTrans==0 );
  70047. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  70048. db->nStatement+db->nSavepoint);
  70049. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70050. #endif
  70051. /* Create a new savepoint structure. */
  70052. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  70053. if( pNew ){
  70054. pNew->zName = (char *)&pNew[1];
  70055. memcpy(pNew->zName, zName, nName+1);
  70056. /* If there is no open transaction, then mark this as a special
  70057. ** "transaction savepoint". */
  70058. if( db->autoCommit ){
  70059. db->autoCommit = 0;
  70060. db->isTransactionSavepoint = 1;
  70061. }else{
  70062. db->nSavepoint++;
  70063. }
  70064. /* Link the new savepoint into the database handle's list. */
  70065. pNew->pNext = db->pSavepoint;
  70066. db->pSavepoint = pNew;
  70067. pNew->nDeferredCons = db->nDeferredCons;
  70068. pNew->nDeferredImmCons = db->nDeferredImmCons;
  70069. }
  70070. }
  70071. }else{
  70072. iSavepoint = 0;
  70073. /* Find the named savepoint. If there is no such savepoint, then an
  70074. ** an error is returned to the user. */
  70075. for(
  70076. pSavepoint = db->pSavepoint;
  70077. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  70078. pSavepoint = pSavepoint->pNext
  70079. ){
  70080. iSavepoint++;
  70081. }
  70082. if( !pSavepoint ){
  70083. sqlite3VdbeError(p, "no such savepoint: %s", zName);
  70084. rc = SQLITE_ERROR;
  70085. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  70086. /* It is not possible to release (commit) a savepoint if there are
  70087. ** active write statements.
  70088. */
  70089. sqlite3VdbeError(p, "cannot release savepoint - "
  70090. "SQL statements in progress");
  70091. rc = SQLITE_BUSY;
  70092. }else{
  70093. /* Determine whether or not this is a transaction savepoint. If so,
  70094. ** and this is a RELEASE command, then the current transaction
  70095. ** is committed.
  70096. */
  70097. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  70098. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  70099. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  70100. goto vdbe_return;
  70101. }
  70102. db->autoCommit = 1;
  70103. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  70104. p->pc = (int)(pOp - aOp);
  70105. db->autoCommit = 0;
  70106. p->rc = rc = SQLITE_BUSY;
  70107. goto vdbe_return;
  70108. }
  70109. db->isTransactionSavepoint = 0;
  70110. rc = p->rc;
  70111. }else{
  70112. int isSchemaChange;
  70113. iSavepoint = db->nSavepoint - iSavepoint - 1;
  70114. if( p1==SAVEPOINT_ROLLBACK ){
  70115. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  70116. for(ii=0; ii<db->nDb; ii++){
  70117. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  70118. SQLITE_ABORT_ROLLBACK,
  70119. isSchemaChange==0);
  70120. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70121. }
  70122. }else{
  70123. isSchemaChange = 0;
  70124. }
  70125. for(ii=0; ii<db->nDb; ii++){
  70126. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  70127. if( rc!=SQLITE_OK ){
  70128. goto abort_due_to_error;
  70129. }
  70130. }
  70131. if( isSchemaChange ){
  70132. sqlite3ExpirePreparedStatements(db);
  70133. sqlite3ResetAllSchemasOfConnection(db);
  70134. db->flags = (db->flags | SQLITE_InternChanges);
  70135. }
  70136. }
  70137. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  70138. ** savepoints nested inside of the savepoint being operated on. */
  70139. while( db->pSavepoint!=pSavepoint ){
  70140. pTmp = db->pSavepoint;
  70141. db->pSavepoint = pTmp->pNext;
  70142. sqlite3DbFree(db, pTmp);
  70143. db->nSavepoint--;
  70144. }
  70145. /* If it is a RELEASE, then destroy the savepoint being operated on
  70146. ** too. If it is a ROLLBACK TO, then set the number of deferred
  70147. ** constraint violations present in the database to the value stored
  70148. ** when the savepoint was created. */
  70149. if( p1==SAVEPOINT_RELEASE ){
  70150. assert( pSavepoint==db->pSavepoint );
  70151. db->pSavepoint = pSavepoint->pNext;
  70152. sqlite3DbFree(db, pSavepoint);
  70153. if( !isTransaction ){
  70154. db->nSavepoint--;
  70155. }
  70156. }else{
  70157. db->nDeferredCons = pSavepoint->nDeferredCons;
  70158. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  70159. }
  70160. if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
  70161. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  70162. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70163. }
  70164. }
  70165. }
  70166. break;
  70167. }
  70168. /* Opcode: AutoCommit P1 P2 * * *
  70169. **
  70170. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  70171. ** back any currently active btree transactions. If there are any active
  70172. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  70173. ** there are active writing VMs or active VMs that use shared cache.
  70174. **
  70175. ** This instruction causes the VM to halt.
  70176. */
  70177. case OP_AutoCommit: {
  70178. int desiredAutoCommit;
  70179. int iRollback;
  70180. int turnOnAC;
  70181. desiredAutoCommit = pOp->p1;
  70182. iRollback = pOp->p2;
  70183. turnOnAC = desiredAutoCommit && !db->autoCommit;
  70184. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  70185. assert( desiredAutoCommit==1 || iRollback==0 );
  70186. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  70187. assert( p->bIsReader );
  70188. if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
  70189. /* If this instruction implements a COMMIT and other VMs are writing
  70190. ** return an error indicating that the other VMs must complete first.
  70191. */
  70192. sqlite3VdbeError(p, "cannot commit transaction - "
  70193. "SQL statements in progress");
  70194. rc = SQLITE_BUSY;
  70195. }else if( desiredAutoCommit!=db->autoCommit ){
  70196. if( iRollback ){
  70197. assert( desiredAutoCommit==1 );
  70198. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  70199. db->autoCommit = 1;
  70200. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  70201. goto vdbe_return;
  70202. }else{
  70203. db->autoCommit = (u8)desiredAutoCommit;
  70204. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  70205. p->pc = (int)(pOp - aOp);
  70206. db->autoCommit = (u8)(1-desiredAutoCommit);
  70207. p->rc = rc = SQLITE_BUSY;
  70208. goto vdbe_return;
  70209. }
  70210. }
  70211. assert( db->nStatement==0 );
  70212. sqlite3CloseSavepoints(db);
  70213. if( p->rc==SQLITE_OK ){
  70214. rc = SQLITE_DONE;
  70215. }else{
  70216. rc = SQLITE_ERROR;
  70217. }
  70218. goto vdbe_return;
  70219. }else{
  70220. sqlite3VdbeError(p,
  70221. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  70222. (iRollback)?"cannot rollback - no transaction is active":
  70223. "cannot commit - no transaction is active"));
  70224. rc = SQLITE_ERROR;
  70225. }
  70226. break;
  70227. }
  70228. /* Opcode: Transaction P1 P2 P3 P4 P5
  70229. **
  70230. ** Begin a transaction on database P1 if a transaction is not already
  70231. ** active.
  70232. ** If P2 is non-zero, then a write-transaction is started, or if a
  70233. ** read-transaction is already active, it is upgraded to a write-transaction.
  70234. ** If P2 is zero, then a read-transaction is started.
  70235. **
  70236. ** P1 is the index of the database file on which the transaction is
  70237. ** started. Index 0 is the main database file and index 1 is the
  70238. ** file used for temporary tables. Indices of 2 or more are used for
  70239. ** attached databases.
  70240. **
  70241. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  70242. ** true (this flag is set if the Vdbe may modify more than one row and may
  70243. ** throw an ABORT exception), a statement transaction may also be opened.
  70244. ** More specifically, a statement transaction is opened iff the database
  70245. ** connection is currently not in autocommit mode, or if there are other
  70246. ** active statements. A statement transaction allows the changes made by this
  70247. ** VDBE to be rolled back after an error without having to roll back the
  70248. ** entire transaction. If no error is encountered, the statement transaction
  70249. ** will automatically commit when the VDBE halts.
  70250. **
  70251. ** If P5!=0 then this opcode also checks the schema cookie against P3
  70252. ** and the schema generation counter against P4.
  70253. ** The cookie changes its value whenever the database schema changes.
  70254. ** This operation is used to detect when that the cookie has changed
  70255. ** and that the current process needs to reread the schema. If the schema
  70256. ** cookie in P3 differs from the schema cookie in the database header or
  70257. ** if the schema generation counter in P4 differs from the current
  70258. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  70259. ** halts. The sqlite3_step() wrapper function might then reprepare the
  70260. ** statement and rerun it from the beginning.
  70261. */
  70262. case OP_Transaction: {
  70263. Btree *pBt;
  70264. int iMeta;
  70265. int iGen;
  70266. assert( p->bIsReader );
  70267. assert( p->readOnly==0 || pOp->p2==0 );
  70268. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70269. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  70270. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  70271. rc = SQLITE_READONLY;
  70272. goto abort_due_to_error;
  70273. }
  70274. pBt = db->aDb[pOp->p1].pBt;
  70275. if( pBt ){
  70276. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  70277. if( rc==SQLITE_BUSY ){
  70278. p->pc = (int)(pOp - aOp);
  70279. p->rc = rc = SQLITE_BUSY;
  70280. goto vdbe_return;
  70281. }
  70282. if( rc!=SQLITE_OK ){
  70283. goto abort_due_to_error;
  70284. }
  70285. if( pOp->p2 && p->usesStmtJournal
  70286. && (db->autoCommit==0 || db->nVdbeRead>1)
  70287. ){
  70288. assert( sqlite3BtreeIsInTrans(pBt) );
  70289. if( p->iStatement==0 ){
  70290. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  70291. db->nStatement++;
  70292. p->iStatement = db->nSavepoint + db->nStatement;
  70293. }
  70294. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  70295. if( rc==SQLITE_OK ){
  70296. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  70297. }
  70298. /* Store the current value of the database handles deferred constraint
  70299. ** counter. If the statement transaction needs to be rolled back,
  70300. ** the value of this counter needs to be restored too. */
  70301. p->nStmtDefCons = db->nDeferredCons;
  70302. p->nStmtDefImmCons = db->nDeferredImmCons;
  70303. }
  70304. /* Gather the schema version number for checking:
  70305. ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
  70306. ** each time a query is executed to ensure that the internal cache of the
  70307. ** schema used when compiling the SQL query matches the schema of the
  70308. ** database against which the compiled query is actually executed.
  70309. */
  70310. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  70311. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  70312. }else{
  70313. iGen = iMeta = 0;
  70314. }
  70315. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  70316. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  70317. sqlite3DbFree(db, p->zErrMsg);
  70318. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  70319. /* If the schema-cookie from the database file matches the cookie
  70320. ** stored with the in-memory representation of the schema, do
  70321. ** not reload the schema from the database file.
  70322. **
  70323. ** If virtual-tables are in use, this is not just an optimization.
  70324. ** Often, v-tables store their data in other SQLite tables, which
  70325. ** are queried from within xNext() and other v-table methods using
  70326. ** prepared queries. If such a query is out-of-date, we do not want to
  70327. ** discard the database schema, as the user code implementing the
  70328. ** v-table would have to be ready for the sqlite3_vtab structure itself
  70329. ** to be invalidated whenever sqlite3_step() is called from within
  70330. ** a v-table method.
  70331. */
  70332. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  70333. sqlite3ResetOneSchema(db, pOp->p1);
  70334. }
  70335. p->expired = 1;
  70336. rc = SQLITE_SCHEMA;
  70337. }
  70338. break;
  70339. }
  70340. /* Opcode: ReadCookie P1 P2 P3 * *
  70341. **
  70342. ** Read cookie number P3 from database P1 and write it into register P2.
  70343. ** P3==1 is the schema version. P3==2 is the database format.
  70344. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  70345. ** the main database file and P1==1 is the database file used to store
  70346. ** temporary tables.
  70347. **
  70348. ** There must be a read-lock on the database (either a transaction
  70349. ** must be started or there must be an open cursor) before
  70350. ** executing this instruction.
  70351. */
  70352. case OP_ReadCookie: { /* out2 */
  70353. int iMeta;
  70354. int iDb;
  70355. int iCookie;
  70356. assert( p->bIsReader );
  70357. iDb = pOp->p1;
  70358. iCookie = pOp->p3;
  70359. assert( pOp->p3<SQLITE_N_BTREE_META );
  70360. assert( iDb>=0 && iDb<db->nDb );
  70361. assert( db->aDb[iDb].pBt!=0 );
  70362. assert( DbMaskTest(p->btreeMask, iDb) );
  70363. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  70364. pOut = out2Prerelease(p, pOp);
  70365. pOut->u.i = iMeta;
  70366. break;
  70367. }
  70368. /* Opcode: SetCookie P1 P2 P3 * *
  70369. **
  70370. ** Write the content of register P3 (interpreted as an integer)
  70371. ** into cookie number P2 of database P1. P2==1 is the schema version.
  70372. ** P2==2 is the database format. P2==3 is the recommended pager cache
  70373. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  70374. ** database file used to store temporary tables.
  70375. **
  70376. ** A transaction must be started before executing this opcode.
  70377. */
  70378. case OP_SetCookie: { /* in3 */
  70379. Db *pDb;
  70380. assert( pOp->p2<SQLITE_N_BTREE_META );
  70381. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70382. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  70383. assert( p->readOnly==0 );
  70384. pDb = &db->aDb[pOp->p1];
  70385. assert( pDb->pBt!=0 );
  70386. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  70387. pIn3 = &aMem[pOp->p3];
  70388. sqlite3VdbeMemIntegerify(pIn3);
  70389. /* See note about index shifting on OP_ReadCookie */
  70390. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
  70391. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  70392. /* When the schema cookie changes, record the new cookie internally */
  70393. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  70394. db->flags |= SQLITE_InternChanges;
  70395. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  70396. /* Record changes in the file format */
  70397. pDb->pSchema->file_format = (u8)pIn3->u.i;
  70398. }
  70399. if( pOp->p1==1 ){
  70400. /* Invalidate all prepared statements whenever the TEMP database
  70401. ** schema is changed. Ticket #1644 */
  70402. sqlite3ExpirePreparedStatements(db);
  70403. p->expired = 0;
  70404. }
  70405. break;
  70406. }
  70407. /* Opcode: OpenRead P1 P2 P3 P4 P5
  70408. ** Synopsis: root=P2 iDb=P3
  70409. **
  70410. ** Open a read-only cursor for the database table whose root page is
  70411. ** P2 in a database file. The database file is determined by P3.
  70412. ** P3==0 means the main database, P3==1 means the database used for
  70413. ** temporary tables, and P3>1 means used the corresponding attached
  70414. ** database. Give the new cursor an identifier of P1. The P1
  70415. ** values need not be contiguous but all P1 values should be small integers.
  70416. ** It is an error for P1 to be negative.
  70417. **
  70418. ** If P5!=0 then use the content of register P2 as the root page, not
  70419. ** the value of P2 itself.
  70420. **
  70421. ** There will be a read lock on the database whenever there is an
  70422. ** open cursor. If the database was unlocked prior to this instruction
  70423. ** then a read lock is acquired as part of this instruction. A read
  70424. ** lock allows other processes to read the database but prohibits
  70425. ** any other process from modifying the database. The read lock is
  70426. ** released when all cursors are closed. If this instruction attempts
  70427. ** to get a read lock but fails, the script terminates with an
  70428. ** SQLITE_BUSY error code.
  70429. **
  70430. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  70431. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  70432. ** structure, then said structure defines the content and collating
  70433. ** sequence of the index being opened. Otherwise, if P4 is an integer
  70434. ** value, it is set to the number of columns in the table.
  70435. **
  70436. ** See also: OpenWrite, ReopenIdx
  70437. */
  70438. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  70439. ** Synopsis: root=P2 iDb=P3
  70440. **
  70441. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  70442. ** checks to see if the cursor on P1 is already open with a root page
  70443. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  70444. ** if the cursor is already open, do not reopen it.
  70445. **
  70446. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  70447. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  70448. ** every other ReopenIdx or OpenRead for the same cursor number.
  70449. **
  70450. ** See the OpenRead opcode documentation for additional information.
  70451. */
  70452. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  70453. ** Synopsis: root=P2 iDb=P3
  70454. **
  70455. ** Open a read/write cursor named P1 on the table or index whose root
  70456. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  70457. ** root page.
  70458. **
  70459. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  70460. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  70461. ** structure, then said structure defines the content and collating
  70462. ** sequence of the index being opened. Otherwise, if P4 is an integer
  70463. ** value, it is set to the number of columns in the table, or to the
  70464. ** largest index of any column of the table that is actually used.
  70465. **
  70466. ** This instruction works just like OpenRead except that it opens the cursor
  70467. ** in read/write mode. For a given table, there can be one or more read-only
  70468. ** cursors or a single read/write cursor but not both.
  70469. **
  70470. ** See also OpenRead.
  70471. */
  70472. case OP_ReopenIdx: {
  70473. int nField;
  70474. KeyInfo *pKeyInfo;
  70475. int p2;
  70476. int iDb;
  70477. int wrFlag;
  70478. Btree *pX;
  70479. VdbeCursor *pCur;
  70480. Db *pDb;
  70481. assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  70482. assert( pOp->p4type==P4_KEYINFO );
  70483. pCur = p->apCsr[pOp->p1];
  70484. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  70485. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  70486. goto open_cursor_set_hints;
  70487. }
  70488. /* If the cursor is not currently open or is open on a different
  70489. ** index, then fall through into OP_OpenRead to force a reopen */
  70490. case OP_OpenRead:
  70491. case OP_OpenWrite:
  70492. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR|OPFLAG_SEEKEQ))==pOp->p5 );
  70493. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
  70494. assert( p->bIsReader );
  70495. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  70496. || p->readOnly==0 );
  70497. if( p->expired ){
  70498. rc = SQLITE_ABORT_ROLLBACK;
  70499. break;
  70500. }
  70501. nField = 0;
  70502. pKeyInfo = 0;
  70503. p2 = pOp->p2;
  70504. iDb = pOp->p3;
  70505. assert( iDb>=0 && iDb<db->nDb );
  70506. assert( DbMaskTest(p->btreeMask, iDb) );
  70507. pDb = &db->aDb[iDb];
  70508. pX = pDb->pBt;
  70509. assert( pX!=0 );
  70510. if( pOp->opcode==OP_OpenWrite ){
  70511. wrFlag = 1;
  70512. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  70513. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  70514. p->minWriteFileFormat = pDb->pSchema->file_format;
  70515. }
  70516. }else{
  70517. wrFlag = 0;
  70518. }
  70519. if( pOp->p5 & OPFLAG_P2ISREG ){
  70520. assert( p2>0 );
  70521. assert( p2<=(p->nMem-p->nCursor) );
  70522. pIn2 = &aMem[p2];
  70523. assert( memIsValid(pIn2) );
  70524. assert( (pIn2->flags & MEM_Int)!=0 );
  70525. sqlite3VdbeMemIntegerify(pIn2);
  70526. p2 = (int)pIn2->u.i;
  70527. /* The p2 value always comes from a prior OP_CreateTable opcode and
  70528. ** that opcode will always set the p2 value to 2 or more or else fail.
  70529. ** If there were a failure, the prepared statement would have halted
  70530. ** before reaching this instruction. */
  70531. if( NEVER(p2<2) ) {
  70532. rc = SQLITE_CORRUPT_BKPT;
  70533. goto abort_due_to_error;
  70534. }
  70535. }
  70536. if( pOp->p4type==P4_KEYINFO ){
  70537. pKeyInfo = pOp->p4.pKeyInfo;
  70538. assert( pKeyInfo->enc==ENC(db) );
  70539. assert( pKeyInfo->db==db );
  70540. nField = pKeyInfo->nField+pKeyInfo->nXField;
  70541. }else if( pOp->p4type==P4_INT32 ){
  70542. nField = pOp->p4.i;
  70543. }
  70544. assert( pOp->p1>=0 );
  70545. assert( nField>=0 );
  70546. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  70547. pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
  70548. if( pCur==0 ) goto no_mem;
  70549. pCur->nullRow = 1;
  70550. pCur->isOrdered = 1;
  70551. pCur->pgnoRoot = p2;
  70552. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  70553. pCur->pKeyInfo = pKeyInfo;
  70554. /* Set the VdbeCursor.isTable variable. Previous versions of
  70555. ** SQLite used to check if the root-page flags were sane at this point
  70556. ** and report database corruption if they were not, but this check has
  70557. ** since moved into the btree layer. */
  70558. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  70559. open_cursor_set_hints:
  70560. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  70561. assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
  70562. sqlite3BtreeCursorHints(pCur->pCursor,
  70563. (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
  70564. break;
  70565. }
  70566. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  70567. ** Synopsis: nColumn=P2
  70568. **
  70569. ** Open a new cursor P1 to a transient table.
  70570. ** The cursor is always opened read/write even if
  70571. ** the main database is read-only. The ephemeral
  70572. ** table is deleted automatically when the cursor is closed.
  70573. **
  70574. ** P2 is the number of columns in the ephemeral table.
  70575. ** The cursor points to a BTree table if P4==0 and to a BTree index
  70576. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  70577. ** that defines the format of keys in the index.
  70578. **
  70579. ** The P5 parameter can be a mask of the BTREE_* flags defined
  70580. ** in btree.h. These flags control aspects of the operation of
  70581. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  70582. ** added automatically.
  70583. */
  70584. /* Opcode: OpenAutoindex P1 P2 * P4 *
  70585. ** Synopsis: nColumn=P2
  70586. **
  70587. ** This opcode works the same as OP_OpenEphemeral. It has a
  70588. ** different name to distinguish its use. Tables created using
  70589. ** by this opcode will be used for automatically created transient
  70590. ** indices in joins.
  70591. */
  70592. case OP_OpenAutoindex:
  70593. case OP_OpenEphemeral: {
  70594. VdbeCursor *pCx;
  70595. KeyInfo *pKeyInfo;
  70596. static const int vfsFlags =
  70597. SQLITE_OPEN_READWRITE |
  70598. SQLITE_OPEN_CREATE |
  70599. SQLITE_OPEN_EXCLUSIVE |
  70600. SQLITE_OPEN_DELETEONCLOSE |
  70601. SQLITE_OPEN_TRANSIENT_DB;
  70602. assert( pOp->p1>=0 );
  70603. assert( pOp->p2>=0 );
  70604. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  70605. if( pCx==0 ) goto no_mem;
  70606. pCx->nullRow = 1;
  70607. pCx->isEphemeral = 1;
  70608. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
  70609. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  70610. if( rc==SQLITE_OK ){
  70611. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  70612. }
  70613. if( rc==SQLITE_OK ){
  70614. /* If a transient index is required, create it by calling
  70615. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  70616. ** opening it. If a transient table is required, just use the
  70617. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  70618. */
  70619. if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  70620. int pgno;
  70621. assert( pOp->p4type==P4_KEYINFO );
  70622. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  70623. if( rc==SQLITE_OK ){
  70624. assert( pgno==MASTER_ROOT+1 );
  70625. assert( pKeyInfo->db==db );
  70626. assert( pKeyInfo->enc==ENC(db) );
  70627. pCx->pKeyInfo = pKeyInfo;
  70628. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
  70629. }
  70630. pCx->isTable = 0;
  70631. }else{
  70632. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
  70633. pCx->isTable = 1;
  70634. }
  70635. }
  70636. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  70637. break;
  70638. }
  70639. /* Opcode: SorterOpen P1 P2 P3 P4 *
  70640. **
  70641. ** This opcode works like OP_OpenEphemeral except that it opens
  70642. ** a transient index that is specifically designed to sort large
  70643. ** tables using an external merge-sort algorithm.
  70644. **
  70645. ** If argument P3 is non-zero, then it indicates that the sorter may
  70646. ** assume that a stable sort considering the first P3 fields of each
  70647. ** key is sufficient to produce the required results.
  70648. */
  70649. case OP_SorterOpen: {
  70650. VdbeCursor *pCx;
  70651. assert( pOp->p1>=0 );
  70652. assert( pOp->p2>=0 );
  70653. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  70654. if( pCx==0 ) goto no_mem;
  70655. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  70656. assert( pCx->pKeyInfo->db==db );
  70657. assert( pCx->pKeyInfo->enc==ENC(db) );
  70658. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  70659. break;
  70660. }
  70661. /* Opcode: SequenceTest P1 P2 * * *
  70662. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  70663. **
  70664. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  70665. ** to P2. Regardless of whether or not the jump is taken, increment the
  70666. ** the sequence value.
  70667. */
  70668. case OP_SequenceTest: {
  70669. VdbeCursor *pC;
  70670. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70671. pC = p->apCsr[pOp->p1];
  70672. assert( pC->pSorter );
  70673. if( (pC->seqCount++)==0 ){
  70674. goto jump_to_p2;
  70675. }
  70676. break;
  70677. }
  70678. /* Opcode: OpenPseudo P1 P2 P3 * *
  70679. ** Synopsis: P3 columns in r[P2]
  70680. **
  70681. ** Open a new cursor that points to a fake table that contains a single
  70682. ** row of data. The content of that one row is the content of memory
  70683. ** register P2. In other words, cursor P1 becomes an alias for the
  70684. ** MEM_Blob content contained in register P2.
  70685. **
  70686. ** A pseudo-table created by this opcode is used to hold a single
  70687. ** row output from the sorter so that the row can be decomposed into
  70688. ** individual columns using the OP_Column opcode. The OP_Column opcode
  70689. ** is the only cursor opcode that works with a pseudo-table.
  70690. **
  70691. ** P3 is the number of fields in the records that will be stored by
  70692. ** the pseudo-table.
  70693. */
  70694. case OP_OpenPseudo: {
  70695. VdbeCursor *pCx;
  70696. assert( pOp->p1>=0 );
  70697. assert( pOp->p3>=0 );
  70698. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  70699. if( pCx==0 ) goto no_mem;
  70700. pCx->nullRow = 1;
  70701. pCx->pseudoTableReg = pOp->p2;
  70702. pCx->isTable = 1;
  70703. assert( pOp->p5==0 );
  70704. break;
  70705. }
  70706. /* Opcode: Close P1 * * * *
  70707. **
  70708. ** Close a cursor previously opened as P1. If P1 is not
  70709. ** currently open, this instruction is a no-op.
  70710. */
  70711. case OP_Close: {
  70712. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70713. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  70714. p->apCsr[pOp->p1] = 0;
  70715. break;
  70716. }
  70717. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  70718. /* Opcode: ColumnsUsed P1 * * P4 *
  70719. **
  70720. ** This opcode (which only exists if SQLite was compiled with
  70721. ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
  70722. ** table or index for cursor P1 are used. P4 is a 64-bit integer
  70723. ** (P4_INT64) in which the first 63 bits are one for each of the
  70724. ** first 63 columns of the table or index that are actually used
  70725. ** by the cursor. The high-order bit is set if any column after
  70726. ** the 64th is used.
  70727. */
  70728. case OP_ColumnsUsed: {
  70729. VdbeCursor *pC;
  70730. pC = p->apCsr[pOp->p1];
  70731. assert( pC->pCursor );
  70732. pC->maskUsed = *(u64*)pOp->p4.pI64;
  70733. break;
  70734. }
  70735. #endif
  70736. /* Opcode: SeekGE P1 P2 P3 P4 *
  70737. ** Synopsis: key=r[P3@P4]
  70738. **
  70739. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  70740. ** use the value in register P3 as the key. If cursor P1 refers
  70741. ** to an SQL index, then P3 is the first in an array of P4 registers
  70742. ** that are used as an unpacked index key.
  70743. **
  70744. ** Reposition cursor P1 so that it points to the smallest entry that
  70745. ** is greater than or equal to the key value. If there are no records
  70746. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  70747. **
  70748. ** This opcode leaves the cursor configured to move in forward order,
  70749. ** from the beginning toward the end. In other words, the cursor is
  70750. ** configured to use Next, not Prev.
  70751. **
  70752. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  70753. */
  70754. /* Opcode: SeekGT P1 P2 P3 P4 *
  70755. ** Synopsis: key=r[P3@P4]
  70756. **
  70757. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  70758. ** use the value in register P3 as a key. If cursor P1 refers
  70759. ** to an SQL index, then P3 is the first in an array of P4 registers
  70760. ** that are used as an unpacked index key.
  70761. **
  70762. ** Reposition cursor P1 so that it points to the smallest entry that
  70763. ** is greater than the key value. If there are no records greater than
  70764. ** the key and P2 is not zero, then jump to P2.
  70765. **
  70766. ** This opcode leaves the cursor configured to move in forward order,
  70767. ** from the beginning toward the end. In other words, the cursor is
  70768. ** configured to use Next, not Prev.
  70769. **
  70770. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  70771. */
  70772. /* Opcode: SeekLT P1 P2 P3 P4 *
  70773. ** Synopsis: key=r[P3@P4]
  70774. **
  70775. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  70776. ** use the value in register P3 as a key. If cursor P1 refers
  70777. ** to an SQL index, then P3 is the first in an array of P4 registers
  70778. ** that are used as an unpacked index key.
  70779. **
  70780. ** Reposition cursor P1 so that it points to the largest entry that
  70781. ** is less than the key value. If there are no records less than
  70782. ** the key and P2 is not zero, then jump to P2.
  70783. **
  70784. ** This opcode leaves the cursor configured to move in reverse order,
  70785. ** from the end toward the beginning. In other words, the cursor is
  70786. ** configured to use Prev, not Next.
  70787. **
  70788. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  70789. */
  70790. /* Opcode: SeekLE P1 P2 P3 P4 *
  70791. ** Synopsis: key=r[P3@P4]
  70792. **
  70793. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  70794. ** use the value in register P3 as a key. If cursor P1 refers
  70795. ** to an SQL index, then P3 is the first in an array of P4 registers
  70796. ** that are used as an unpacked index key.
  70797. **
  70798. ** Reposition cursor P1 so that it points to the largest entry that
  70799. ** is less than or equal to the key value. If there are no records
  70800. ** less than or equal to the key and P2 is not zero, then jump to P2.
  70801. **
  70802. ** This opcode leaves the cursor configured to move in reverse order,
  70803. ** from the end toward the beginning. In other words, the cursor is
  70804. ** configured to use Prev, not Next.
  70805. **
  70806. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  70807. */
  70808. case OP_SeekLT: /* jump, in3 */
  70809. case OP_SeekLE: /* jump, in3 */
  70810. case OP_SeekGE: /* jump, in3 */
  70811. case OP_SeekGT: { /* jump, in3 */
  70812. int res;
  70813. int oc;
  70814. VdbeCursor *pC;
  70815. UnpackedRecord r;
  70816. int nField;
  70817. i64 iKey; /* The rowid we are to seek to */
  70818. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70819. assert( pOp->p2!=0 );
  70820. pC = p->apCsr[pOp->p1];
  70821. assert( pC!=0 );
  70822. assert( pC->pseudoTableReg==0 );
  70823. assert( OP_SeekLE == OP_SeekLT+1 );
  70824. assert( OP_SeekGE == OP_SeekLT+2 );
  70825. assert( OP_SeekGT == OP_SeekLT+3 );
  70826. assert( pC->isOrdered );
  70827. assert( pC->pCursor!=0 );
  70828. oc = pOp->opcode;
  70829. pC->nullRow = 0;
  70830. #ifdef SQLITE_DEBUG
  70831. pC->seekOp = pOp->opcode;
  70832. #endif
  70833. /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
  70834. ** OP_SeekLE opcodes are allowed, and these must be immediately followed
  70835. ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
  70836. */
  70837. #ifdef SQLITE_DEBUG
  70838. if( sqlite3BtreeCursorHasHint(pC->pCursor, BTREE_SEEK_EQ) ){
  70839. assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
  70840. assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
  70841. assert( pOp[1].p1==pOp[0].p1 );
  70842. assert( pOp[1].p2==pOp[0].p2 );
  70843. assert( pOp[1].p3==pOp[0].p3 );
  70844. assert( pOp[1].p4.i==pOp[0].p4.i );
  70845. }
  70846. #endif
  70847. if( pC->isTable ){
  70848. /* The input value in P3 might be of any type: integer, real, string,
  70849. ** blob, or NULL. But it needs to be an integer before we can do
  70850. ** the seek, so convert it. */
  70851. pIn3 = &aMem[pOp->p3];
  70852. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  70853. applyNumericAffinity(pIn3, 0);
  70854. }
  70855. iKey = sqlite3VdbeIntValue(pIn3);
  70856. /* If the P3 value could not be converted into an integer without
  70857. ** loss of information, then special processing is required... */
  70858. if( (pIn3->flags & MEM_Int)==0 ){
  70859. if( (pIn3->flags & MEM_Real)==0 ){
  70860. /* If the P3 value cannot be converted into any kind of a number,
  70861. ** then the seek is not possible, so jump to P2 */
  70862. VdbeBranchTaken(1,2); goto jump_to_p2;
  70863. break;
  70864. }
  70865. /* If the approximation iKey is larger than the actual real search
  70866. ** term, substitute >= for > and < for <=. e.g. if the search term
  70867. ** is 4.9 and the integer approximation 5:
  70868. **
  70869. ** (x > 4.9) -> (x >= 5)
  70870. ** (x <= 4.9) -> (x < 5)
  70871. */
  70872. if( pIn3->u.r<(double)iKey ){
  70873. assert( OP_SeekGE==(OP_SeekGT-1) );
  70874. assert( OP_SeekLT==(OP_SeekLE-1) );
  70875. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  70876. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  70877. }
  70878. /* If the approximation iKey is smaller than the actual real search
  70879. ** term, substitute <= for < and > for >=. */
  70880. else if( pIn3->u.r>(double)iKey ){
  70881. assert( OP_SeekLE==(OP_SeekLT+1) );
  70882. assert( OP_SeekGT==(OP_SeekGE+1) );
  70883. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  70884. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  70885. }
  70886. }
  70887. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  70888. pC->movetoTarget = iKey; /* Used by OP_Delete */
  70889. if( rc!=SQLITE_OK ){
  70890. goto abort_due_to_error;
  70891. }
  70892. }else{
  70893. nField = pOp->p4.i;
  70894. assert( pOp->p4type==P4_INT32 );
  70895. assert( nField>0 );
  70896. r.pKeyInfo = pC->pKeyInfo;
  70897. r.nField = (u16)nField;
  70898. /* The next line of code computes as follows, only faster:
  70899. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  70900. ** r.default_rc = -1;
  70901. ** }else{
  70902. ** r.default_rc = +1;
  70903. ** }
  70904. */
  70905. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  70906. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  70907. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  70908. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  70909. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  70910. r.aMem = &aMem[pOp->p3];
  70911. #ifdef SQLITE_DEBUG
  70912. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  70913. #endif
  70914. ExpandBlob(r.aMem);
  70915. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
  70916. if( rc!=SQLITE_OK ){
  70917. goto abort_due_to_error;
  70918. }
  70919. }
  70920. pC->deferredMoveto = 0;
  70921. pC->cacheStatus = CACHE_STALE;
  70922. #ifdef SQLITE_TEST
  70923. sqlite3_search_count++;
  70924. #endif
  70925. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  70926. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  70927. res = 0;
  70928. rc = sqlite3BtreeNext(pC->pCursor, &res);
  70929. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70930. }else{
  70931. res = 0;
  70932. }
  70933. }else{
  70934. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  70935. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  70936. res = 0;
  70937. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  70938. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  70939. }else{
  70940. /* res might be negative because the table is empty. Check to
  70941. ** see if this is the case.
  70942. */
  70943. res = sqlite3BtreeEof(pC->pCursor);
  70944. }
  70945. }
  70946. assert( pOp->p2>0 );
  70947. VdbeBranchTaken(res!=0,2);
  70948. if( res ){
  70949. goto jump_to_p2;
  70950. }
  70951. break;
  70952. }
  70953. /* Opcode: Seek P1 P2 * * *
  70954. ** Synopsis: intkey=r[P2]
  70955. **
  70956. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  70957. ** for P1 to move so that it points to the rowid given by P2.
  70958. **
  70959. ** This is actually a deferred seek. Nothing actually happens until
  70960. ** the cursor is used to read a record. That way, if no reads
  70961. ** occur, no unnecessary I/O happens.
  70962. */
  70963. case OP_Seek: { /* in2 */
  70964. VdbeCursor *pC;
  70965. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  70966. pC = p->apCsr[pOp->p1];
  70967. assert( pC!=0 );
  70968. assert( pC->pCursor!=0 );
  70969. assert( pC->isTable );
  70970. pC->nullRow = 0;
  70971. pIn2 = &aMem[pOp->p2];
  70972. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  70973. pC->deferredMoveto = 1;
  70974. break;
  70975. }
  70976. /* Opcode: Found P1 P2 P3 P4 *
  70977. ** Synopsis: key=r[P3@P4]
  70978. **
  70979. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  70980. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  70981. ** record.
  70982. **
  70983. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  70984. ** is a prefix of any entry in P1 then a jump is made to P2 and
  70985. ** P1 is left pointing at the matching entry.
  70986. **
  70987. ** This operation leaves the cursor in a state where it can be
  70988. ** advanced in the forward direction. The Next instruction will work,
  70989. ** but not the Prev instruction.
  70990. **
  70991. ** See also: NotFound, NoConflict, NotExists. SeekGe
  70992. */
  70993. /* Opcode: NotFound P1 P2 P3 P4 *
  70994. ** Synopsis: key=r[P3@P4]
  70995. **
  70996. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  70997. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  70998. ** record.
  70999. **
  71000. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  71001. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  71002. ** does contain an entry whose prefix matches the P3/P4 record then control
  71003. ** falls through to the next instruction and P1 is left pointing at the
  71004. ** matching entry.
  71005. **
  71006. ** This operation leaves the cursor in a state where it cannot be
  71007. ** advanced in either direction. In other words, the Next and Prev
  71008. ** opcodes do not work after this operation.
  71009. **
  71010. ** See also: Found, NotExists, NoConflict
  71011. */
  71012. /* Opcode: NoConflict P1 P2 P3 P4 *
  71013. ** Synopsis: key=r[P3@P4]
  71014. **
  71015. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  71016. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  71017. ** record.
  71018. **
  71019. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  71020. ** contains any NULL value, jump immediately to P2. If all terms of the
  71021. ** record are not-NULL then a check is done to determine if any row in the
  71022. ** P1 index btree has a matching key prefix. If there are no matches, jump
  71023. ** immediately to P2. If there is a match, fall through and leave the P1
  71024. ** cursor pointing to the matching row.
  71025. **
  71026. ** This opcode is similar to OP_NotFound with the exceptions that the
  71027. ** branch is always taken if any part of the search key input is NULL.
  71028. **
  71029. ** This operation leaves the cursor in a state where it cannot be
  71030. ** advanced in either direction. In other words, the Next and Prev
  71031. ** opcodes do not work after this operation.
  71032. **
  71033. ** See also: NotFound, Found, NotExists
  71034. */
  71035. case OP_NoConflict: /* jump, in3 */
  71036. case OP_NotFound: /* jump, in3 */
  71037. case OP_Found: { /* jump, in3 */
  71038. int alreadyExists;
  71039. int takeJump;
  71040. int ii;
  71041. VdbeCursor *pC;
  71042. int res;
  71043. char *pFree;
  71044. UnpackedRecord *pIdxKey;
  71045. UnpackedRecord r;
  71046. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
  71047. #ifdef SQLITE_TEST
  71048. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  71049. #endif
  71050. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71051. assert( pOp->p4type==P4_INT32 );
  71052. pC = p->apCsr[pOp->p1];
  71053. assert( pC!=0 );
  71054. #ifdef SQLITE_DEBUG
  71055. pC->seekOp = pOp->opcode;
  71056. #endif
  71057. pIn3 = &aMem[pOp->p3];
  71058. assert( pC->pCursor!=0 );
  71059. assert( pC->isTable==0 );
  71060. pFree = 0;
  71061. if( pOp->p4.i>0 ){
  71062. r.pKeyInfo = pC->pKeyInfo;
  71063. r.nField = (u16)pOp->p4.i;
  71064. r.aMem = pIn3;
  71065. for(ii=0; ii<r.nField; ii++){
  71066. assert( memIsValid(&r.aMem[ii]) );
  71067. ExpandBlob(&r.aMem[ii]);
  71068. #ifdef SQLITE_DEBUG
  71069. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  71070. #endif
  71071. }
  71072. pIdxKey = &r;
  71073. }else{
  71074. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  71075. pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  71076. );
  71077. if( pIdxKey==0 ) goto no_mem;
  71078. assert( pIn3->flags & MEM_Blob );
  71079. ExpandBlob(pIn3);
  71080. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  71081. }
  71082. pIdxKey->default_rc = 0;
  71083. takeJump = 0;
  71084. if( pOp->opcode==OP_NoConflict ){
  71085. /* For the OP_NoConflict opcode, take the jump if any of the
  71086. ** input fields are NULL, since any key with a NULL will not
  71087. ** conflict */
  71088. for(ii=0; ii<pIdxKey->nField; ii++){
  71089. if( pIdxKey->aMem[ii].flags & MEM_Null ){
  71090. takeJump = 1;
  71091. break;
  71092. }
  71093. }
  71094. }
  71095. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  71096. sqlite3DbFree(db, pFree);
  71097. if( rc!=SQLITE_OK ){
  71098. break;
  71099. }
  71100. pC->seekResult = res;
  71101. alreadyExists = (res==0);
  71102. pC->nullRow = 1-alreadyExists;
  71103. pC->deferredMoveto = 0;
  71104. pC->cacheStatus = CACHE_STALE;
  71105. if( pOp->opcode==OP_Found ){
  71106. VdbeBranchTaken(alreadyExists!=0,2);
  71107. if( alreadyExists ) goto jump_to_p2;
  71108. }else{
  71109. VdbeBranchTaken(takeJump||alreadyExists==0,2);
  71110. if( takeJump || !alreadyExists ) goto jump_to_p2;
  71111. }
  71112. break;
  71113. }
  71114. /* Opcode: NotExists P1 P2 P3 * *
  71115. ** Synopsis: intkey=r[P3]
  71116. **
  71117. ** P1 is the index of a cursor open on an SQL table btree (with integer
  71118. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  71119. ** rowid P3 then jump immediately to P2. If P1 does contain a record
  71120. ** with rowid P3 then leave the cursor pointing at that record and fall
  71121. ** through to the next instruction.
  71122. **
  71123. ** The OP_NotFound opcode performs the same operation on index btrees
  71124. ** (with arbitrary multi-value keys).
  71125. **
  71126. ** This opcode leaves the cursor in a state where it cannot be advanced
  71127. ** in either direction. In other words, the Next and Prev opcodes will
  71128. ** not work following this opcode.
  71129. **
  71130. ** See also: Found, NotFound, NoConflict
  71131. */
  71132. case OP_NotExists: { /* jump, in3 */
  71133. VdbeCursor *pC;
  71134. BtCursor *pCrsr;
  71135. int res;
  71136. u64 iKey;
  71137. pIn3 = &aMem[pOp->p3];
  71138. assert( pIn3->flags & MEM_Int );
  71139. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71140. pC = p->apCsr[pOp->p1];
  71141. assert( pC!=0 );
  71142. #ifdef SQLITE_DEBUG
  71143. pC->seekOp = 0;
  71144. #endif
  71145. assert( pC->isTable );
  71146. assert( pC->pseudoTableReg==0 );
  71147. pCrsr = pC->pCursor;
  71148. assert( pCrsr!=0 );
  71149. res = 0;
  71150. iKey = pIn3->u.i;
  71151. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  71152. pC->movetoTarget = iKey; /* Used by OP_Delete */
  71153. pC->nullRow = 0;
  71154. pC->cacheStatus = CACHE_STALE;
  71155. pC->deferredMoveto = 0;
  71156. VdbeBranchTaken(res!=0,2);
  71157. pC->seekResult = res;
  71158. if( res!=0 ) goto jump_to_p2;
  71159. break;
  71160. }
  71161. /* Opcode: Sequence P1 P2 * * *
  71162. ** Synopsis: r[P2]=cursor[P1].ctr++
  71163. **
  71164. ** Find the next available sequence number for cursor P1.
  71165. ** Write the sequence number into register P2.
  71166. ** The sequence number on the cursor is incremented after this
  71167. ** instruction.
  71168. */
  71169. case OP_Sequence: { /* out2 */
  71170. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71171. assert( p->apCsr[pOp->p1]!=0 );
  71172. pOut = out2Prerelease(p, pOp);
  71173. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  71174. break;
  71175. }
  71176. /* Opcode: NewRowid P1 P2 P3 * *
  71177. ** Synopsis: r[P2]=rowid
  71178. **
  71179. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  71180. ** The record number is not previously used as a key in the database
  71181. ** table that cursor P1 points to. The new record number is written
  71182. ** written to register P2.
  71183. **
  71184. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  71185. ** the largest previously generated record number. No new record numbers are
  71186. ** allowed to be less than this value. When this value reaches its maximum,
  71187. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  71188. ** generated record number. This P3 mechanism is used to help implement the
  71189. ** AUTOINCREMENT feature.
  71190. */
  71191. case OP_NewRowid: { /* out2 */
  71192. i64 v; /* The new rowid */
  71193. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  71194. int res; /* Result of an sqlite3BtreeLast() */
  71195. int cnt; /* Counter to limit the number of searches */
  71196. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  71197. VdbeFrame *pFrame; /* Root frame of VDBE */
  71198. v = 0;
  71199. res = 0;
  71200. pOut = out2Prerelease(p, pOp);
  71201. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71202. pC = p->apCsr[pOp->p1];
  71203. assert( pC!=0 );
  71204. assert( pC->pCursor!=0 );
  71205. {
  71206. /* The next rowid or record number (different terms for the same
  71207. ** thing) is obtained in a two-step algorithm.
  71208. **
  71209. ** First we attempt to find the largest existing rowid and add one
  71210. ** to that. But if the largest existing rowid is already the maximum
  71211. ** positive integer, we have to fall through to the second
  71212. ** probabilistic algorithm
  71213. **
  71214. ** The second algorithm is to select a rowid at random and see if
  71215. ** it already exists in the table. If it does not exist, we have
  71216. ** succeeded. If the random rowid does exist, we select a new one
  71217. ** and try again, up to 100 times.
  71218. */
  71219. assert( pC->isTable );
  71220. #ifdef SQLITE_32BIT_ROWID
  71221. # define MAX_ROWID 0x7fffffff
  71222. #else
  71223. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  71224. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  71225. ** to provide the constant while making all compilers happy.
  71226. */
  71227. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  71228. #endif
  71229. if( !pC->useRandomRowid ){
  71230. rc = sqlite3BtreeLast(pC->pCursor, &res);
  71231. if( rc!=SQLITE_OK ){
  71232. goto abort_due_to_error;
  71233. }
  71234. if( res ){
  71235. v = 1; /* IMP: R-61914-48074 */
  71236. }else{
  71237. assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
  71238. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  71239. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  71240. if( v>=MAX_ROWID ){
  71241. pC->useRandomRowid = 1;
  71242. }else{
  71243. v++; /* IMP: R-29538-34987 */
  71244. }
  71245. }
  71246. }
  71247. #ifndef SQLITE_OMIT_AUTOINCREMENT
  71248. if( pOp->p3 ){
  71249. /* Assert that P3 is a valid memory cell. */
  71250. assert( pOp->p3>0 );
  71251. if( p->pFrame ){
  71252. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  71253. /* Assert that P3 is a valid memory cell. */
  71254. assert( pOp->p3<=pFrame->nMem );
  71255. pMem = &pFrame->aMem[pOp->p3];
  71256. }else{
  71257. /* Assert that P3 is a valid memory cell. */
  71258. assert( pOp->p3<=(p->nMem-p->nCursor) );
  71259. pMem = &aMem[pOp->p3];
  71260. memAboutToChange(p, pMem);
  71261. }
  71262. assert( memIsValid(pMem) );
  71263. REGISTER_TRACE(pOp->p3, pMem);
  71264. sqlite3VdbeMemIntegerify(pMem);
  71265. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  71266. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  71267. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  71268. goto abort_due_to_error;
  71269. }
  71270. if( v<pMem->u.i+1 ){
  71271. v = pMem->u.i + 1;
  71272. }
  71273. pMem->u.i = v;
  71274. }
  71275. #endif
  71276. if( pC->useRandomRowid ){
  71277. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  71278. ** largest possible integer (9223372036854775807) then the database
  71279. ** engine starts picking positive candidate ROWIDs at random until
  71280. ** it finds one that is not previously used. */
  71281. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  71282. ** an AUTOINCREMENT table. */
  71283. cnt = 0;
  71284. do{
  71285. sqlite3_randomness(sizeof(v), &v);
  71286. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  71287. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
  71288. 0, &res))==SQLITE_OK)
  71289. && (res==0)
  71290. && (++cnt<100));
  71291. if( rc==SQLITE_OK && res==0 ){
  71292. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  71293. goto abort_due_to_error;
  71294. }
  71295. assert( v>0 ); /* EV: R-40812-03570 */
  71296. }
  71297. pC->deferredMoveto = 0;
  71298. pC->cacheStatus = CACHE_STALE;
  71299. }
  71300. pOut->u.i = v;
  71301. break;
  71302. }
  71303. /* Opcode: Insert P1 P2 P3 P4 P5
  71304. ** Synopsis: intkey=r[P3] data=r[P2]
  71305. **
  71306. ** Write an entry into the table of cursor P1. A new entry is
  71307. ** created if it doesn't already exist or the data for an existing
  71308. ** entry is overwritten. The data is the value MEM_Blob stored in register
  71309. ** number P2. The key is stored in register P3. The key must
  71310. ** be a MEM_Int.
  71311. **
  71312. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  71313. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  71314. ** then rowid is stored for subsequent return by the
  71315. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  71316. **
  71317. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  71318. ** the last seek operation (OP_NotExists) was a success, then this
  71319. ** operation will not attempt to find the appropriate row before doing
  71320. ** the insert but will instead overwrite the row that the cursor is
  71321. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  71322. ** has already positioned the cursor correctly. This is an optimization
  71323. ** that boosts performance by avoiding redundant seeks.
  71324. **
  71325. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  71326. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  71327. ** is part of an INSERT operation. The difference is only important to
  71328. ** the update hook.
  71329. **
  71330. ** Parameter P4 may point to a string containing the table-name, or
  71331. ** may be NULL. If it is not NULL, then the update-hook
  71332. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  71333. **
  71334. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  71335. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  71336. ** and register P2 becomes ephemeral. If the cursor is changed, the
  71337. ** value of register P2 will then change. Make sure this does not
  71338. ** cause any problems.)
  71339. **
  71340. ** This instruction only works on tables. The equivalent instruction
  71341. ** for indices is OP_IdxInsert.
  71342. */
  71343. /* Opcode: InsertInt P1 P2 P3 P4 P5
  71344. ** Synopsis: intkey=P3 data=r[P2]
  71345. **
  71346. ** This works exactly like OP_Insert except that the key is the
  71347. ** integer value P3, not the value of the integer stored in register P3.
  71348. */
  71349. case OP_Insert:
  71350. case OP_InsertInt: {
  71351. Mem *pData; /* MEM cell holding data for the record to be inserted */
  71352. Mem *pKey; /* MEM cell holding key for the record */
  71353. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  71354. VdbeCursor *pC; /* Cursor to table into which insert is written */
  71355. int nZero; /* Number of zero-bytes to append */
  71356. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  71357. const char *zDb; /* database name - used by the update hook */
  71358. const char *zTbl; /* Table name - used by the opdate hook */
  71359. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  71360. pData = &aMem[pOp->p2];
  71361. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71362. assert( memIsValid(pData) );
  71363. pC = p->apCsr[pOp->p1];
  71364. assert( pC!=0 );
  71365. assert( pC->pCursor!=0 );
  71366. assert( pC->pseudoTableReg==0 );
  71367. assert( pC->isTable );
  71368. REGISTER_TRACE(pOp->p2, pData);
  71369. if( pOp->opcode==OP_Insert ){
  71370. pKey = &aMem[pOp->p3];
  71371. assert( pKey->flags & MEM_Int );
  71372. assert( memIsValid(pKey) );
  71373. REGISTER_TRACE(pOp->p3, pKey);
  71374. iKey = pKey->u.i;
  71375. }else{
  71376. assert( pOp->opcode==OP_InsertInt );
  71377. iKey = pOp->p3;
  71378. }
  71379. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  71380. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
  71381. if( pData->flags & MEM_Null ){
  71382. pData->z = 0;
  71383. pData->n = 0;
  71384. }else{
  71385. assert( pData->flags & (MEM_Blob|MEM_Str) );
  71386. }
  71387. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  71388. if( pData->flags & MEM_Zero ){
  71389. nZero = pData->u.nZero;
  71390. }else{
  71391. nZero = 0;
  71392. }
  71393. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  71394. pData->z, pData->n, nZero,
  71395. (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  71396. );
  71397. pC->deferredMoveto = 0;
  71398. pC->cacheStatus = CACHE_STALE;
  71399. /* Invoke the update-hook if required. */
  71400. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  71401. zDb = db->aDb[pC->iDb].zName;
  71402. zTbl = pOp->p4.z;
  71403. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  71404. assert( pC->isTable );
  71405. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  71406. assert( pC->iDb>=0 );
  71407. }
  71408. break;
  71409. }
  71410. /* Opcode: Delete P1 P2 * P4 *
  71411. **
  71412. ** Delete the record at which the P1 cursor is currently pointing.
  71413. **
  71414. ** The cursor will be left pointing at either the next or the previous
  71415. ** record in the table. If it is left pointing at the next record, then
  71416. ** the next Next instruction will be a no-op. Hence it is OK to delete
  71417. ** a record from within a Next loop.
  71418. **
  71419. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  71420. ** incremented (otherwise not).
  71421. **
  71422. ** P1 must not be pseudo-table. It has to be a real table with
  71423. ** multiple rows.
  71424. **
  71425. ** If P4 is not NULL, then it is the name of the table that P1 is
  71426. ** pointing to. The update hook will be invoked, if it exists.
  71427. ** If P4 is not NULL then the P1 cursor must have been positioned
  71428. ** using OP_NotFound prior to invoking this opcode.
  71429. */
  71430. case OP_Delete: {
  71431. VdbeCursor *pC;
  71432. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71433. pC = p->apCsr[pOp->p1];
  71434. assert( pC!=0 );
  71435. assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  71436. assert( pC->deferredMoveto==0 );
  71437. #ifdef SQLITE_DEBUG
  71438. /* The seek operation that positioned the cursor prior to OP_Delete will
  71439. ** have also set the pC->movetoTarget field to the rowid of the row that
  71440. ** is being deleted */
  71441. if( pOp->p4.z && pC->isTable ){
  71442. i64 iKey = 0;
  71443. sqlite3BtreeKeySize(pC->pCursor, &iKey);
  71444. assert( pC->movetoTarget==iKey );
  71445. }
  71446. #endif
  71447. rc = sqlite3BtreeDelete(pC->pCursor);
  71448. pC->cacheStatus = CACHE_STALE;
  71449. /* Invoke the update-hook if required. */
  71450. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
  71451. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
  71452. db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
  71453. assert( pC->iDb>=0 );
  71454. }
  71455. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  71456. break;
  71457. }
  71458. /* Opcode: ResetCount * * * * *
  71459. **
  71460. ** The value of the change counter is copied to the database handle
  71461. ** change counter (returned by subsequent calls to sqlite3_changes()).
  71462. ** Then the VMs internal change counter resets to 0.
  71463. ** This is used by trigger programs.
  71464. */
  71465. case OP_ResetCount: {
  71466. sqlite3VdbeSetChanges(db, p->nChange);
  71467. p->nChange = 0;
  71468. break;
  71469. }
  71470. /* Opcode: SorterCompare P1 P2 P3 P4
  71471. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  71472. **
  71473. ** P1 is a sorter cursor. This instruction compares a prefix of the
  71474. ** record blob in register P3 against a prefix of the entry that
  71475. ** the sorter cursor currently points to. Only the first P4 fields
  71476. ** of r[P3] and the sorter record are compared.
  71477. **
  71478. ** If either P3 or the sorter contains a NULL in one of their significant
  71479. ** fields (not counting the P4 fields at the end which are ignored) then
  71480. ** the comparison is assumed to be equal.
  71481. **
  71482. ** Fall through to next instruction if the two records compare equal to
  71483. ** each other. Jump to P2 if they are different.
  71484. */
  71485. case OP_SorterCompare: {
  71486. VdbeCursor *pC;
  71487. int res;
  71488. int nKeyCol;
  71489. pC = p->apCsr[pOp->p1];
  71490. assert( isSorter(pC) );
  71491. assert( pOp->p4type==P4_INT32 );
  71492. pIn3 = &aMem[pOp->p3];
  71493. nKeyCol = pOp->p4.i;
  71494. res = 0;
  71495. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  71496. VdbeBranchTaken(res!=0,2);
  71497. if( res ) goto jump_to_p2;
  71498. break;
  71499. };
  71500. /* Opcode: SorterData P1 P2 P3 * *
  71501. ** Synopsis: r[P2]=data
  71502. **
  71503. ** Write into register P2 the current sorter data for sorter cursor P1.
  71504. ** Then clear the column header cache on cursor P3.
  71505. **
  71506. ** This opcode is normally use to move a record out of the sorter and into
  71507. ** a register that is the source for a pseudo-table cursor created using
  71508. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  71509. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  71510. ** us from having to issue a separate NullRow instruction to clear that cache.
  71511. */
  71512. case OP_SorterData: {
  71513. VdbeCursor *pC;
  71514. pOut = &aMem[pOp->p2];
  71515. pC = p->apCsr[pOp->p1];
  71516. assert( isSorter(pC) );
  71517. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  71518. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  71519. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71520. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  71521. break;
  71522. }
  71523. /* Opcode: RowData P1 P2 * * *
  71524. ** Synopsis: r[P2]=data
  71525. **
  71526. ** Write into register P2 the complete row data for cursor P1.
  71527. ** There is no interpretation of the data.
  71528. ** It is just copied onto the P2 register exactly as
  71529. ** it is found in the database file.
  71530. **
  71531. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  71532. ** of a real table, not a pseudo-table.
  71533. */
  71534. /* Opcode: RowKey P1 P2 * * *
  71535. ** Synopsis: r[P2]=key
  71536. **
  71537. ** Write into register P2 the complete row key for cursor P1.
  71538. ** There is no interpretation of the data.
  71539. ** The key is copied onto the P2 register exactly as
  71540. ** it is found in the database file.
  71541. **
  71542. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  71543. ** of a real table, not a pseudo-table.
  71544. */
  71545. case OP_RowKey:
  71546. case OP_RowData: {
  71547. VdbeCursor *pC;
  71548. BtCursor *pCrsr;
  71549. u32 n;
  71550. i64 n64;
  71551. pOut = &aMem[pOp->p2];
  71552. memAboutToChange(p, pOut);
  71553. /* Note that RowKey and RowData are really exactly the same instruction */
  71554. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71555. pC = p->apCsr[pOp->p1];
  71556. assert( isSorter(pC)==0 );
  71557. assert( pC->isTable || pOp->opcode!=OP_RowData );
  71558. assert( pC->isTable==0 || pOp->opcode==OP_RowData );
  71559. assert( pC!=0 );
  71560. assert( pC->nullRow==0 );
  71561. assert( pC->pseudoTableReg==0 );
  71562. assert( pC->pCursor!=0 );
  71563. pCrsr = pC->pCursor;
  71564. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  71565. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  71566. ** the cursor. If this where not the case, on of the following assert()s
  71567. ** would fail. Should this ever change (because of changes in the code
  71568. ** generator) then the fix would be to insert a call to
  71569. ** sqlite3VdbeCursorMoveto().
  71570. */
  71571. assert( pC->deferredMoveto==0 );
  71572. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  71573. #if 0 /* Not required due to the previous to assert() statements */
  71574. rc = sqlite3VdbeCursorMoveto(pC);
  71575. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  71576. #endif
  71577. if( pC->isTable==0 ){
  71578. assert( !pC->isTable );
  71579. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
  71580. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  71581. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  71582. goto too_big;
  71583. }
  71584. n = (u32)n64;
  71585. }else{
  71586. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
  71587. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  71588. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  71589. goto too_big;
  71590. }
  71591. }
  71592. testcase( n==0 );
  71593. if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
  71594. goto no_mem;
  71595. }
  71596. pOut->n = n;
  71597. MemSetTypeFlag(pOut, MEM_Blob);
  71598. if( pC->isTable==0 ){
  71599. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  71600. }else{
  71601. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  71602. }
  71603. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  71604. UPDATE_MAX_BLOBSIZE(pOut);
  71605. REGISTER_TRACE(pOp->p2, pOut);
  71606. break;
  71607. }
  71608. /* Opcode: Rowid P1 P2 * * *
  71609. ** Synopsis: r[P2]=rowid
  71610. **
  71611. ** Store in register P2 an integer which is the key of the table entry that
  71612. ** P1 is currently point to.
  71613. **
  71614. ** P1 can be either an ordinary table or a virtual table. There used to
  71615. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  71616. ** one opcode now works for both table types.
  71617. */
  71618. case OP_Rowid: { /* out2 */
  71619. VdbeCursor *pC;
  71620. i64 v;
  71621. sqlite3_vtab *pVtab;
  71622. const sqlite3_module *pModule;
  71623. pOut = out2Prerelease(p, pOp);
  71624. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71625. pC = p->apCsr[pOp->p1];
  71626. assert( pC!=0 );
  71627. assert( pC->pseudoTableReg==0 || pC->nullRow );
  71628. if( pC->nullRow ){
  71629. pOut->flags = MEM_Null;
  71630. break;
  71631. }else if( pC->deferredMoveto ){
  71632. v = pC->movetoTarget;
  71633. #ifndef SQLITE_OMIT_VIRTUALTABLE
  71634. }else if( pC->pVtabCursor ){
  71635. pVtab = pC->pVtabCursor->pVtab;
  71636. pModule = pVtab->pModule;
  71637. assert( pModule->xRowid );
  71638. rc = pModule->xRowid(pC->pVtabCursor, &v);
  71639. sqlite3VtabImportErrmsg(p, pVtab);
  71640. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  71641. }else{
  71642. assert( pC->pCursor!=0 );
  71643. rc = sqlite3VdbeCursorRestore(pC);
  71644. if( rc ) goto abort_due_to_error;
  71645. if( pC->nullRow ){
  71646. pOut->flags = MEM_Null;
  71647. break;
  71648. }
  71649. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  71650. assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
  71651. }
  71652. pOut->u.i = v;
  71653. break;
  71654. }
  71655. /* Opcode: NullRow P1 * * * *
  71656. **
  71657. ** Move the cursor P1 to a null row. Any OP_Column operations
  71658. ** that occur while the cursor is on the null row will always
  71659. ** write a NULL.
  71660. */
  71661. case OP_NullRow: {
  71662. VdbeCursor *pC;
  71663. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71664. pC = p->apCsr[pOp->p1];
  71665. assert( pC!=0 );
  71666. pC->nullRow = 1;
  71667. pC->cacheStatus = CACHE_STALE;
  71668. if( pC->pCursor ){
  71669. sqlite3BtreeClearCursor(pC->pCursor);
  71670. }
  71671. break;
  71672. }
  71673. /* Opcode: Last P1 P2 P3 * *
  71674. **
  71675. ** The next use of the Rowid or Column or Prev instruction for P1
  71676. ** will refer to the last entry in the database table or index.
  71677. ** If the table or index is empty and P2>0, then jump immediately to P2.
  71678. ** If P2 is 0 or if the table or index is not empty, fall through
  71679. ** to the following instruction.
  71680. **
  71681. ** This opcode leaves the cursor configured to move in reverse order,
  71682. ** from the end toward the beginning. In other words, the cursor is
  71683. ** configured to use Prev, not Next.
  71684. */
  71685. case OP_Last: { /* jump */
  71686. VdbeCursor *pC;
  71687. BtCursor *pCrsr;
  71688. int res;
  71689. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71690. pC = p->apCsr[pOp->p1];
  71691. assert( pC!=0 );
  71692. pCrsr = pC->pCursor;
  71693. res = 0;
  71694. assert( pCrsr!=0 );
  71695. rc = sqlite3BtreeLast(pCrsr, &res);
  71696. pC->nullRow = (u8)res;
  71697. pC->deferredMoveto = 0;
  71698. pC->cacheStatus = CACHE_STALE;
  71699. pC->seekResult = pOp->p3;
  71700. #ifdef SQLITE_DEBUG
  71701. pC->seekOp = OP_Last;
  71702. #endif
  71703. if( pOp->p2>0 ){
  71704. VdbeBranchTaken(res!=0,2);
  71705. if( res ) goto jump_to_p2;
  71706. }
  71707. break;
  71708. }
  71709. /* Opcode: Sort P1 P2 * * *
  71710. **
  71711. ** This opcode does exactly the same thing as OP_Rewind except that
  71712. ** it increments an undocumented global variable used for testing.
  71713. **
  71714. ** Sorting is accomplished by writing records into a sorting index,
  71715. ** then rewinding that index and playing it back from beginning to
  71716. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  71717. ** rewinding so that the global variable will be incremented and
  71718. ** regression tests can determine whether or not the optimizer is
  71719. ** correctly optimizing out sorts.
  71720. */
  71721. case OP_SorterSort: /* jump */
  71722. case OP_Sort: { /* jump */
  71723. #ifdef SQLITE_TEST
  71724. sqlite3_sort_count++;
  71725. sqlite3_search_count--;
  71726. #endif
  71727. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  71728. /* Fall through into OP_Rewind */
  71729. }
  71730. /* Opcode: Rewind P1 P2 * * *
  71731. **
  71732. ** The next use of the Rowid or Column or Next instruction for P1
  71733. ** will refer to the first entry in the database table or index.
  71734. ** If the table or index is empty, jump immediately to P2.
  71735. ** If the table or index is not empty, fall through to the following
  71736. ** instruction.
  71737. **
  71738. ** This opcode leaves the cursor configured to move in forward order,
  71739. ** from the beginning toward the end. In other words, the cursor is
  71740. ** configured to use Next, not Prev.
  71741. */
  71742. case OP_Rewind: { /* jump */
  71743. VdbeCursor *pC;
  71744. BtCursor *pCrsr;
  71745. int res;
  71746. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71747. pC = p->apCsr[pOp->p1];
  71748. assert( pC!=0 );
  71749. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  71750. res = 1;
  71751. #ifdef SQLITE_DEBUG
  71752. pC->seekOp = OP_Rewind;
  71753. #endif
  71754. if( isSorter(pC) ){
  71755. rc = sqlite3VdbeSorterRewind(pC, &res);
  71756. }else{
  71757. pCrsr = pC->pCursor;
  71758. assert( pCrsr );
  71759. rc = sqlite3BtreeFirst(pCrsr, &res);
  71760. pC->deferredMoveto = 0;
  71761. pC->cacheStatus = CACHE_STALE;
  71762. }
  71763. pC->nullRow = (u8)res;
  71764. assert( pOp->p2>0 && pOp->p2<p->nOp );
  71765. VdbeBranchTaken(res!=0,2);
  71766. if( res ) goto jump_to_p2;
  71767. break;
  71768. }
  71769. /* Opcode: Next P1 P2 P3 P4 P5
  71770. **
  71771. ** Advance cursor P1 so that it points to the next key/data pair in its
  71772. ** table or index. If there are no more key/value pairs then fall through
  71773. ** to the following instruction. But if the cursor advance was successful,
  71774. ** jump immediately to P2.
  71775. **
  71776. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  71777. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  71778. ** to follow SeekLT, SeekLE, or OP_Last.
  71779. **
  71780. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  71781. ** been opened prior to this opcode or the program will segfault.
  71782. **
  71783. ** The P3 value is a hint to the btree implementation. If P3==1, that
  71784. ** means P1 is an SQL index and that this instruction could have been
  71785. ** omitted if that index had been unique. P3 is usually 0. P3 is
  71786. ** always either 0 or 1.
  71787. **
  71788. ** P4 is always of type P4_ADVANCE. The function pointer points to
  71789. ** sqlite3BtreeNext().
  71790. **
  71791. ** If P5 is positive and the jump is taken, then event counter
  71792. ** number P5-1 in the prepared statement is incremented.
  71793. **
  71794. ** See also: Prev, NextIfOpen
  71795. */
  71796. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  71797. **
  71798. ** This opcode works just like Next except that if cursor P1 is not
  71799. ** open it behaves a no-op.
  71800. */
  71801. /* Opcode: Prev P1 P2 P3 P4 P5
  71802. **
  71803. ** Back up cursor P1 so that it points to the previous key/data pair in its
  71804. ** table or index. If there is no previous key/value pairs then fall through
  71805. ** to the following instruction. But if the cursor backup was successful,
  71806. ** jump immediately to P2.
  71807. **
  71808. **
  71809. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  71810. ** OP_Last opcode used to position the cursor. Prev is not allowed
  71811. ** to follow SeekGT, SeekGE, or OP_Rewind.
  71812. **
  71813. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  71814. ** not open then the behavior is undefined.
  71815. **
  71816. ** The P3 value is a hint to the btree implementation. If P3==1, that
  71817. ** means P1 is an SQL index and that this instruction could have been
  71818. ** omitted if that index had been unique. P3 is usually 0. P3 is
  71819. ** always either 0 or 1.
  71820. **
  71821. ** P4 is always of type P4_ADVANCE. The function pointer points to
  71822. ** sqlite3BtreePrevious().
  71823. **
  71824. ** If P5 is positive and the jump is taken, then event counter
  71825. ** number P5-1 in the prepared statement is incremented.
  71826. */
  71827. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  71828. **
  71829. ** This opcode works just like Prev except that if cursor P1 is not
  71830. ** open it behaves a no-op.
  71831. */
  71832. case OP_SorterNext: { /* jump */
  71833. VdbeCursor *pC;
  71834. int res;
  71835. pC = p->apCsr[pOp->p1];
  71836. assert( isSorter(pC) );
  71837. res = 0;
  71838. rc = sqlite3VdbeSorterNext(db, pC, &res);
  71839. goto next_tail;
  71840. case OP_PrevIfOpen: /* jump */
  71841. case OP_NextIfOpen: /* jump */
  71842. if( p->apCsr[pOp->p1]==0 ) break;
  71843. /* Fall through */
  71844. case OP_Prev: /* jump */
  71845. case OP_Next: /* jump */
  71846. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71847. assert( pOp->p5<ArraySize(p->aCounter) );
  71848. pC = p->apCsr[pOp->p1];
  71849. res = pOp->p3;
  71850. assert( pC!=0 );
  71851. assert( pC->deferredMoveto==0 );
  71852. assert( pC->pCursor );
  71853. assert( res==0 || (res==1 && pC->isTable==0) );
  71854. testcase( res==1 );
  71855. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  71856. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  71857. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  71858. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  71859. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  71860. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  71861. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  71862. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  71863. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  71864. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  71865. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  71866. || pC->seekOp==OP_Last );
  71867. rc = pOp->p4.xAdvance(pC->pCursor, &res);
  71868. next_tail:
  71869. pC->cacheStatus = CACHE_STALE;
  71870. VdbeBranchTaken(res==0,2);
  71871. if( res==0 ){
  71872. pC->nullRow = 0;
  71873. p->aCounter[pOp->p5]++;
  71874. #ifdef SQLITE_TEST
  71875. sqlite3_search_count++;
  71876. #endif
  71877. goto jump_to_p2_and_check_for_interrupt;
  71878. }else{
  71879. pC->nullRow = 1;
  71880. }
  71881. goto check_for_interrupt;
  71882. }
  71883. /* Opcode: IdxInsert P1 P2 P3 * P5
  71884. ** Synopsis: key=r[P2]
  71885. **
  71886. ** Register P2 holds an SQL index key made using the
  71887. ** MakeRecord instructions. This opcode writes that key
  71888. ** into the index P1. Data for the entry is nil.
  71889. **
  71890. ** P3 is a flag that provides a hint to the b-tree layer that this
  71891. ** insert is likely to be an append.
  71892. **
  71893. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  71894. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  71895. ** then the change counter is unchanged.
  71896. **
  71897. ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
  71898. ** just done a seek to the spot where the new entry is to be inserted.
  71899. ** This flag avoids doing an extra seek.
  71900. **
  71901. ** This instruction only works for indices. The equivalent instruction
  71902. ** for tables is OP_Insert.
  71903. */
  71904. case OP_SorterInsert: /* in2 */
  71905. case OP_IdxInsert: { /* in2 */
  71906. VdbeCursor *pC;
  71907. int nKey;
  71908. const char *zKey;
  71909. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71910. pC = p->apCsr[pOp->p1];
  71911. assert( pC!=0 );
  71912. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  71913. pIn2 = &aMem[pOp->p2];
  71914. assert( pIn2->flags & MEM_Blob );
  71915. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  71916. assert( pC->pCursor!=0 );
  71917. assert( pC->isTable==0 );
  71918. rc = ExpandBlob(pIn2);
  71919. if( rc==SQLITE_OK ){
  71920. if( pOp->opcode==OP_SorterInsert ){
  71921. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  71922. }else{
  71923. nKey = pIn2->n;
  71924. zKey = pIn2->z;
  71925. rc = sqlite3BtreeInsert(pC->pCursor, zKey, nKey, "", 0, 0, pOp->p3,
  71926. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  71927. );
  71928. assert( pC->deferredMoveto==0 );
  71929. pC->cacheStatus = CACHE_STALE;
  71930. }
  71931. }
  71932. break;
  71933. }
  71934. /* Opcode: IdxDelete P1 P2 P3 * *
  71935. ** Synopsis: key=r[P2@P3]
  71936. **
  71937. ** The content of P3 registers starting at register P2 form
  71938. ** an unpacked index key. This opcode removes that entry from the
  71939. ** index opened by cursor P1.
  71940. */
  71941. case OP_IdxDelete: {
  71942. VdbeCursor *pC;
  71943. BtCursor *pCrsr;
  71944. int res;
  71945. UnpackedRecord r;
  71946. assert( pOp->p3>0 );
  71947. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  71948. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71949. pC = p->apCsr[pOp->p1];
  71950. assert( pC!=0 );
  71951. pCrsr = pC->pCursor;
  71952. assert( pCrsr!=0 );
  71953. assert( pOp->p5==0 );
  71954. r.pKeyInfo = pC->pKeyInfo;
  71955. r.nField = (u16)pOp->p3;
  71956. r.default_rc = 0;
  71957. r.aMem = &aMem[pOp->p2];
  71958. #ifdef SQLITE_DEBUG
  71959. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  71960. #endif
  71961. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  71962. if( rc==SQLITE_OK && res==0 ){
  71963. rc = sqlite3BtreeDelete(pCrsr);
  71964. }
  71965. assert( pC->deferredMoveto==0 );
  71966. pC->cacheStatus = CACHE_STALE;
  71967. break;
  71968. }
  71969. /* Opcode: IdxRowid P1 P2 * * *
  71970. ** Synopsis: r[P2]=rowid
  71971. **
  71972. ** Write into register P2 an integer which is the last entry in the record at
  71973. ** the end of the index key pointed to by cursor P1. This integer should be
  71974. ** the rowid of the table entry to which this index entry points.
  71975. **
  71976. ** See also: Rowid, MakeRecord.
  71977. */
  71978. case OP_IdxRowid: { /* out2 */
  71979. BtCursor *pCrsr;
  71980. VdbeCursor *pC;
  71981. i64 rowid;
  71982. pOut = out2Prerelease(p, pOp);
  71983. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  71984. pC = p->apCsr[pOp->p1];
  71985. assert( pC!=0 );
  71986. pCrsr = pC->pCursor;
  71987. assert( pCrsr!=0 );
  71988. pOut->flags = MEM_Null;
  71989. assert( pC->isTable==0 );
  71990. assert( pC->deferredMoveto==0 );
  71991. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  71992. ** out from under the cursor. That will never happend for an IdxRowid
  71993. ** opcode, hence the NEVER() arround the check of the return value.
  71994. */
  71995. rc = sqlite3VdbeCursorRestore(pC);
  71996. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  71997. if( !pC->nullRow ){
  71998. rowid = 0; /* Not needed. Only used to silence a warning. */
  71999. rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
  72000. if( rc!=SQLITE_OK ){
  72001. goto abort_due_to_error;
  72002. }
  72003. pOut->u.i = rowid;
  72004. pOut->flags = MEM_Int;
  72005. }
  72006. break;
  72007. }
  72008. /* Opcode: IdxGE P1 P2 P3 P4 P5
  72009. ** Synopsis: key=r[P3@P4]
  72010. **
  72011. ** The P4 register values beginning with P3 form an unpacked index
  72012. ** key that omits the PRIMARY KEY. Compare this key value against the index
  72013. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  72014. ** fields at the end.
  72015. **
  72016. ** If the P1 index entry is greater than or equal to the key value
  72017. ** then jump to P2. Otherwise fall through to the next instruction.
  72018. */
  72019. /* Opcode: IdxGT P1 P2 P3 P4 P5
  72020. ** Synopsis: key=r[P3@P4]
  72021. **
  72022. ** The P4 register values beginning with P3 form an unpacked index
  72023. ** key that omits the PRIMARY KEY. Compare this key value against the index
  72024. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  72025. ** fields at the end.
  72026. **
  72027. ** If the P1 index entry is greater than the key value
  72028. ** then jump to P2. Otherwise fall through to the next instruction.
  72029. */
  72030. /* Opcode: IdxLT P1 P2 P3 P4 P5
  72031. ** Synopsis: key=r[P3@P4]
  72032. **
  72033. ** The P4 register values beginning with P3 form an unpacked index
  72034. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  72035. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  72036. ** ROWID on the P1 index.
  72037. **
  72038. ** If the P1 index entry is less than the key value then jump to P2.
  72039. ** Otherwise fall through to the next instruction.
  72040. */
  72041. /* Opcode: IdxLE P1 P2 P3 P4 P5
  72042. ** Synopsis: key=r[P3@P4]
  72043. **
  72044. ** The P4 register values beginning with P3 form an unpacked index
  72045. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  72046. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  72047. ** ROWID on the P1 index.
  72048. **
  72049. ** If the P1 index entry is less than or equal to the key value then jump
  72050. ** to P2. Otherwise fall through to the next instruction.
  72051. */
  72052. case OP_IdxLE: /* jump */
  72053. case OP_IdxGT: /* jump */
  72054. case OP_IdxLT: /* jump */
  72055. case OP_IdxGE: { /* jump */
  72056. VdbeCursor *pC;
  72057. int res;
  72058. UnpackedRecord r;
  72059. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72060. pC = p->apCsr[pOp->p1];
  72061. assert( pC!=0 );
  72062. assert( pC->isOrdered );
  72063. assert( pC->pCursor!=0);
  72064. assert( pC->deferredMoveto==0 );
  72065. assert( pOp->p5==0 || pOp->p5==1 );
  72066. assert( pOp->p4type==P4_INT32 );
  72067. r.pKeyInfo = pC->pKeyInfo;
  72068. r.nField = (u16)pOp->p4.i;
  72069. if( pOp->opcode<OP_IdxLT ){
  72070. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  72071. r.default_rc = -1;
  72072. }else{
  72073. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  72074. r.default_rc = 0;
  72075. }
  72076. r.aMem = &aMem[pOp->p3];
  72077. #ifdef SQLITE_DEBUG
  72078. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  72079. #endif
  72080. res = 0; /* Not needed. Only used to silence a warning. */
  72081. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  72082. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  72083. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  72084. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  72085. res = -res;
  72086. }else{
  72087. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  72088. res++;
  72089. }
  72090. VdbeBranchTaken(res>0,2);
  72091. if( res>0 ) goto jump_to_p2;
  72092. break;
  72093. }
  72094. /* Opcode: Destroy P1 P2 P3 * *
  72095. **
  72096. ** Delete an entire database table or index whose root page in the database
  72097. ** file is given by P1.
  72098. **
  72099. ** The table being destroyed is in the main database file if P3==0. If
  72100. ** P3==1 then the table to be clear is in the auxiliary database file
  72101. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  72102. **
  72103. ** If AUTOVACUUM is enabled then it is possible that another root page
  72104. ** might be moved into the newly deleted root page in order to keep all
  72105. ** root pages contiguous at the beginning of the database. The former
  72106. ** value of the root page that moved - its value before the move occurred -
  72107. ** is stored in register P2. If no page
  72108. ** movement was required (because the table being dropped was already
  72109. ** the last one in the database) then a zero is stored in register P2.
  72110. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  72111. **
  72112. ** See also: Clear
  72113. */
  72114. case OP_Destroy: { /* out2 */
  72115. int iMoved;
  72116. int iDb;
  72117. assert( p->readOnly==0 );
  72118. pOut = out2Prerelease(p, pOp);
  72119. pOut->flags = MEM_Null;
  72120. if( db->nVdbeRead > db->nVDestroy+1 ){
  72121. rc = SQLITE_LOCKED;
  72122. p->errorAction = OE_Abort;
  72123. }else{
  72124. iDb = pOp->p3;
  72125. assert( DbMaskTest(p->btreeMask, iDb) );
  72126. iMoved = 0; /* Not needed. Only to silence a warning. */
  72127. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  72128. pOut->flags = MEM_Int;
  72129. pOut->u.i = iMoved;
  72130. #ifndef SQLITE_OMIT_AUTOVACUUM
  72131. if( rc==SQLITE_OK && iMoved!=0 ){
  72132. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  72133. /* All OP_Destroy operations occur on the same btree */
  72134. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  72135. resetSchemaOnFault = iDb+1;
  72136. }
  72137. #endif
  72138. }
  72139. break;
  72140. }
  72141. /* Opcode: Clear P1 P2 P3
  72142. **
  72143. ** Delete all contents of the database table or index whose root page
  72144. ** in the database file is given by P1. But, unlike Destroy, do not
  72145. ** remove the table or index from the database file.
  72146. **
  72147. ** The table being clear is in the main database file if P2==0. If
  72148. ** P2==1 then the table to be clear is in the auxiliary database file
  72149. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  72150. **
  72151. ** If the P3 value is non-zero, then the table referred to must be an
  72152. ** intkey table (an SQL table, not an index). In this case the row change
  72153. ** count is incremented by the number of rows in the table being cleared.
  72154. ** If P3 is greater than zero, then the value stored in register P3 is
  72155. ** also incremented by the number of rows in the table being cleared.
  72156. **
  72157. ** See also: Destroy
  72158. */
  72159. case OP_Clear: {
  72160. int nChange;
  72161. nChange = 0;
  72162. assert( p->readOnly==0 );
  72163. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  72164. rc = sqlite3BtreeClearTable(
  72165. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  72166. );
  72167. if( pOp->p3 ){
  72168. p->nChange += nChange;
  72169. if( pOp->p3>0 ){
  72170. assert( memIsValid(&aMem[pOp->p3]) );
  72171. memAboutToChange(p, &aMem[pOp->p3]);
  72172. aMem[pOp->p3].u.i += nChange;
  72173. }
  72174. }
  72175. break;
  72176. }
  72177. /* Opcode: ResetSorter P1 * * * *
  72178. **
  72179. ** Delete all contents from the ephemeral table or sorter
  72180. ** that is open on cursor P1.
  72181. **
  72182. ** This opcode only works for cursors used for sorting and
  72183. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  72184. */
  72185. case OP_ResetSorter: {
  72186. VdbeCursor *pC;
  72187. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  72188. pC = p->apCsr[pOp->p1];
  72189. assert( pC!=0 );
  72190. if( pC->pSorter ){
  72191. sqlite3VdbeSorterReset(db, pC->pSorter);
  72192. }else{
  72193. assert( pC->isEphemeral );
  72194. rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
  72195. }
  72196. break;
  72197. }
  72198. /* Opcode: CreateTable P1 P2 * * *
  72199. ** Synopsis: r[P2]=root iDb=P1
  72200. **
  72201. ** Allocate a new table in the main database file if P1==0 or in the
  72202. ** auxiliary database file if P1==1 or in an attached database if
  72203. ** P1>1. Write the root page number of the new table into
  72204. ** register P2
  72205. **
  72206. ** The difference between a table and an index is this: A table must
  72207. ** have a 4-byte integer key and can have arbitrary data. An index
  72208. ** has an arbitrary key but no data.
  72209. **
  72210. ** See also: CreateIndex
  72211. */
  72212. /* Opcode: CreateIndex P1 P2 * * *
  72213. ** Synopsis: r[P2]=root iDb=P1
  72214. **
  72215. ** Allocate a new index in the main database file if P1==0 or in the
  72216. ** auxiliary database file if P1==1 or in an attached database if
  72217. ** P1>1. Write the root page number of the new table into
  72218. ** register P2.
  72219. **
  72220. ** See documentation on OP_CreateTable for additional information.
  72221. */
  72222. case OP_CreateIndex: /* out2 */
  72223. case OP_CreateTable: { /* out2 */
  72224. int pgno;
  72225. int flags;
  72226. Db *pDb;
  72227. pOut = out2Prerelease(p, pOp);
  72228. pgno = 0;
  72229. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  72230. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  72231. assert( p->readOnly==0 );
  72232. pDb = &db->aDb[pOp->p1];
  72233. assert( pDb->pBt!=0 );
  72234. if( pOp->opcode==OP_CreateTable ){
  72235. /* flags = BTREE_INTKEY; */
  72236. flags = BTREE_INTKEY;
  72237. }else{
  72238. flags = BTREE_BLOBKEY;
  72239. }
  72240. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  72241. pOut->u.i = pgno;
  72242. break;
  72243. }
  72244. /* Opcode: ParseSchema P1 * * P4 *
  72245. **
  72246. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  72247. ** that match the WHERE clause P4.
  72248. **
  72249. ** This opcode invokes the parser to create a new virtual machine,
  72250. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  72251. */
  72252. case OP_ParseSchema: {
  72253. int iDb;
  72254. const char *zMaster;
  72255. char *zSql;
  72256. InitData initData;
  72257. /* Any prepared statement that invokes this opcode will hold mutexes
  72258. ** on every btree. This is a prerequisite for invoking
  72259. ** sqlite3InitCallback().
  72260. */
  72261. #ifdef SQLITE_DEBUG
  72262. for(iDb=0; iDb<db->nDb; iDb++){
  72263. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  72264. }
  72265. #endif
  72266. iDb = pOp->p1;
  72267. assert( iDb>=0 && iDb<db->nDb );
  72268. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  72269. /* Used to be a conditional */ {
  72270. zMaster = SCHEMA_TABLE(iDb);
  72271. initData.db = db;
  72272. initData.iDb = pOp->p1;
  72273. initData.pzErrMsg = &p->zErrMsg;
  72274. zSql = sqlite3MPrintf(db,
  72275. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  72276. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  72277. if( zSql==0 ){
  72278. rc = SQLITE_NOMEM;
  72279. }else{
  72280. assert( db->init.busy==0 );
  72281. db->init.busy = 1;
  72282. initData.rc = SQLITE_OK;
  72283. assert( !db->mallocFailed );
  72284. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  72285. if( rc==SQLITE_OK ) rc = initData.rc;
  72286. sqlite3DbFree(db, zSql);
  72287. db->init.busy = 0;
  72288. }
  72289. }
  72290. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  72291. if( rc==SQLITE_NOMEM ){
  72292. goto no_mem;
  72293. }
  72294. break;
  72295. }
  72296. #if !defined(SQLITE_OMIT_ANALYZE)
  72297. /* Opcode: LoadAnalysis P1 * * * *
  72298. **
  72299. ** Read the sqlite_stat1 table for database P1 and load the content
  72300. ** of that table into the internal index hash table. This will cause
  72301. ** the analysis to be used when preparing all subsequent queries.
  72302. */
  72303. case OP_LoadAnalysis: {
  72304. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  72305. rc = sqlite3AnalysisLoad(db, pOp->p1);
  72306. break;
  72307. }
  72308. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  72309. /* Opcode: DropTable P1 * * P4 *
  72310. **
  72311. ** Remove the internal (in-memory) data structures that describe
  72312. ** the table named P4 in database P1. This is called after a table
  72313. ** is dropped from disk (using the Destroy opcode) in order to keep
  72314. ** the internal representation of the
  72315. ** schema consistent with what is on disk.
  72316. */
  72317. case OP_DropTable: {
  72318. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  72319. break;
  72320. }
  72321. /* Opcode: DropIndex P1 * * P4 *
  72322. **
  72323. ** Remove the internal (in-memory) data structures that describe
  72324. ** the index named P4 in database P1. This is called after an index
  72325. ** is dropped from disk (using the Destroy opcode)
  72326. ** in order to keep the internal representation of the
  72327. ** schema consistent with what is on disk.
  72328. */
  72329. case OP_DropIndex: {
  72330. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  72331. break;
  72332. }
  72333. /* Opcode: DropTrigger P1 * * P4 *
  72334. **
  72335. ** Remove the internal (in-memory) data structures that describe
  72336. ** the trigger named P4 in database P1. This is called after a trigger
  72337. ** is dropped from disk (using the Destroy opcode) in order to keep
  72338. ** the internal representation of the
  72339. ** schema consistent with what is on disk.
  72340. */
  72341. case OP_DropTrigger: {
  72342. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  72343. break;
  72344. }
  72345. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  72346. /* Opcode: IntegrityCk P1 P2 P3 * P5
  72347. **
  72348. ** Do an analysis of the currently open database. Store in
  72349. ** register P1 the text of an error message describing any problems.
  72350. ** If no problems are found, store a NULL in register P1.
  72351. **
  72352. ** The register P3 contains the maximum number of allowed errors.
  72353. ** At most reg(P3) errors will be reported.
  72354. ** In other words, the analysis stops as soon as reg(P1) errors are
  72355. ** seen. Reg(P1) is updated with the number of errors remaining.
  72356. **
  72357. ** The root page numbers of all tables in the database are integer
  72358. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  72359. ** total.
  72360. **
  72361. ** If P5 is not zero, the check is done on the auxiliary database
  72362. ** file, not the main database file.
  72363. **
  72364. ** This opcode is used to implement the integrity_check pragma.
  72365. */
  72366. case OP_IntegrityCk: {
  72367. int nRoot; /* Number of tables to check. (Number of root pages.) */
  72368. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  72369. int j; /* Loop counter */
  72370. int nErr; /* Number of errors reported */
  72371. char *z; /* Text of the error report */
  72372. Mem *pnErr; /* Register keeping track of errors remaining */
  72373. assert( p->bIsReader );
  72374. nRoot = pOp->p2;
  72375. assert( nRoot>0 );
  72376. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  72377. if( aRoot==0 ) goto no_mem;
  72378. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  72379. pnErr = &aMem[pOp->p3];
  72380. assert( (pnErr->flags & MEM_Int)!=0 );
  72381. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  72382. pIn1 = &aMem[pOp->p1];
  72383. for(j=0; j<nRoot; j++){
  72384. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  72385. }
  72386. aRoot[j] = 0;
  72387. assert( pOp->p5<db->nDb );
  72388. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  72389. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  72390. (int)pnErr->u.i, &nErr);
  72391. sqlite3DbFree(db, aRoot);
  72392. pnErr->u.i -= nErr;
  72393. sqlite3VdbeMemSetNull(pIn1);
  72394. if( nErr==0 ){
  72395. assert( z==0 );
  72396. }else if( z==0 ){
  72397. goto no_mem;
  72398. }else{
  72399. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  72400. }
  72401. UPDATE_MAX_BLOBSIZE(pIn1);
  72402. sqlite3VdbeChangeEncoding(pIn1, encoding);
  72403. break;
  72404. }
  72405. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  72406. /* Opcode: RowSetAdd P1 P2 * * *
  72407. ** Synopsis: rowset(P1)=r[P2]
  72408. **
  72409. ** Insert the integer value held by register P2 into a boolean index
  72410. ** held in register P1.
  72411. **
  72412. ** An assertion fails if P2 is not an integer.
  72413. */
  72414. case OP_RowSetAdd: { /* in1, in2 */
  72415. pIn1 = &aMem[pOp->p1];
  72416. pIn2 = &aMem[pOp->p2];
  72417. assert( (pIn2->flags & MEM_Int)!=0 );
  72418. if( (pIn1->flags & MEM_RowSet)==0 ){
  72419. sqlite3VdbeMemSetRowSet(pIn1);
  72420. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  72421. }
  72422. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  72423. break;
  72424. }
  72425. /* Opcode: RowSetRead P1 P2 P3 * *
  72426. ** Synopsis: r[P3]=rowset(P1)
  72427. **
  72428. ** Extract the smallest value from boolean index P1 and put that value into
  72429. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  72430. ** unchanged and jump to instruction P2.
  72431. */
  72432. case OP_RowSetRead: { /* jump, in1, out3 */
  72433. i64 val;
  72434. pIn1 = &aMem[pOp->p1];
  72435. if( (pIn1->flags & MEM_RowSet)==0
  72436. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  72437. ){
  72438. /* The boolean index is empty */
  72439. sqlite3VdbeMemSetNull(pIn1);
  72440. VdbeBranchTaken(1,2);
  72441. goto jump_to_p2_and_check_for_interrupt;
  72442. }else{
  72443. /* A value was pulled from the index */
  72444. VdbeBranchTaken(0,2);
  72445. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  72446. }
  72447. goto check_for_interrupt;
  72448. }
  72449. /* Opcode: RowSetTest P1 P2 P3 P4
  72450. ** Synopsis: if r[P3] in rowset(P1) goto P2
  72451. **
  72452. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  72453. ** contains a RowSet object and that RowSet object contains
  72454. ** the value held in P3, jump to register P2. Otherwise, insert the
  72455. ** integer in P3 into the RowSet and continue on to the
  72456. ** next opcode.
  72457. **
  72458. ** The RowSet object is optimized for the case where successive sets
  72459. ** of integers, where each set contains no duplicates. Each set
  72460. ** of values is identified by a unique P4 value. The first set
  72461. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  72462. ** non-negative. For non-negative values of P4 only the lower 4
  72463. ** bits are significant.
  72464. **
  72465. ** This allows optimizations: (a) when P4==0 there is no need to test
  72466. ** the rowset object for P3, as it is guaranteed not to contain it,
  72467. ** (b) when P4==-1 there is no need to insert the value, as it will
  72468. ** never be tested for, and (c) when a value that is part of set X is
  72469. ** inserted, there is no need to search to see if the same value was
  72470. ** previously inserted as part of set X (only if it was previously
  72471. ** inserted as part of some other set).
  72472. */
  72473. case OP_RowSetTest: { /* jump, in1, in3 */
  72474. int iSet;
  72475. int exists;
  72476. pIn1 = &aMem[pOp->p1];
  72477. pIn3 = &aMem[pOp->p3];
  72478. iSet = pOp->p4.i;
  72479. assert( pIn3->flags&MEM_Int );
  72480. /* If there is anything other than a rowset object in memory cell P1,
  72481. ** delete it now and initialize P1 with an empty rowset
  72482. */
  72483. if( (pIn1->flags & MEM_RowSet)==0 ){
  72484. sqlite3VdbeMemSetRowSet(pIn1);
  72485. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  72486. }
  72487. assert( pOp->p4type==P4_INT32 );
  72488. assert( iSet==-1 || iSet>=0 );
  72489. if( iSet ){
  72490. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  72491. VdbeBranchTaken(exists!=0,2);
  72492. if( exists ) goto jump_to_p2;
  72493. }
  72494. if( iSet>=0 ){
  72495. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  72496. }
  72497. break;
  72498. }
  72499. #ifndef SQLITE_OMIT_TRIGGER
  72500. /* Opcode: Program P1 P2 P3 P4 P5
  72501. **
  72502. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  72503. **
  72504. ** P1 contains the address of the memory cell that contains the first memory
  72505. ** cell in an array of values used as arguments to the sub-program. P2
  72506. ** contains the address to jump to if the sub-program throws an IGNORE
  72507. ** exception using the RAISE() function. Register P3 contains the address
  72508. ** of a memory cell in this (the parent) VM that is used to allocate the
  72509. ** memory required by the sub-vdbe at runtime.
  72510. **
  72511. ** P4 is a pointer to the VM containing the trigger program.
  72512. **
  72513. ** If P5 is non-zero, then recursive program invocation is enabled.
  72514. */
  72515. case OP_Program: { /* jump */
  72516. int nMem; /* Number of memory registers for sub-program */
  72517. int nByte; /* Bytes of runtime space required for sub-program */
  72518. Mem *pRt; /* Register to allocate runtime space */
  72519. Mem *pMem; /* Used to iterate through memory cells */
  72520. Mem *pEnd; /* Last memory cell in new array */
  72521. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  72522. SubProgram *pProgram; /* Sub-program to execute */
  72523. void *t; /* Token identifying trigger */
  72524. pProgram = pOp->p4.pProgram;
  72525. pRt = &aMem[pOp->p3];
  72526. assert( pProgram->nOp>0 );
  72527. /* If the p5 flag is clear, then recursive invocation of triggers is
  72528. ** disabled for backwards compatibility (p5 is set if this sub-program
  72529. ** is really a trigger, not a foreign key action, and the flag set
  72530. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  72531. **
  72532. ** It is recursive invocation of triggers, at the SQL level, that is
  72533. ** disabled. In some cases a single trigger may generate more than one
  72534. ** SubProgram (if the trigger may be executed with more than one different
  72535. ** ON CONFLICT algorithm). SubProgram structures associated with a
  72536. ** single trigger all have the same value for the SubProgram.token
  72537. ** variable. */
  72538. if( pOp->p5 ){
  72539. t = pProgram->token;
  72540. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  72541. if( pFrame ) break;
  72542. }
  72543. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  72544. rc = SQLITE_ERROR;
  72545. sqlite3VdbeError(p, "too many levels of trigger recursion");
  72546. break;
  72547. }
  72548. /* Register pRt is used to store the memory required to save the state
  72549. ** of the current program, and the memory required at runtime to execute
  72550. ** the trigger program. If this trigger has been fired before, then pRt
  72551. ** is already allocated. Otherwise, it must be initialized. */
  72552. if( (pRt->flags&MEM_Frame)==0 ){
  72553. /* SubProgram.nMem is set to the number of memory cells used by the
  72554. ** program stored in SubProgram.aOp. As well as these, one memory
  72555. ** cell is required for each cursor used by the program. Set local
  72556. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  72557. */
  72558. nMem = pProgram->nMem + pProgram->nCsr;
  72559. nByte = ROUND8(sizeof(VdbeFrame))
  72560. + nMem * sizeof(Mem)
  72561. + pProgram->nCsr * sizeof(VdbeCursor *)
  72562. + pProgram->nOnce * sizeof(u8);
  72563. pFrame = sqlite3DbMallocZero(db, nByte);
  72564. if( !pFrame ){
  72565. goto no_mem;
  72566. }
  72567. sqlite3VdbeMemRelease(pRt);
  72568. pRt->flags = MEM_Frame;
  72569. pRt->u.pFrame = pFrame;
  72570. pFrame->v = p;
  72571. pFrame->nChildMem = nMem;
  72572. pFrame->nChildCsr = pProgram->nCsr;
  72573. pFrame->pc = (int)(pOp - aOp);
  72574. pFrame->aMem = p->aMem;
  72575. pFrame->nMem = p->nMem;
  72576. pFrame->apCsr = p->apCsr;
  72577. pFrame->nCursor = p->nCursor;
  72578. pFrame->aOp = p->aOp;
  72579. pFrame->nOp = p->nOp;
  72580. pFrame->token = pProgram->token;
  72581. pFrame->aOnceFlag = p->aOnceFlag;
  72582. pFrame->nOnceFlag = p->nOnceFlag;
  72583. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72584. pFrame->anExec = p->anExec;
  72585. #endif
  72586. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  72587. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  72588. pMem->flags = MEM_Undefined;
  72589. pMem->db = db;
  72590. }
  72591. }else{
  72592. pFrame = pRt->u.pFrame;
  72593. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
  72594. assert( pProgram->nCsr==pFrame->nChildCsr );
  72595. assert( (int)(pOp - aOp)==pFrame->pc );
  72596. }
  72597. p->nFrame++;
  72598. pFrame->pParent = p->pFrame;
  72599. pFrame->lastRowid = lastRowid;
  72600. pFrame->nChange = p->nChange;
  72601. pFrame->nDbChange = p->db->nChange;
  72602. p->nChange = 0;
  72603. p->pFrame = pFrame;
  72604. p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
  72605. p->nMem = pFrame->nChildMem;
  72606. p->nCursor = (u16)pFrame->nChildCsr;
  72607. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  72608. p->aOp = aOp = pProgram->aOp;
  72609. p->nOp = pProgram->nOp;
  72610. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  72611. p->nOnceFlag = pProgram->nOnce;
  72612. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  72613. p->anExec = 0;
  72614. #endif
  72615. pOp = &aOp[-1];
  72616. memset(p->aOnceFlag, 0, p->nOnceFlag);
  72617. break;
  72618. }
  72619. /* Opcode: Param P1 P2 * * *
  72620. **
  72621. ** This opcode is only ever present in sub-programs called via the
  72622. ** OP_Program instruction. Copy a value currently stored in a memory
  72623. ** cell of the calling (parent) frame to cell P2 in the current frames
  72624. ** address space. This is used by trigger programs to access the new.*
  72625. ** and old.* values.
  72626. **
  72627. ** The address of the cell in the parent frame is determined by adding
  72628. ** the value of the P1 argument to the value of the P1 argument to the
  72629. ** calling OP_Program instruction.
  72630. */
  72631. case OP_Param: { /* out2 */
  72632. VdbeFrame *pFrame;
  72633. Mem *pIn;
  72634. pOut = out2Prerelease(p, pOp);
  72635. pFrame = p->pFrame;
  72636. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  72637. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  72638. break;
  72639. }
  72640. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  72641. #ifndef SQLITE_OMIT_FOREIGN_KEY
  72642. /* Opcode: FkCounter P1 P2 * * *
  72643. ** Synopsis: fkctr[P1]+=P2
  72644. **
  72645. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  72646. ** If P1 is non-zero, the database constraint counter is incremented
  72647. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  72648. ** statement counter is incremented (immediate foreign key constraints).
  72649. */
  72650. case OP_FkCounter: {
  72651. if( db->flags & SQLITE_DeferFKs ){
  72652. db->nDeferredImmCons += pOp->p2;
  72653. }else if( pOp->p1 ){
  72654. db->nDeferredCons += pOp->p2;
  72655. }else{
  72656. p->nFkConstraint += pOp->p2;
  72657. }
  72658. break;
  72659. }
  72660. /* Opcode: FkIfZero P1 P2 * * *
  72661. ** Synopsis: if fkctr[P1]==0 goto P2
  72662. **
  72663. ** This opcode tests if a foreign key constraint-counter is currently zero.
  72664. ** If so, jump to instruction P2. Otherwise, fall through to the next
  72665. ** instruction.
  72666. **
  72667. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  72668. ** is zero (the one that counts deferred constraint violations). If P1 is
  72669. ** zero, the jump is taken if the statement constraint-counter is zero
  72670. ** (immediate foreign key constraint violations).
  72671. */
  72672. case OP_FkIfZero: { /* jump */
  72673. if( pOp->p1 ){
  72674. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  72675. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  72676. }else{
  72677. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  72678. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
  72679. }
  72680. break;
  72681. }
  72682. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  72683. #ifndef SQLITE_OMIT_AUTOINCREMENT
  72684. /* Opcode: MemMax P1 P2 * * *
  72685. ** Synopsis: r[P1]=max(r[P1],r[P2])
  72686. **
  72687. ** P1 is a register in the root frame of this VM (the root frame is
  72688. ** different from the current frame if this instruction is being executed
  72689. ** within a sub-program). Set the value of register P1 to the maximum of
  72690. ** its current value and the value in register P2.
  72691. **
  72692. ** This instruction throws an error if the memory cell is not initially
  72693. ** an integer.
  72694. */
  72695. case OP_MemMax: { /* in2 */
  72696. VdbeFrame *pFrame;
  72697. if( p->pFrame ){
  72698. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  72699. pIn1 = &pFrame->aMem[pOp->p1];
  72700. }else{
  72701. pIn1 = &aMem[pOp->p1];
  72702. }
  72703. assert( memIsValid(pIn1) );
  72704. sqlite3VdbeMemIntegerify(pIn1);
  72705. pIn2 = &aMem[pOp->p2];
  72706. sqlite3VdbeMemIntegerify(pIn2);
  72707. if( pIn1->u.i<pIn2->u.i){
  72708. pIn1->u.i = pIn2->u.i;
  72709. }
  72710. break;
  72711. }
  72712. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  72713. /* Opcode: IfPos P1 P2 * * *
  72714. ** Synopsis: if r[P1]>0 goto P2
  72715. **
  72716. ** Register P1 must contain an integer.
  72717. ** If the value of register P1 is 1 or greater, jump to P2 and
  72718. ** add the literal value P3 to register P1.
  72719. **
  72720. ** If the initial value of register P1 is less than 1, then the
  72721. ** value is unchanged and control passes through to the next instruction.
  72722. */
  72723. case OP_IfPos: { /* jump, in1 */
  72724. pIn1 = &aMem[pOp->p1];
  72725. assert( pIn1->flags&MEM_Int );
  72726. VdbeBranchTaken( pIn1->u.i>0, 2);
  72727. if( pIn1->u.i>0 ) goto jump_to_p2;
  72728. break;
  72729. }
  72730. /* Opcode: IfNeg P1 P2 P3 * *
  72731. ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
  72732. **
  72733. ** Register P1 must contain an integer. Add literal P3 to the value in
  72734. ** register P1 then if the value of register P1 is less than zero, jump to P2.
  72735. */
  72736. case OP_IfNeg: { /* jump, in1 */
  72737. pIn1 = &aMem[pOp->p1];
  72738. assert( pIn1->flags&MEM_Int );
  72739. pIn1->u.i += pOp->p3;
  72740. VdbeBranchTaken(pIn1->u.i<0, 2);
  72741. if( pIn1->u.i<0 ) goto jump_to_p2;
  72742. break;
  72743. }
  72744. /* Opcode: IfNotZero P1 P2 P3 * *
  72745. ** Synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2
  72746. **
  72747. ** Register P1 must contain an integer. If the content of register P1 is
  72748. ** initially nonzero, then add P3 to P1 and jump to P2. If register P1 is
  72749. ** initially zero, leave it unchanged and fall through.
  72750. */
  72751. case OP_IfNotZero: { /* jump, in1 */
  72752. pIn1 = &aMem[pOp->p1];
  72753. assert( pIn1->flags&MEM_Int );
  72754. VdbeBranchTaken(pIn1->u.i<0, 2);
  72755. if( pIn1->u.i ){
  72756. pIn1->u.i += pOp->p3;
  72757. goto jump_to_p2;
  72758. }
  72759. break;
  72760. }
  72761. /* Opcode: DecrJumpZero P1 P2 * * *
  72762. ** Synopsis: if (--r[P1])==0 goto P2
  72763. **
  72764. ** Register P1 must hold an integer. Decrement the value in register P1
  72765. ** then jump to P2 if the new value is exactly zero.
  72766. */
  72767. case OP_DecrJumpZero: { /* jump, in1 */
  72768. pIn1 = &aMem[pOp->p1];
  72769. assert( pIn1->flags&MEM_Int );
  72770. pIn1->u.i--;
  72771. VdbeBranchTaken(pIn1->u.i==0, 2);
  72772. if( pIn1->u.i==0 ) goto jump_to_p2;
  72773. break;
  72774. }
  72775. /* Opcode: JumpZeroIncr P1 P2 * * *
  72776. ** Synopsis: if (r[P1]++)==0 ) goto P2
  72777. **
  72778. ** The register P1 must contain an integer. If register P1 is initially
  72779. ** zero, then jump to P2. Increment register P1 regardless of whether or
  72780. ** not the jump is taken.
  72781. */
  72782. case OP_JumpZeroIncr: { /* jump, in1 */
  72783. pIn1 = &aMem[pOp->p1];
  72784. assert( pIn1->flags&MEM_Int );
  72785. VdbeBranchTaken(pIn1->u.i==0, 2);
  72786. if( (pIn1->u.i++)==0 ) goto jump_to_p2;
  72787. break;
  72788. }
  72789. /* Opcode: AggStep0 * P2 P3 P4 P5
  72790. ** Synopsis: accum=r[P3] step(r[P2@P5])
  72791. **
  72792. ** Execute the step function for an aggregate. The
  72793. ** function has P5 arguments. P4 is a pointer to the FuncDef
  72794. ** structure that specifies the function. Register P3 is the
  72795. ** accumulator.
  72796. **
  72797. ** The P5 arguments are taken from register P2 and its
  72798. ** successors.
  72799. */
  72800. /* Opcode: AggStep * P2 P3 P4 P5
  72801. ** Synopsis: accum=r[P3] step(r[P2@P5])
  72802. **
  72803. ** Execute the step function for an aggregate. The
  72804. ** function has P5 arguments. P4 is a pointer to an sqlite3_context
  72805. ** object that is used to run the function. Register P3 is
  72806. ** as the accumulator.
  72807. **
  72808. ** The P5 arguments are taken from register P2 and its
  72809. ** successors.
  72810. **
  72811. ** This opcode is initially coded as OP_AggStep0. On first evaluation,
  72812. ** the FuncDef stored in P4 is converted into an sqlite3_context and
  72813. ** the opcode is changed. In this way, the initialization of the
  72814. ** sqlite3_context only happens once, instead of on each call to the
  72815. ** step function.
  72816. */
  72817. case OP_AggStep0: {
  72818. int n;
  72819. sqlite3_context *pCtx;
  72820. assert( pOp->p4type==P4_FUNCDEF );
  72821. n = pOp->p5;
  72822. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  72823. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  72824. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  72825. pCtx = sqlite3DbMallocRaw(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
  72826. if( pCtx==0 ) goto no_mem;
  72827. pCtx->pMem = 0;
  72828. pCtx->pFunc = pOp->p4.pFunc;
  72829. pCtx->iOp = (int)(pOp - aOp);
  72830. pCtx->pVdbe = p;
  72831. pCtx->argc = n;
  72832. pOp->p4type = P4_FUNCCTX;
  72833. pOp->p4.pCtx = pCtx;
  72834. pOp->opcode = OP_AggStep;
  72835. /* Fall through into OP_AggStep */
  72836. }
  72837. case OP_AggStep: {
  72838. int i;
  72839. sqlite3_context *pCtx;
  72840. Mem *pMem;
  72841. Mem t;
  72842. assert( pOp->p4type==P4_FUNCCTX );
  72843. pCtx = pOp->p4.pCtx;
  72844. pMem = &aMem[pOp->p3];
  72845. /* If this function is inside of a trigger, the register array in aMem[]
  72846. ** might change from one evaluation to the next. The next block of code
  72847. ** checks to see if the register array has changed, and if so it
  72848. ** reinitializes the relavant parts of the sqlite3_context object */
  72849. if( pCtx->pMem != pMem ){
  72850. pCtx->pMem = pMem;
  72851. for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
  72852. }
  72853. #ifdef SQLITE_DEBUG
  72854. for(i=0; i<pCtx->argc; i++){
  72855. assert( memIsValid(pCtx->argv[i]) );
  72856. REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
  72857. }
  72858. #endif
  72859. pMem->n++;
  72860. sqlite3VdbeMemInit(&t, db, MEM_Null);
  72861. pCtx->pOut = &t;
  72862. pCtx->fErrorOrAux = 0;
  72863. pCtx->skipFlag = 0;
  72864. (pCtx->pFunc->xStep)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
  72865. if( pCtx->fErrorOrAux ){
  72866. if( pCtx->isError ){
  72867. sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
  72868. rc = pCtx->isError;
  72869. }
  72870. sqlite3VdbeMemRelease(&t);
  72871. }else{
  72872. assert( t.flags==MEM_Null );
  72873. }
  72874. if( pCtx->skipFlag ){
  72875. assert( pOp[-1].opcode==OP_CollSeq );
  72876. i = pOp[-1].p1;
  72877. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  72878. }
  72879. break;
  72880. }
  72881. /* Opcode: AggFinal P1 P2 * P4 *
  72882. ** Synopsis: accum=r[P1] N=P2
  72883. **
  72884. ** Execute the finalizer function for an aggregate. P1 is
  72885. ** the memory location that is the accumulator for the aggregate.
  72886. **
  72887. ** P2 is the number of arguments that the step function takes and
  72888. ** P4 is a pointer to the FuncDef for this function. The P2
  72889. ** argument is not used by this opcode. It is only there to disambiguate
  72890. ** functions that can take varying numbers of arguments. The
  72891. ** P4 argument is only needed for the degenerate case where
  72892. ** the step function was not previously called.
  72893. */
  72894. case OP_AggFinal: {
  72895. Mem *pMem;
  72896. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  72897. pMem = &aMem[pOp->p1];
  72898. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  72899. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  72900. if( rc ){
  72901. sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
  72902. }
  72903. sqlite3VdbeChangeEncoding(pMem, encoding);
  72904. UPDATE_MAX_BLOBSIZE(pMem);
  72905. if( sqlite3VdbeMemTooBig(pMem) ){
  72906. goto too_big;
  72907. }
  72908. break;
  72909. }
  72910. #ifndef SQLITE_OMIT_WAL
  72911. /* Opcode: Checkpoint P1 P2 P3 * *
  72912. **
  72913. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  72914. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
  72915. ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
  72916. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  72917. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  72918. ** in the WAL that have been checkpointed after the checkpoint
  72919. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  72920. ** mem[P3+2] are initialized to -1.
  72921. */
  72922. case OP_Checkpoint: {
  72923. int i; /* Loop counter */
  72924. int aRes[3]; /* Results */
  72925. Mem *pMem; /* Write results here */
  72926. assert( p->readOnly==0 );
  72927. aRes[0] = 0;
  72928. aRes[1] = aRes[2] = -1;
  72929. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  72930. || pOp->p2==SQLITE_CHECKPOINT_FULL
  72931. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  72932. || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
  72933. );
  72934. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  72935. if( rc==SQLITE_BUSY ){
  72936. rc = SQLITE_OK;
  72937. aRes[0] = 1;
  72938. }
  72939. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  72940. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  72941. }
  72942. break;
  72943. };
  72944. #endif
  72945. #ifndef SQLITE_OMIT_PRAGMA
  72946. /* Opcode: JournalMode P1 P2 P3 * *
  72947. **
  72948. ** Change the journal mode of database P1 to P3. P3 must be one of the
  72949. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  72950. ** modes (delete, truncate, persist, off and memory), this is a simple
  72951. ** operation. No IO is required.
  72952. **
  72953. ** If changing into or out of WAL mode the procedure is more complicated.
  72954. **
  72955. ** Write a string containing the final journal-mode to register P2.
  72956. */
  72957. case OP_JournalMode: { /* out2 */
  72958. Btree *pBt; /* Btree to change journal mode of */
  72959. Pager *pPager; /* Pager associated with pBt */
  72960. int eNew; /* New journal mode */
  72961. int eOld; /* The old journal mode */
  72962. #ifndef SQLITE_OMIT_WAL
  72963. const char *zFilename; /* Name of database file for pPager */
  72964. #endif
  72965. pOut = out2Prerelease(p, pOp);
  72966. eNew = pOp->p3;
  72967. assert( eNew==PAGER_JOURNALMODE_DELETE
  72968. || eNew==PAGER_JOURNALMODE_TRUNCATE
  72969. || eNew==PAGER_JOURNALMODE_PERSIST
  72970. || eNew==PAGER_JOURNALMODE_OFF
  72971. || eNew==PAGER_JOURNALMODE_MEMORY
  72972. || eNew==PAGER_JOURNALMODE_WAL
  72973. || eNew==PAGER_JOURNALMODE_QUERY
  72974. );
  72975. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  72976. assert( p->readOnly==0 );
  72977. pBt = db->aDb[pOp->p1].pBt;
  72978. pPager = sqlite3BtreePager(pBt);
  72979. eOld = sqlite3PagerGetJournalMode(pPager);
  72980. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  72981. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  72982. #ifndef SQLITE_OMIT_WAL
  72983. zFilename = sqlite3PagerFilename(pPager, 1);
  72984. /* Do not allow a transition to journal_mode=WAL for a database
  72985. ** in temporary storage or if the VFS does not support shared memory
  72986. */
  72987. if( eNew==PAGER_JOURNALMODE_WAL
  72988. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  72989. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  72990. ){
  72991. eNew = eOld;
  72992. }
  72993. if( (eNew!=eOld)
  72994. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  72995. ){
  72996. if( !db->autoCommit || db->nVdbeRead>1 ){
  72997. rc = SQLITE_ERROR;
  72998. sqlite3VdbeError(p,
  72999. "cannot change %s wal mode from within a transaction",
  73000. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  73001. );
  73002. break;
  73003. }else{
  73004. if( eOld==PAGER_JOURNALMODE_WAL ){
  73005. /* If leaving WAL mode, close the log file. If successful, the call
  73006. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  73007. ** file. An EXCLUSIVE lock may still be held on the database file
  73008. ** after a successful return.
  73009. */
  73010. rc = sqlite3PagerCloseWal(pPager);
  73011. if( rc==SQLITE_OK ){
  73012. sqlite3PagerSetJournalMode(pPager, eNew);
  73013. }
  73014. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  73015. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  73016. ** as an intermediate */
  73017. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  73018. }
  73019. /* Open a transaction on the database file. Regardless of the journal
  73020. ** mode, this transaction always uses a rollback journal.
  73021. */
  73022. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  73023. if( rc==SQLITE_OK ){
  73024. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  73025. }
  73026. }
  73027. }
  73028. #endif /* ifndef SQLITE_OMIT_WAL */
  73029. if( rc ){
  73030. eNew = eOld;
  73031. }
  73032. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  73033. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  73034. pOut->z = (char *)sqlite3JournalModename(eNew);
  73035. pOut->n = sqlite3Strlen30(pOut->z);
  73036. pOut->enc = SQLITE_UTF8;
  73037. sqlite3VdbeChangeEncoding(pOut, encoding);
  73038. break;
  73039. };
  73040. #endif /* SQLITE_OMIT_PRAGMA */
  73041. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  73042. /* Opcode: Vacuum * * * * *
  73043. **
  73044. ** Vacuum the entire database. This opcode will cause other virtual
  73045. ** machines to be created and run. It may not be called from within
  73046. ** a transaction.
  73047. */
  73048. case OP_Vacuum: {
  73049. assert( p->readOnly==0 );
  73050. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  73051. break;
  73052. }
  73053. #endif
  73054. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  73055. /* Opcode: IncrVacuum P1 P2 * * *
  73056. **
  73057. ** Perform a single step of the incremental vacuum procedure on
  73058. ** the P1 database. If the vacuum has finished, jump to instruction
  73059. ** P2. Otherwise, fall through to the next instruction.
  73060. */
  73061. case OP_IncrVacuum: { /* jump */
  73062. Btree *pBt;
  73063. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  73064. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  73065. assert( p->readOnly==0 );
  73066. pBt = db->aDb[pOp->p1].pBt;
  73067. rc = sqlite3BtreeIncrVacuum(pBt);
  73068. VdbeBranchTaken(rc==SQLITE_DONE,2);
  73069. if( rc==SQLITE_DONE ){
  73070. rc = SQLITE_OK;
  73071. goto jump_to_p2;
  73072. }
  73073. break;
  73074. }
  73075. #endif
  73076. /* Opcode: Expire P1 * * * *
  73077. **
  73078. ** Cause precompiled statements to expire. When an expired statement
  73079. ** is executed using sqlite3_step() it will either automatically
  73080. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  73081. ** or it will fail with SQLITE_SCHEMA.
  73082. **
  73083. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  73084. ** then only the currently executing statement is expired.
  73085. */
  73086. case OP_Expire: {
  73087. if( !pOp->p1 ){
  73088. sqlite3ExpirePreparedStatements(db);
  73089. }else{
  73090. p->expired = 1;
  73091. }
  73092. break;
  73093. }
  73094. #ifndef SQLITE_OMIT_SHARED_CACHE
  73095. /* Opcode: TableLock P1 P2 P3 P4 *
  73096. ** Synopsis: iDb=P1 root=P2 write=P3
  73097. **
  73098. ** Obtain a lock on a particular table. This instruction is only used when
  73099. ** the shared-cache feature is enabled.
  73100. **
  73101. ** P1 is the index of the database in sqlite3.aDb[] of the database
  73102. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  73103. ** a write lock if P3==1.
  73104. **
  73105. ** P2 contains the root-page of the table to lock.
  73106. **
  73107. ** P4 contains a pointer to the name of the table being locked. This is only
  73108. ** used to generate an error message if the lock cannot be obtained.
  73109. */
  73110. case OP_TableLock: {
  73111. u8 isWriteLock = (u8)pOp->p3;
  73112. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  73113. int p1 = pOp->p1;
  73114. assert( p1>=0 && p1<db->nDb );
  73115. assert( DbMaskTest(p->btreeMask, p1) );
  73116. assert( isWriteLock==0 || isWriteLock==1 );
  73117. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  73118. if( (rc&0xFF)==SQLITE_LOCKED ){
  73119. const char *z = pOp->p4.z;
  73120. sqlite3VdbeError(p, "database table is locked: %s", z);
  73121. }
  73122. }
  73123. break;
  73124. }
  73125. #endif /* SQLITE_OMIT_SHARED_CACHE */
  73126. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73127. /* Opcode: VBegin * * * P4 *
  73128. **
  73129. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  73130. ** xBegin method for that table.
  73131. **
  73132. ** Also, whether or not P4 is set, check that this is not being called from
  73133. ** within a callback to a virtual table xSync() method. If it is, the error
  73134. ** code will be set to SQLITE_LOCKED.
  73135. */
  73136. case OP_VBegin: {
  73137. VTable *pVTab;
  73138. pVTab = pOp->p4.pVtab;
  73139. rc = sqlite3VtabBegin(db, pVTab);
  73140. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  73141. break;
  73142. }
  73143. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73144. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73145. /* Opcode: VCreate P1 P2 * * *
  73146. **
  73147. ** P2 is a register that holds the name of a virtual table in database
  73148. ** P1. Call the xCreate method for that table.
  73149. */
  73150. case OP_VCreate: {
  73151. Mem sMem; /* For storing the record being decoded */
  73152. const char *zTab; /* Name of the virtual table */
  73153. memset(&sMem, 0, sizeof(sMem));
  73154. sMem.db = db;
  73155. /* Because P2 is always a static string, it is impossible for the
  73156. ** sqlite3VdbeMemCopy() to fail */
  73157. assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
  73158. assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
  73159. rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
  73160. assert( rc==SQLITE_OK );
  73161. zTab = (const char*)sqlite3_value_text(&sMem);
  73162. assert( zTab || db->mallocFailed );
  73163. if( zTab ){
  73164. rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
  73165. }
  73166. sqlite3VdbeMemRelease(&sMem);
  73167. break;
  73168. }
  73169. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73170. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73171. /* Opcode: VDestroy P1 * * P4 *
  73172. **
  73173. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  73174. ** of that table.
  73175. */
  73176. case OP_VDestroy: {
  73177. db->nVDestroy++;
  73178. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  73179. db->nVDestroy--;
  73180. break;
  73181. }
  73182. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73183. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73184. /* Opcode: VOpen P1 * * P4 *
  73185. **
  73186. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  73187. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  73188. ** table and stores that cursor in P1.
  73189. */
  73190. case OP_VOpen: {
  73191. VdbeCursor *pCur;
  73192. sqlite3_vtab_cursor *pVtabCursor;
  73193. sqlite3_vtab *pVtab;
  73194. const sqlite3_module *pModule;
  73195. assert( p->bIsReader );
  73196. pCur = 0;
  73197. pVtabCursor = 0;
  73198. pVtab = pOp->p4.pVtab->pVtab;
  73199. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  73200. rc = SQLITE_LOCKED;
  73201. break;
  73202. }
  73203. pModule = pVtab->pModule;
  73204. rc = pModule->xOpen(pVtab, &pVtabCursor);
  73205. sqlite3VtabImportErrmsg(p, pVtab);
  73206. if( SQLITE_OK==rc ){
  73207. /* Initialize sqlite3_vtab_cursor base class */
  73208. pVtabCursor->pVtab = pVtab;
  73209. /* Initialize vdbe cursor object */
  73210. pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  73211. if( pCur ){
  73212. pCur->pVtabCursor = pVtabCursor;
  73213. pVtab->nRef++;
  73214. }else{
  73215. assert( db->mallocFailed );
  73216. pModule->xClose(pVtabCursor);
  73217. goto no_mem;
  73218. }
  73219. }
  73220. break;
  73221. }
  73222. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73223. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73224. /* Opcode: VFilter P1 P2 P3 P4 *
  73225. ** Synopsis: iplan=r[P3] zplan='P4'
  73226. **
  73227. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  73228. ** the filtered result set is empty.
  73229. **
  73230. ** P4 is either NULL or a string that was generated by the xBestIndex
  73231. ** method of the module. The interpretation of the P4 string is left
  73232. ** to the module implementation.
  73233. **
  73234. ** This opcode invokes the xFilter method on the virtual table specified
  73235. ** by P1. The integer query plan parameter to xFilter is stored in register
  73236. ** P3. Register P3+1 stores the argc parameter to be passed to the
  73237. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  73238. ** additional parameters which are passed to
  73239. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  73240. **
  73241. ** A jump is made to P2 if the result set after filtering would be empty.
  73242. */
  73243. case OP_VFilter: { /* jump */
  73244. int nArg;
  73245. int iQuery;
  73246. const sqlite3_module *pModule;
  73247. Mem *pQuery;
  73248. Mem *pArgc;
  73249. sqlite3_vtab_cursor *pVtabCursor;
  73250. sqlite3_vtab *pVtab;
  73251. VdbeCursor *pCur;
  73252. int res;
  73253. int i;
  73254. Mem **apArg;
  73255. pQuery = &aMem[pOp->p3];
  73256. pArgc = &pQuery[1];
  73257. pCur = p->apCsr[pOp->p1];
  73258. assert( memIsValid(pQuery) );
  73259. REGISTER_TRACE(pOp->p3, pQuery);
  73260. assert( pCur->pVtabCursor );
  73261. pVtabCursor = pCur->pVtabCursor;
  73262. pVtab = pVtabCursor->pVtab;
  73263. pModule = pVtab->pModule;
  73264. /* Grab the index number and argc parameters */
  73265. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  73266. nArg = (int)pArgc->u.i;
  73267. iQuery = (int)pQuery->u.i;
  73268. /* Invoke the xFilter method */
  73269. res = 0;
  73270. apArg = p->apArg;
  73271. for(i = 0; i<nArg; i++){
  73272. apArg[i] = &pArgc[i+1];
  73273. }
  73274. rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  73275. sqlite3VtabImportErrmsg(p, pVtab);
  73276. if( rc==SQLITE_OK ){
  73277. res = pModule->xEof(pVtabCursor);
  73278. }
  73279. pCur->nullRow = 0;
  73280. VdbeBranchTaken(res!=0,2);
  73281. if( res ) goto jump_to_p2;
  73282. break;
  73283. }
  73284. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73285. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73286. /* Opcode: VColumn P1 P2 P3 * *
  73287. ** Synopsis: r[P3]=vcolumn(P2)
  73288. **
  73289. ** Store the value of the P2-th column of
  73290. ** the row of the virtual-table that the
  73291. ** P1 cursor is pointing to into register P3.
  73292. */
  73293. case OP_VColumn: {
  73294. sqlite3_vtab *pVtab;
  73295. const sqlite3_module *pModule;
  73296. Mem *pDest;
  73297. sqlite3_context sContext;
  73298. VdbeCursor *pCur = p->apCsr[pOp->p1];
  73299. assert( pCur->pVtabCursor );
  73300. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  73301. pDest = &aMem[pOp->p3];
  73302. memAboutToChange(p, pDest);
  73303. if( pCur->nullRow ){
  73304. sqlite3VdbeMemSetNull(pDest);
  73305. break;
  73306. }
  73307. pVtab = pCur->pVtabCursor->pVtab;
  73308. pModule = pVtab->pModule;
  73309. assert( pModule->xColumn );
  73310. memset(&sContext, 0, sizeof(sContext));
  73311. sContext.pOut = pDest;
  73312. MemSetTypeFlag(pDest, MEM_Null);
  73313. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  73314. sqlite3VtabImportErrmsg(p, pVtab);
  73315. if( sContext.isError ){
  73316. rc = sContext.isError;
  73317. }
  73318. sqlite3VdbeChangeEncoding(pDest, encoding);
  73319. REGISTER_TRACE(pOp->p3, pDest);
  73320. UPDATE_MAX_BLOBSIZE(pDest);
  73321. if( sqlite3VdbeMemTooBig(pDest) ){
  73322. goto too_big;
  73323. }
  73324. break;
  73325. }
  73326. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73327. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73328. /* Opcode: VNext P1 P2 * * *
  73329. **
  73330. ** Advance virtual table P1 to the next row in its result set and
  73331. ** jump to instruction P2. Or, if the virtual table has reached
  73332. ** the end of its result set, then fall through to the next instruction.
  73333. */
  73334. case OP_VNext: { /* jump */
  73335. sqlite3_vtab *pVtab;
  73336. const sqlite3_module *pModule;
  73337. int res;
  73338. VdbeCursor *pCur;
  73339. res = 0;
  73340. pCur = p->apCsr[pOp->p1];
  73341. assert( pCur->pVtabCursor );
  73342. if( pCur->nullRow ){
  73343. break;
  73344. }
  73345. pVtab = pCur->pVtabCursor->pVtab;
  73346. pModule = pVtab->pModule;
  73347. assert( pModule->xNext );
  73348. /* Invoke the xNext() method of the module. There is no way for the
  73349. ** underlying implementation to return an error if one occurs during
  73350. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  73351. ** data is available) and the error code returned when xColumn or
  73352. ** some other method is next invoked on the save virtual table cursor.
  73353. */
  73354. rc = pModule->xNext(pCur->pVtabCursor);
  73355. sqlite3VtabImportErrmsg(p, pVtab);
  73356. if( rc==SQLITE_OK ){
  73357. res = pModule->xEof(pCur->pVtabCursor);
  73358. }
  73359. VdbeBranchTaken(!res,2);
  73360. if( !res ){
  73361. /* If there is data, jump to P2 */
  73362. goto jump_to_p2_and_check_for_interrupt;
  73363. }
  73364. goto check_for_interrupt;
  73365. }
  73366. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73367. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73368. /* Opcode: VRename P1 * * P4 *
  73369. **
  73370. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  73371. ** This opcode invokes the corresponding xRename method. The value
  73372. ** in register P1 is passed as the zName argument to the xRename method.
  73373. */
  73374. case OP_VRename: {
  73375. sqlite3_vtab *pVtab;
  73376. Mem *pName;
  73377. pVtab = pOp->p4.pVtab->pVtab;
  73378. pName = &aMem[pOp->p1];
  73379. assert( pVtab->pModule->xRename );
  73380. assert( memIsValid(pName) );
  73381. assert( p->readOnly==0 );
  73382. REGISTER_TRACE(pOp->p1, pName);
  73383. assert( pName->flags & MEM_Str );
  73384. testcase( pName->enc==SQLITE_UTF8 );
  73385. testcase( pName->enc==SQLITE_UTF16BE );
  73386. testcase( pName->enc==SQLITE_UTF16LE );
  73387. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  73388. if( rc==SQLITE_OK ){
  73389. rc = pVtab->pModule->xRename(pVtab, pName->z);
  73390. sqlite3VtabImportErrmsg(p, pVtab);
  73391. p->expired = 0;
  73392. }
  73393. break;
  73394. }
  73395. #endif
  73396. #ifndef SQLITE_OMIT_VIRTUALTABLE
  73397. /* Opcode: VUpdate P1 P2 P3 P4 P5
  73398. ** Synopsis: data=r[P3@P2]
  73399. **
  73400. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  73401. ** This opcode invokes the corresponding xUpdate method. P2 values
  73402. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  73403. ** invocation. The value in register (P3+P2-1) corresponds to the
  73404. ** p2th element of the argv array passed to xUpdate.
  73405. **
  73406. ** The xUpdate method will do a DELETE or an INSERT or both.
  73407. ** The argv[0] element (which corresponds to memory cell P3)
  73408. ** is the rowid of a row to delete. If argv[0] is NULL then no
  73409. ** deletion occurs. The argv[1] element is the rowid of the new
  73410. ** row. This can be NULL to have the virtual table select the new
  73411. ** rowid for itself. The subsequent elements in the array are
  73412. ** the values of columns in the new row.
  73413. **
  73414. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  73415. ** a row to delete.
  73416. **
  73417. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  73418. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  73419. ** is set to the value of the rowid for the row just inserted.
  73420. **
  73421. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  73422. ** apply in the case of a constraint failure on an insert or update.
  73423. */
  73424. case OP_VUpdate: {
  73425. sqlite3_vtab *pVtab;
  73426. const sqlite3_module *pModule;
  73427. int nArg;
  73428. int i;
  73429. sqlite_int64 rowid;
  73430. Mem **apArg;
  73431. Mem *pX;
  73432. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  73433. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  73434. );
  73435. assert( p->readOnly==0 );
  73436. pVtab = pOp->p4.pVtab->pVtab;
  73437. if( pVtab==0 || NEVER(pVtab->pModule==0) ){
  73438. rc = SQLITE_LOCKED;
  73439. break;
  73440. }
  73441. pModule = pVtab->pModule;
  73442. nArg = pOp->p2;
  73443. assert( pOp->p4type==P4_VTAB );
  73444. if( ALWAYS(pModule->xUpdate) ){
  73445. u8 vtabOnConflict = db->vtabOnConflict;
  73446. apArg = p->apArg;
  73447. pX = &aMem[pOp->p3];
  73448. for(i=0; i<nArg; i++){
  73449. assert( memIsValid(pX) );
  73450. memAboutToChange(p, pX);
  73451. apArg[i] = pX;
  73452. pX++;
  73453. }
  73454. db->vtabOnConflict = pOp->p5;
  73455. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  73456. db->vtabOnConflict = vtabOnConflict;
  73457. sqlite3VtabImportErrmsg(p, pVtab);
  73458. if( rc==SQLITE_OK && pOp->p1 ){
  73459. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  73460. db->lastRowid = lastRowid = rowid;
  73461. }
  73462. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  73463. if( pOp->p5==OE_Ignore ){
  73464. rc = SQLITE_OK;
  73465. }else{
  73466. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  73467. }
  73468. }else{
  73469. p->nChange++;
  73470. }
  73471. }
  73472. break;
  73473. }
  73474. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  73475. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  73476. /* Opcode: Pagecount P1 P2 * * *
  73477. **
  73478. ** Write the current number of pages in database P1 to memory cell P2.
  73479. */
  73480. case OP_Pagecount: { /* out2 */
  73481. pOut = out2Prerelease(p, pOp);
  73482. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  73483. break;
  73484. }
  73485. #endif
  73486. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  73487. /* Opcode: MaxPgcnt P1 P2 P3 * *
  73488. **
  73489. ** Try to set the maximum page count for database P1 to the value in P3.
  73490. ** Do not let the maximum page count fall below the current page count and
  73491. ** do not change the maximum page count value if P3==0.
  73492. **
  73493. ** Store the maximum page count after the change in register P2.
  73494. */
  73495. case OP_MaxPgcnt: { /* out2 */
  73496. unsigned int newMax;
  73497. Btree *pBt;
  73498. pOut = out2Prerelease(p, pOp);
  73499. pBt = db->aDb[pOp->p1].pBt;
  73500. newMax = 0;
  73501. if( pOp->p3 ){
  73502. newMax = sqlite3BtreeLastPage(pBt);
  73503. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  73504. }
  73505. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  73506. break;
  73507. }
  73508. #endif
  73509. /* Opcode: Init * P2 * P4 *
  73510. ** Synopsis: Start at P2
  73511. **
  73512. ** Programs contain a single instance of this opcode as the very first
  73513. ** opcode.
  73514. **
  73515. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  73516. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  73517. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  73518. **
  73519. ** If P2 is not zero, jump to instruction P2.
  73520. */
  73521. case OP_Init: { /* jump */
  73522. char *zTrace;
  73523. char *z;
  73524. #ifndef SQLITE_OMIT_TRACE
  73525. if( db->xTrace
  73526. && !p->doingRerun
  73527. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  73528. ){
  73529. z = sqlite3VdbeExpandSql(p, zTrace);
  73530. db->xTrace(db->pTraceArg, z);
  73531. sqlite3DbFree(db, z);
  73532. }
  73533. #ifdef SQLITE_USE_FCNTL_TRACE
  73534. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  73535. if( zTrace ){
  73536. int i;
  73537. for(i=0; i<db->nDb; i++){
  73538. if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  73539. sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
  73540. }
  73541. }
  73542. #endif /* SQLITE_USE_FCNTL_TRACE */
  73543. #ifdef SQLITE_DEBUG
  73544. if( (db->flags & SQLITE_SqlTrace)!=0
  73545. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  73546. ){
  73547. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  73548. }
  73549. #endif /* SQLITE_DEBUG */
  73550. #endif /* SQLITE_OMIT_TRACE */
  73551. if( pOp->p2 ) goto jump_to_p2;
  73552. break;
  73553. }
  73554. /* Opcode: Noop * * * * *
  73555. **
  73556. ** Do nothing. This instruction is often useful as a jump
  73557. ** destination.
  73558. */
  73559. /*
  73560. ** The magic Explain opcode are only inserted when explain==2 (which
  73561. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  73562. ** This opcode records information from the optimizer. It is the
  73563. ** the same as a no-op. This opcodesnever appears in a real VM program.
  73564. */
  73565. default: { /* This is really OP_Noop and OP_Explain */
  73566. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  73567. break;
  73568. }
  73569. /*****************************************************************************
  73570. ** The cases of the switch statement above this line should all be indented
  73571. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  73572. ** readability. From this point on down, the normal indentation rules are
  73573. ** restored.
  73574. *****************************************************************************/
  73575. }
  73576. #ifdef VDBE_PROFILE
  73577. {
  73578. u64 endTime = sqlite3Hwtime();
  73579. if( endTime>start ) pOrigOp->cycles += endTime - start;
  73580. pOrigOp->cnt++;
  73581. }
  73582. #endif
  73583. /* The following code adds nothing to the actual functionality
  73584. ** of the program. It is only here for testing and debugging.
  73585. ** On the other hand, it does burn CPU cycles every time through
  73586. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  73587. */
  73588. #ifndef NDEBUG
  73589. assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
  73590. #ifdef SQLITE_DEBUG
  73591. if( db->flags & SQLITE_VdbeTrace ){
  73592. if( rc!=0 ) printf("rc=%d\n",rc);
  73593. if( pOrigOp->opflags & (OPFLG_OUT2) ){
  73594. registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
  73595. }
  73596. if( pOrigOp->opflags & OPFLG_OUT3 ){
  73597. registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
  73598. }
  73599. }
  73600. #endif /* SQLITE_DEBUG */
  73601. #endif /* NDEBUG */
  73602. } /* The end of the for(;;) loop the loops through opcodes */
  73603. /* If we reach this point, it means that execution is finished with
  73604. ** an error of some kind.
  73605. */
  73606. vdbe_error_halt:
  73607. assert( rc );
  73608. p->rc = rc;
  73609. testcase( sqlite3GlobalConfig.xLog!=0 );
  73610. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  73611. (int)(pOp - aOp), p->zSql, p->zErrMsg);
  73612. sqlite3VdbeHalt(p);
  73613. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  73614. rc = SQLITE_ERROR;
  73615. if( resetSchemaOnFault>0 ){
  73616. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  73617. }
  73618. /* This is the only way out of this procedure. We have to
  73619. ** release the mutexes on btrees that were acquired at the
  73620. ** top. */
  73621. vdbe_return:
  73622. db->lastRowid = lastRowid;
  73623. testcase( nVmStep>0 );
  73624. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  73625. sqlite3VdbeLeave(p);
  73626. return rc;
  73627. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  73628. ** is encountered.
  73629. */
  73630. too_big:
  73631. sqlite3VdbeError(p, "string or blob too big");
  73632. rc = SQLITE_TOOBIG;
  73633. goto vdbe_error_halt;
  73634. /* Jump to here if a malloc() fails.
  73635. */
  73636. no_mem:
  73637. db->mallocFailed = 1;
  73638. sqlite3VdbeError(p, "out of memory");
  73639. rc = SQLITE_NOMEM;
  73640. goto vdbe_error_halt;
  73641. /* Jump to here for any other kind of fatal error. The "rc" variable
  73642. ** should hold the error number.
  73643. */
  73644. abort_due_to_error:
  73645. assert( p->zErrMsg==0 );
  73646. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  73647. if( rc!=SQLITE_IOERR_NOMEM ){
  73648. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  73649. }
  73650. goto vdbe_error_halt;
  73651. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  73652. ** flag.
  73653. */
  73654. abort_due_to_interrupt:
  73655. assert( db->u1.isInterrupted );
  73656. rc = SQLITE_INTERRUPT;
  73657. p->rc = rc;
  73658. sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
  73659. goto vdbe_error_halt;
  73660. }
  73661. /************** End of vdbe.c ************************************************/
  73662. /************** Begin file vdbeblob.c ****************************************/
  73663. /*
  73664. ** 2007 May 1
  73665. **
  73666. ** The author disclaims copyright to this source code. In place of
  73667. ** a legal notice, here is a blessing:
  73668. **
  73669. ** May you do good and not evil.
  73670. ** May you find forgiveness for yourself and forgive others.
  73671. ** May you share freely, never taking more than you give.
  73672. **
  73673. *************************************************************************
  73674. **
  73675. ** This file contains code used to implement incremental BLOB I/O.
  73676. */
  73677. /* #include "sqliteInt.h" */
  73678. /* #include "vdbeInt.h" */
  73679. #ifndef SQLITE_OMIT_INCRBLOB
  73680. /*
  73681. ** Valid sqlite3_blob* handles point to Incrblob structures.
  73682. */
  73683. typedef struct Incrblob Incrblob;
  73684. struct Incrblob {
  73685. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  73686. int nByte; /* Size of open blob, in bytes */
  73687. int iOffset; /* Byte offset of blob in cursor data */
  73688. int iCol; /* Table column this handle is open on */
  73689. BtCursor *pCsr; /* Cursor pointing at blob row */
  73690. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  73691. sqlite3 *db; /* The associated database */
  73692. };
  73693. /*
  73694. ** This function is used by both blob_open() and blob_reopen(). It seeks
  73695. ** the b-tree cursor associated with blob handle p to point to row iRow.
  73696. ** If successful, SQLITE_OK is returned and subsequent calls to
  73697. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  73698. **
  73699. ** If an error occurs, or if the specified row does not exist or does not
  73700. ** contain a value of type TEXT or BLOB in the column nominated when the
  73701. ** blob handle was opened, then an error code is returned and *pzErr may
  73702. ** be set to point to a buffer containing an error message. It is the
  73703. ** responsibility of the caller to free the error message buffer using
  73704. ** sqlite3DbFree().
  73705. **
  73706. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  73707. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  73708. ** immediately return SQLITE_ABORT.
  73709. */
  73710. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  73711. int rc; /* Error code */
  73712. char *zErr = 0; /* Error message */
  73713. Vdbe *v = (Vdbe *)p->pStmt;
  73714. /* Set the value of the SQL statements only variable to integer iRow.
  73715. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  73716. ** triggering asserts related to mutexes.
  73717. */
  73718. assert( v->aVar[0].flags&MEM_Int );
  73719. v->aVar[0].u.i = iRow;
  73720. rc = sqlite3_step(p->pStmt);
  73721. if( rc==SQLITE_ROW ){
  73722. VdbeCursor *pC = v->apCsr[0];
  73723. u32 type = pC->aType[p->iCol];
  73724. if( type<12 ){
  73725. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  73726. type==0?"null": type==7?"real": "integer"
  73727. );
  73728. rc = SQLITE_ERROR;
  73729. sqlite3_finalize(p->pStmt);
  73730. p->pStmt = 0;
  73731. }else{
  73732. p->iOffset = pC->aType[p->iCol + pC->nField];
  73733. p->nByte = sqlite3VdbeSerialTypeLen(type);
  73734. p->pCsr = pC->pCursor;
  73735. sqlite3BtreeIncrblobCursor(p->pCsr);
  73736. }
  73737. }
  73738. if( rc==SQLITE_ROW ){
  73739. rc = SQLITE_OK;
  73740. }else if( p->pStmt ){
  73741. rc = sqlite3_finalize(p->pStmt);
  73742. p->pStmt = 0;
  73743. if( rc==SQLITE_OK ){
  73744. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  73745. rc = SQLITE_ERROR;
  73746. }else{
  73747. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  73748. }
  73749. }
  73750. assert( rc!=SQLITE_OK || zErr==0 );
  73751. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  73752. *pzErr = zErr;
  73753. return rc;
  73754. }
  73755. /*
  73756. ** Open a blob handle.
  73757. */
  73758. SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
  73759. sqlite3* db, /* The database connection */
  73760. const char *zDb, /* The attached database containing the blob */
  73761. const char *zTable, /* The table containing the blob */
  73762. const char *zColumn, /* The column containing the blob */
  73763. sqlite_int64 iRow, /* The row containing the glob */
  73764. int flags, /* True -> read/write access, false -> read-only */
  73765. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  73766. ){
  73767. int nAttempt = 0;
  73768. int iCol; /* Index of zColumn in row-record */
  73769. /* This VDBE program seeks a btree cursor to the identified
  73770. ** db/table/row entry. The reason for using a vdbe program instead
  73771. ** of writing code to use the b-tree layer directly is that the
  73772. ** vdbe program will take advantage of the various transaction,
  73773. ** locking and error handling infrastructure built into the vdbe.
  73774. **
  73775. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  73776. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  73777. ** uses it to implement the blob_read(), blob_write() and
  73778. ** blob_bytes() functions.
  73779. **
  73780. ** The sqlite3_blob_close() function finalizes the vdbe program,
  73781. ** which closes the b-tree cursor and (possibly) commits the
  73782. ** transaction.
  73783. */
  73784. static const int iLn = VDBE_OFFSET_LINENO(4);
  73785. static const VdbeOpList openBlob[] = {
  73786. /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
  73787. {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
  73788. /* One of the following two instructions is replaced by an OP_Noop. */
  73789. {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
  73790. {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
  73791. {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
  73792. {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
  73793. {OP_Column, 0, 0, 1}, /* 6 */
  73794. {OP_ResultRow, 1, 0, 0}, /* 7 */
  73795. {OP_Goto, 0, 4, 0}, /* 8 */
  73796. {OP_Close, 0, 0, 0}, /* 9 */
  73797. {OP_Halt, 0, 0, 0}, /* 10 */
  73798. };
  73799. int rc = SQLITE_OK;
  73800. char *zErr = 0;
  73801. Table *pTab;
  73802. Parse *pParse = 0;
  73803. Incrblob *pBlob = 0;
  73804. #ifdef SQLITE_ENABLE_API_ARMOR
  73805. if( ppBlob==0 ){
  73806. return SQLITE_MISUSE_BKPT;
  73807. }
  73808. #endif
  73809. *ppBlob = 0;
  73810. #ifdef SQLITE_ENABLE_API_ARMOR
  73811. if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
  73812. return SQLITE_MISUSE_BKPT;
  73813. }
  73814. #endif
  73815. flags = !!flags; /* flags = (flags ? 1 : 0); */
  73816. sqlite3_mutex_enter(db->mutex);
  73817. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  73818. if( !pBlob ) goto blob_open_out;
  73819. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  73820. if( !pParse ) goto blob_open_out;
  73821. do {
  73822. memset(pParse, 0, sizeof(Parse));
  73823. pParse->db = db;
  73824. sqlite3DbFree(db, zErr);
  73825. zErr = 0;
  73826. sqlite3BtreeEnterAll(db);
  73827. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  73828. if( pTab && IsVirtual(pTab) ){
  73829. pTab = 0;
  73830. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  73831. }
  73832. if( pTab && !HasRowid(pTab) ){
  73833. pTab = 0;
  73834. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  73835. }
  73836. #ifndef SQLITE_OMIT_VIEW
  73837. if( pTab && pTab->pSelect ){
  73838. pTab = 0;
  73839. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  73840. }
  73841. #endif
  73842. if( !pTab ){
  73843. if( pParse->zErrMsg ){
  73844. sqlite3DbFree(db, zErr);
  73845. zErr = pParse->zErrMsg;
  73846. pParse->zErrMsg = 0;
  73847. }
  73848. rc = SQLITE_ERROR;
  73849. sqlite3BtreeLeaveAll(db);
  73850. goto blob_open_out;
  73851. }
  73852. /* Now search pTab for the exact column. */
  73853. for(iCol=0; iCol<pTab->nCol; iCol++) {
  73854. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  73855. break;
  73856. }
  73857. }
  73858. if( iCol==pTab->nCol ){
  73859. sqlite3DbFree(db, zErr);
  73860. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  73861. rc = SQLITE_ERROR;
  73862. sqlite3BtreeLeaveAll(db);
  73863. goto blob_open_out;
  73864. }
  73865. /* If the value is being opened for writing, check that the
  73866. ** column is not indexed, and that it is not part of a foreign key.
  73867. ** It is against the rules to open a column to which either of these
  73868. ** descriptions applies for writing. */
  73869. if( flags ){
  73870. const char *zFault = 0;
  73871. Index *pIdx;
  73872. #ifndef SQLITE_OMIT_FOREIGN_KEY
  73873. if( db->flags&SQLITE_ForeignKeys ){
  73874. /* Check that the column is not part of an FK child key definition. It
  73875. ** is not necessary to check if it is part of a parent key, as parent
  73876. ** key columns must be indexed. The check below will pick up this
  73877. ** case. */
  73878. FKey *pFKey;
  73879. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  73880. int j;
  73881. for(j=0; j<pFKey->nCol; j++){
  73882. if( pFKey->aCol[j].iFrom==iCol ){
  73883. zFault = "foreign key";
  73884. }
  73885. }
  73886. }
  73887. }
  73888. #endif
  73889. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  73890. int j;
  73891. for(j=0; j<pIdx->nKeyCol; j++){
  73892. if( pIdx->aiColumn[j]==iCol ){
  73893. zFault = "indexed";
  73894. }
  73895. }
  73896. }
  73897. if( zFault ){
  73898. sqlite3DbFree(db, zErr);
  73899. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  73900. rc = SQLITE_ERROR;
  73901. sqlite3BtreeLeaveAll(db);
  73902. goto blob_open_out;
  73903. }
  73904. }
  73905. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  73906. assert( pBlob->pStmt || db->mallocFailed );
  73907. if( pBlob->pStmt ){
  73908. Vdbe *v = (Vdbe *)pBlob->pStmt;
  73909. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  73910. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
  73911. pTab->pSchema->schema_cookie,
  73912. pTab->pSchema->iGeneration);
  73913. sqlite3VdbeChangeP5(v, 1);
  73914. sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  73915. /* Make sure a mutex is held on the table to be accessed */
  73916. sqlite3VdbeUsesBtree(v, iDb);
  73917. /* Configure the OP_TableLock instruction */
  73918. #ifdef SQLITE_OMIT_SHARED_CACHE
  73919. sqlite3VdbeChangeToNoop(v, 1);
  73920. #else
  73921. sqlite3VdbeChangeP1(v, 1, iDb);
  73922. sqlite3VdbeChangeP2(v, 1, pTab->tnum);
  73923. sqlite3VdbeChangeP3(v, 1, flags);
  73924. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  73925. #endif
  73926. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  73927. ** parameter of the other to pTab->tnum. */
  73928. sqlite3VdbeChangeToNoop(v, 3 - flags);
  73929. sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
  73930. sqlite3VdbeChangeP3(v, 2 + flags, iDb);
  73931. /* Configure the number of columns. Configure the cursor to
  73932. ** think that the table has one more column than it really
  73933. ** does. An OP_Column to retrieve this imaginary column will
  73934. ** always return an SQL NULL. This is useful because it means
  73935. ** we can invoke OP_Column to fill in the vdbe cursors type
  73936. ** and offset cache without causing any IO.
  73937. */
  73938. sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  73939. sqlite3VdbeChangeP2(v, 6, pTab->nCol);
  73940. if( !db->mallocFailed ){
  73941. pParse->nVar = 1;
  73942. pParse->nMem = 1;
  73943. pParse->nTab = 1;
  73944. sqlite3VdbeMakeReady(v, pParse);
  73945. }
  73946. }
  73947. pBlob->flags = flags;
  73948. pBlob->iCol = iCol;
  73949. pBlob->db = db;
  73950. sqlite3BtreeLeaveAll(db);
  73951. if( db->mallocFailed ){
  73952. goto blob_open_out;
  73953. }
  73954. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  73955. rc = blobSeekToRow(pBlob, iRow, &zErr);
  73956. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  73957. blob_open_out:
  73958. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  73959. *ppBlob = (sqlite3_blob *)pBlob;
  73960. }else{
  73961. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  73962. sqlite3DbFree(db, pBlob);
  73963. }
  73964. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  73965. sqlite3DbFree(db, zErr);
  73966. sqlite3ParserReset(pParse);
  73967. sqlite3StackFree(db, pParse);
  73968. rc = sqlite3ApiExit(db, rc);
  73969. sqlite3_mutex_leave(db->mutex);
  73970. return rc;
  73971. }
  73972. /*
  73973. ** Close a blob handle that was previously created using
  73974. ** sqlite3_blob_open().
  73975. */
  73976. SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
  73977. Incrblob *p = (Incrblob *)pBlob;
  73978. int rc;
  73979. sqlite3 *db;
  73980. if( p ){
  73981. db = p->db;
  73982. sqlite3_mutex_enter(db->mutex);
  73983. rc = sqlite3_finalize(p->pStmt);
  73984. sqlite3DbFree(db, p);
  73985. sqlite3_mutex_leave(db->mutex);
  73986. }else{
  73987. rc = SQLITE_OK;
  73988. }
  73989. return rc;
  73990. }
  73991. /*
  73992. ** Perform a read or write operation on a blob
  73993. */
  73994. static int blobReadWrite(
  73995. sqlite3_blob *pBlob,
  73996. void *z,
  73997. int n,
  73998. int iOffset,
  73999. int (*xCall)(BtCursor*, u32, u32, void*)
  74000. ){
  74001. int rc;
  74002. Incrblob *p = (Incrblob *)pBlob;
  74003. Vdbe *v;
  74004. sqlite3 *db;
  74005. if( p==0 ) return SQLITE_MISUSE_BKPT;
  74006. db = p->db;
  74007. sqlite3_mutex_enter(db->mutex);
  74008. v = (Vdbe*)p->pStmt;
  74009. if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
  74010. /* Request is out of range. Return a transient error. */
  74011. rc = SQLITE_ERROR;
  74012. }else if( v==0 ){
  74013. /* If there is no statement handle, then the blob-handle has
  74014. ** already been invalidated. Return SQLITE_ABORT in this case.
  74015. */
  74016. rc = SQLITE_ABORT;
  74017. }else{
  74018. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  74019. ** returned, clean-up the statement handle.
  74020. */
  74021. assert( db == v->db );
  74022. sqlite3BtreeEnterCursor(p->pCsr);
  74023. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  74024. sqlite3BtreeLeaveCursor(p->pCsr);
  74025. if( rc==SQLITE_ABORT ){
  74026. sqlite3VdbeFinalize(v);
  74027. p->pStmt = 0;
  74028. }else{
  74029. v->rc = rc;
  74030. }
  74031. }
  74032. sqlite3Error(db, rc);
  74033. rc = sqlite3ApiExit(db, rc);
  74034. sqlite3_mutex_leave(db->mutex);
  74035. return rc;
  74036. }
  74037. /*
  74038. ** Read data from a blob handle.
  74039. */
  74040. SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  74041. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  74042. }
  74043. /*
  74044. ** Write data to a blob handle.
  74045. */
  74046. SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  74047. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  74048. }
  74049. /*
  74050. ** Query a blob handle for the size of the data.
  74051. **
  74052. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  74053. ** so no mutex is required for access.
  74054. */
  74055. SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
  74056. Incrblob *p = (Incrblob *)pBlob;
  74057. return (p && p->pStmt) ? p->nByte : 0;
  74058. }
  74059. /*
  74060. ** Move an existing blob handle to point to a different row of the same
  74061. ** database table.
  74062. **
  74063. ** If an error occurs, or if the specified row does not exist or does not
  74064. ** contain a blob or text value, then an error code is returned and the
  74065. ** database handle error code and message set. If this happens, then all
  74066. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  74067. ** immediately return SQLITE_ABORT.
  74068. */
  74069. SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  74070. int rc;
  74071. Incrblob *p = (Incrblob *)pBlob;
  74072. sqlite3 *db;
  74073. if( p==0 ) return SQLITE_MISUSE_BKPT;
  74074. db = p->db;
  74075. sqlite3_mutex_enter(db->mutex);
  74076. if( p->pStmt==0 ){
  74077. /* If there is no statement handle, then the blob-handle has
  74078. ** already been invalidated. Return SQLITE_ABORT in this case.
  74079. */
  74080. rc = SQLITE_ABORT;
  74081. }else{
  74082. char *zErr;
  74083. rc = blobSeekToRow(p, iRow, &zErr);
  74084. if( rc!=SQLITE_OK ){
  74085. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  74086. sqlite3DbFree(db, zErr);
  74087. }
  74088. assert( rc!=SQLITE_SCHEMA );
  74089. }
  74090. rc = sqlite3ApiExit(db, rc);
  74091. assert( rc==SQLITE_OK || p->pStmt==0 );
  74092. sqlite3_mutex_leave(db->mutex);
  74093. return rc;
  74094. }
  74095. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  74096. /************** End of vdbeblob.c ********************************************/
  74097. /************** Begin file vdbesort.c ****************************************/
  74098. /*
  74099. ** 2011-07-09
  74100. **
  74101. ** The author disclaims copyright to this source code. In place of
  74102. ** a legal notice, here is a blessing:
  74103. **
  74104. ** May you do good and not evil.
  74105. ** May you find forgiveness for yourself and forgive others.
  74106. ** May you share freely, never taking more than you give.
  74107. **
  74108. *************************************************************************
  74109. ** This file contains code for the VdbeSorter object, used in concert with
  74110. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  74111. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  74112. ** using indexes and without LIMIT clauses.
  74113. **
  74114. ** The VdbeSorter object implements a multi-threaded external merge sort
  74115. ** algorithm that is efficient even if the number of elements being sorted
  74116. ** exceeds the available memory.
  74117. **
  74118. ** Here is the (internal, non-API) interface between this module and the
  74119. ** rest of the SQLite system:
  74120. **
  74121. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  74122. **
  74123. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  74124. ** object. The row is a binary blob in the
  74125. ** OP_MakeRecord format that contains both
  74126. ** the ORDER BY key columns and result columns
  74127. ** in the case of a SELECT w/ ORDER BY, or
  74128. ** the complete record for an index entry
  74129. ** in the case of a CREATE INDEX.
  74130. **
  74131. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  74132. ** Position the read cursor on the
  74133. ** first sorted element.
  74134. **
  74135. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  74136. ** element.
  74137. **
  74138. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  74139. ** row currently under the read cursor.
  74140. **
  74141. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  74142. ** currently under the read cursor against
  74143. ** another binary blob X and report if
  74144. ** X is strictly less than the read cursor.
  74145. ** Used to enforce uniqueness in a
  74146. ** CREATE UNIQUE INDEX statement.
  74147. **
  74148. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  74149. ** all resources.
  74150. **
  74151. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  74152. ** is like Close() followed by Init() only
  74153. ** much faster.
  74154. **
  74155. ** The interfaces above must be called in a particular order. Write() can
  74156. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  74157. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  74158. **
  74159. ** Init()
  74160. ** for each record: Write()
  74161. ** Rewind()
  74162. ** Rowkey()/Compare()
  74163. ** Next()
  74164. ** Close()
  74165. **
  74166. ** Algorithm:
  74167. **
  74168. ** Records passed to the sorter via calls to Write() are initially held
  74169. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  74170. ** a threshold, when Rewind() is called the set of records is sorted using
  74171. ** an in-memory merge sort. In this case, no temporary files are required
  74172. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  74173. ** directly from main memory.
  74174. **
  74175. ** If the amount of space used to store records in main memory exceeds the
  74176. ** threshold, then the set of records currently in memory are sorted and
  74177. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  74178. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  74179. ** of PMAs may be created by merging existing PMAs together - for example
  74180. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  74181. **
  74182. ** The threshold for the amount of main memory to use before flushing
  74183. ** records to a PMA is roughly the same as the limit configured for the
  74184. ** page-cache of the main database. Specifically, the threshold is set to
  74185. ** the value returned by "PRAGMA main.page_size" multipled by
  74186. ** that returned by "PRAGMA main.cache_size", in bytes.
  74187. **
  74188. ** If the sorter is running in single-threaded mode, then all PMAs generated
  74189. ** are appended to a single temporary file. Or, if the sorter is running in
  74190. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  74191. ** N is the configured number of worker threads. In this case, instead of
  74192. ** sorting the records and writing the PMA to a temporary file itself, the
  74193. ** calling thread usually launches a worker thread to do so. Except, if
  74194. ** there are already N worker threads running, the main thread does the work
  74195. ** itself.
  74196. **
  74197. ** The sorter is running in multi-threaded mode if (a) the library was built
  74198. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  74199. ** than zero, and (b) worker threads have been enabled at runtime by calling
  74200. ** "PRAGMA threads=N" with some value of N greater than 0.
  74201. **
  74202. ** When Rewind() is called, any data remaining in memory is flushed to a
  74203. ** final PMA. So at this point the data is stored in some number of sorted
  74204. ** PMAs within temporary files on disk.
  74205. **
  74206. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  74207. ** sorter is running in single-threaded mode, then these PMAs are merged
  74208. ** incrementally as keys are retreived from the sorter by the VDBE. The
  74209. ** MergeEngine object, described in further detail below, performs this
  74210. ** merge.
  74211. **
  74212. ** Or, if running in multi-threaded mode, then a background thread is
  74213. ** launched to merge the existing PMAs. Once the background thread has
  74214. ** merged T bytes of data into a single sorted PMA, the main thread
  74215. ** begins reading keys from that PMA while the background thread proceeds
  74216. ** with merging the next T bytes of data. And so on.
  74217. **
  74218. ** Parameter T is set to half the value of the memory threshold used
  74219. ** by Write() above to determine when to create a new PMA.
  74220. **
  74221. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  74222. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  74223. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  74224. ** disk are merged together. Then T bytes of data from the second set, and
  74225. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  74226. ** PMAs at a time. This done is to improve locality.
  74227. **
  74228. ** If running in multi-threaded mode and there are more than
  74229. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  74230. ** than one background thread may be created. Specifically, there may be
  74231. ** one background thread for each temporary file on disk, and one background
  74232. ** thread to merge the output of each of the others to a single PMA for
  74233. ** the main thread to read from.
  74234. */
  74235. /* #include "sqliteInt.h" */
  74236. /* #include "vdbeInt.h" */
  74237. /*
  74238. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  74239. ** messages to stderr that may be helpful in understanding the performance
  74240. ** characteristics of the sorter in multi-threaded mode.
  74241. */
  74242. #if 0
  74243. # define SQLITE_DEBUG_SORTER_THREADS 1
  74244. #endif
  74245. /*
  74246. ** Hard-coded maximum amount of data to accumulate in memory before flushing
  74247. ** to a level 0 PMA. The purpose of this limit is to prevent various integer
  74248. ** overflows. 512MiB.
  74249. */
  74250. #define SQLITE_MAX_PMASZ (1<<29)
  74251. /*
  74252. ** Private objects used by the sorter
  74253. */
  74254. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  74255. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  74256. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  74257. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  74258. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  74259. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  74260. typedef struct SorterList SorterList; /* In-memory list of records */
  74261. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  74262. /*
  74263. ** A container for a temp file handle and the current amount of data
  74264. ** stored in the file.
  74265. */
  74266. struct SorterFile {
  74267. sqlite3_file *pFd; /* File handle */
  74268. i64 iEof; /* Bytes of data stored in pFd */
  74269. };
  74270. /*
  74271. ** An in-memory list of objects to be sorted.
  74272. **
  74273. ** If aMemory==0 then each object is allocated separately and the objects
  74274. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  74275. ** are stored in the aMemory[] bulk memory, one right after the other, and
  74276. ** are connected using SorterRecord.u.iNext.
  74277. */
  74278. struct SorterList {
  74279. SorterRecord *pList; /* Linked list of records */
  74280. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  74281. int szPMA; /* Size of pList as PMA in bytes */
  74282. };
  74283. /*
  74284. ** The MergeEngine object is used to combine two or more smaller PMAs into
  74285. ** one big PMA using a merge operation. Separate PMAs all need to be
  74286. ** combined into one big PMA in order to be able to step through the sorted
  74287. ** records in order.
  74288. **
  74289. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  74290. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  74291. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  74292. ** For the purposes of the paragraphs below, we assume that the array is
  74293. ** actually N elements in size, where N is the smallest power of 2 greater
  74294. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  74295. ** are treated as if they are empty (always at EOF).
  74296. **
  74297. ** The aTree[] array is also N elements in size. The value of N is stored in
  74298. ** the MergeEngine.nTree variable.
  74299. **
  74300. ** The final (N/2) elements of aTree[] contain the results of comparing
  74301. ** pairs of PMA keys together. Element i contains the result of
  74302. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  74303. ** aTree element is set to the index of it.
  74304. **
  74305. ** For the purposes of this comparison, EOF is considered greater than any
  74306. ** other key value. If the keys are equal (only possible with two EOF
  74307. ** values), it doesn't matter which index is stored.
  74308. **
  74309. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  74310. ** above contains the index of the smallest of each block of 4 PmaReaders
  74311. ** And so on. So that aTree[1] contains the index of the PmaReader that
  74312. ** currently points to the smallest key value. aTree[0] is unused.
  74313. **
  74314. ** Example:
  74315. **
  74316. ** aReadr[0] -> Banana
  74317. ** aReadr[1] -> Feijoa
  74318. ** aReadr[2] -> Elderberry
  74319. ** aReadr[3] -> Currant
  74320. ** aReadr[4] -> Grapefruit
  74321. ** aReadr[5] -> Apple
  74322. ** aReadr[6] -> Durian
  74323. ** aReadr[7] -> EOF
  74324. **
  74325. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  74326. **
  74327. ** The current element is "Apple" (the value of the key indicated by
  74328. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  74329. ** be advanced to the next key in its segment. Say the next key is
  74330. ** "Eggplant":
  74331. **
  74332. ** aReadr[5] -> Eggplant
  74333. **
  74334. ** The contents of aTree[] are updated first by comparing the new PmaReader
  74335. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  74336. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  74337. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  74338. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  74339. ** so the value written into element 1 of the array is 0. As follows:
  74340. **
  74341. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  74342. **
  74343. ** In other words, each time we advance to the next sorter element, log2(N)
  74344. ** key comparison operations are required, where N is the number of segments
  74345. ** being merged (rounded up to the next power of 2).
  74346. */
  74347. struct MergeEngine {
  74348. int nTree; /* Used size of aTree/aReadr (power of 2) */
  74349. SortSubtask *pTask; /* Used by this thread only */
  74350. int *aTree; /* Current state of incremental merge */
  74351. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  74352. };
  74353. /*
  74354. ** This object represents a single thread of control in a sort operation.
  74355. ** Exactly VdbeSorter.nTask instances of this object are allocated
  74356. ** as part of each VdbeSorter object. Instances are never allocated any
  74357. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  74358. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  74359. ** single-threaded operation, there is exactly one instance of this object
  74360. ** and for multi-threaded operation there are two or more instances.
  74361. **
  74362. ** Essentially, this structure contains all those fields of the VdbeSorter
  74363. ** structure for which each thread requires a separate instance. For example,
  74364. ** each thread requries its own UnpackedRecord object to unpack records in
  74365. ** as part of comparison operations.
  74366. **
  74367. ** Before a background thread is launched, variable bDone is set to 0. Then,
  74368. ** right before it exits, the thread itself sets bDone to 1. This is used for
  74369. ** two purposes:
  74370. **
  74371. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  74372. ** attempt to select a SortSubtask for which there is not already an
  74373. ** active background thread (since doing so causes the main thread
  74374. ** to block until it finishes).
  74375. **
  74376. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  74377. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  74378. ** block provoke debugging output.
  74379. **
  74380. ** In both cases, the effects of the main thread seeing (bDone==0) even
  74381. ** after the thread has finished are not dire. So we don't worry about
  74382. ** memory barriers and such here.
  74383. */
  74384. typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
  74385. struct SortSubtask {
  74386. SQLiteThread *pThread; /* Background thread, if any */
  74387. int bDone; /* Set if thread is finished but not joined */
  74388. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  74389. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  74390. SorterList list; /* List for thread to write to a PMA */
  74391. int nPMA; /* Number of PMAs currently in file */
  74392. SorterCompare xCompare; /* Compare function to use */
  74393. SorterFile file; /* Temp file for level-0 PMAs */
  74394. SorterFile file2; /* Space for other PMAs */
  74395. };
  74396. /*
  74397. ** Main sorter structure. A single instance of this is allocated for each
  74398. ** sorter cursor created by the VDBE.
  74399. **
  74400. ** mxKeysize:
  74401. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  74402. ** this variable is updated so as to be set to the size on disk of the
  74403. ** largest record in the sorter.
  74404. */
  74405. struct VdbeSorter {
  74406. int mnPmaSize; /* Minimum PMA size, in bytes */
  74407. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  74408. int mxKeysize; /* Largest serialized key seen so far */
  74409. int pgsz; /* Main database page size */
  74410. PmaReader *pReader; /* Readr data from here after Rewind() */
  74411. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  74412. sqlite3 *db; /* Database connection */
  74413. KeyInfo *pKeyInfo; /* How to compare records */
  74414. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  74415. SorterList list; /* List of in-memory records */
  74416. int iMemory; /* Offset of free space in list.aMemory */
  74417. int nMemory; /* Size of list.aMemory allocation in bytes */
  74418. u8 bUsePMA; /* True if one or more PMAs created */
  74419. u8 bUseThreads; /* True to use background threads */
  74420. u8 iPrev; /* Previous thread used to flush PMA */
  74421. u8 nTask; /* Size of aTask[] array */
  74422. u8 typeMask;
  74423. SortSubtask aTask[1]; /* One or more subtasks */
  74424. };
  74425. #define SORTER_TYPE_INTEGER 0x01
  74426. #define SORTER_TYPE_TEXT 0x02
  74427. /*
  74428. ** An instance of the following object is used to read records out of a
  74429. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  74430. ** aKey might point into aMap or into aBuffer. If neither of those locations
  74431. ** contain a contiguous representation of the key, then aAlloc is allocated
  74432. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  74433. **
  74434. ** pFd==0 at EOF.
  74435. */
  74436. struct PmaReader {
  74437. i64 iReadOff; /* Current read offset */
  74438. i64 iEof; /* 1 byte past EOF for this PmaReader */
  74439. int nAlloc; /* Bytes of space at aAlloc */
  74440. int nKey; /* Number of bytes in key */
  74441. sqlite3_file *pFd; /* File handle we are reading from */
  74442. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  74443. u8 *aKey; /* Pointer to current key */
  74444. u8 *aBuffer; /* Current read buffer */
  74445. int nBuffer; /* Size of read buffer in bytes */
  74446. u8 *aMap; /* Pointer to mapping of entire file */
  74447. IncrMerger *pIncr; /* Incremental merger */
  74448. };
  74449. /*
  74450. ** Normally, a PmaReader object iterates through an existing PMA stored
  74451. ** within a temp file. However, if the PmaReader.pIncr variable points to
  74452. ** an object of the following type, it may be used to iterate/merge through
  74453. ** multiple PMAs simultaneously.
  74454. **
  74455. ** There are two types of IncrMerger object - single (bUseThread==0) and
  74456. ** multi-threaded (bUseThread==1).
  74457. **
  74458. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  74459. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  74460. ** size. When the IncrMerger is initialized, it reads enough data from
  74461. ** pMerger to populate aFile[0]. It then sets variables within the
  74462. ** corresponding PmaReader object to read from that file and kicks off
  74463. ** a background thread to populate aFile[1] with the next mxSz bytes of
  74464. ** sorted record data from pMerger.
  74465. **
  74466. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  74467. ** background thread has finished populating aFile[1]. It then exchanges
  74468. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  74469. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  74470. ** another background thread to populate the new aFile[1]. And so on, until
  74471. ** the contents of pMerger are exhausted.
  74472. **
  74473. ** A single-threaded IncrMerger does not open any temporary files of its
  74474. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  74475. ** at offset iStartOff of file pTask->file2. And instead of using a
  74476. ** background thread to prepare data for the PmaReader, with a single
  74477. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  74478. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  74479. ** of data.
  74480. */
  74481. struct IncrMerger {
  74482. SortSubtask *pTask; /* Task that owns this merger */
  74483. MergeEngine *pMerger; /* Merge engine thread reads data from */
  74484. i64 iStartOff; /* Offset to start writing file at */
  74485. int mxSz; /* Maximum bytes of data to store */
  74486. int bEof; /* Set to true when merge is finished */
  74487. int bUseThread; /* True to use a bg thread for this object */
  74488. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  74489. };
  74490. /*
  74491. ** An instance of this object is used for writing a PMA.
  74492. **
  74493. ** The PMA is written one record at a time. Each record is of an arbitrary
  74494. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  74495. ** each block is aligned on a page boundary. This object caches writes to
  74496. ** the PMA so that aligned, page-size blocks are written.
  74497. */
  74498. struct PmaWriter {
  74499. int eFWErr; /* Non-zero if in an error state */
  74500. u8 *aBuffer; /* Pointer to write buffer */
  74501. int nBuffer; /* Size of write buffer in bytes */
  74502. int iBufStart; /* First byte of buffer to write */
  74503. int iBufEnd; /* Last byte of buffer to write */
  74504. i64 iWriteOff; /* Offset of start of buffer in file */
  74505. sqlite3_file *pFd; /* File handle to write to */
  74506. };
  74507. /*
  74508. ** This object is the header on a single record while that record is being
  74509. ** held in memory and prior to being written out as part of a PMA.
  74510. **
  74511. ** How the linked list is connected depends on how memory is being managed
  74512. ** by this module. If using a separate allocation for each in-memory record
  74513. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  74514. ** SorterRecord.u.pNext pointers.
  74515. **
  74516. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  74517. ** then while records are being accumulated the list is linked using the
  74518. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  74519. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  74520. ** has finished passing records to the sorter, or when the in-memory buffer
  74521. ** is full, the list is sorted. As part of the sorting process, it is
  74522. ** converted to use the SorterRecord.u.pNext pointers. See function
  74523. ** vdbeSorterSort() for details.
  74524. */
  74525. struct SorterRecord {
  74526. int nVal; /* Size of the record in bytes */
  74527. union {
  74528. SorterRecord *pNext; /* Pointer to next record in list */
  74529. int iNext; /* Offset within aMemory of next record */
  74530. } u;
  74531. /* The data for the record immediately follows this header */
  74532. };
  74533. /* Return a pointer to the buffer containing the record data for SorterRecord
  74534. ** object p. Should be used as if:
  74535. **
  74536. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  74537. */
  74538. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  74539. /* Maximum number of PMAs that a single MergeEngine can merge */
  74540. #define SORTER_MAX_MERGE_COUNT 16
  74541. static int vdbeIncrSwap(IncrMerger*);
  74542. static void vdbeIncrFree(IncrMerger *);
  74543. /*
  74544. ** Free all memory belonging to the PmaReader object passed as the
  74545. ** argument. All structure fields are set to zero before returning.
  74546. */
  74547. static void vdbePmaReaderClear(PmaReader *pReadr){
  74548. sqlite3_free(pReadr->aAlloc);
  74549. sqlite3_free(pReadr->aBuffer);
  74550. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  74551. vdbeIncrFree(pReadr->pIncr);
  74552. memset(pReadr, 0, sizeof(PmaReader));
  74553. }
  74554. /*
  74555. ** Read the next nByte bytes of data from the PMA p.
  74556. ** If successful, set *ppOut to point to a buffer containing the data
  74557. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  74558. ** error code.
  74559. **
  74560. ** The buffer returned in *ppOut is only valid until the
  74561. ** next call to this function.
  74562. */
  74563. static int vdbePmaReadBlob(
  74564. PmaReader *p, /* PmaReader from which to take the blob */
  74565. int nByte, /* Bytes of data to read */
  74566. u8 **ppOut /* OUT: Pointer to buffer containing data */
  74567. ){
  74568. int iBuf; /* Offset within buffer to read from */
  74569. int nAvail; /* Bytes of data available in buffer */
  74570. if( p->aMap ){
  74571. *ppOut = &p->aMap[p->iReadOff];
  74572. p->iReadOff += nByte;
  74573. return SQLITE_OK;
  74574. }
  74575. assert( p->aBuffer );
  74576. /* If there is no more data to be read from the buffer, read the next
  74577. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  74578. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  74579. iBuf = p->iReadOff % p->nBuffer;
  74580. if( iBuf==0 ){
  74581. int nRead; /* Bytes to read from disk */
  74582. int rc; /* sqlite3OsRead() return code */
  74583. /* Determine how many bytes of data to read. */
  74584. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  74585. nRead = p->nBuffer;
  74586. }else{
  74587. nRead = (int)(p->iEof - p->iReadOff);
  74588. }
  74589. assert( nRead>0 );
  74590. /* Readr data from the file. Return early if an error occurs. */
  74591. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  74592. assert( rc!=SQLITE_IOERR_SHORT_READ );
  74593. if( rc!=SQLITE_OK ) return rc;
  74594. }
  74595. nAvail = p->nBuffer - iBuf;
  74596. if( nByte<=nAvail ){
  74597. /* The requested data is available in the in-memory buffer. In this
  74598. ** case there is no need to make a copy of the data, just return a
  74599. ** pointer into the buffer to the caller. */
  74600. *ppOut = &p->aBuffer[iBuf];
  74601. p->iReadOff += nByte;
  74602. }else{
  74603. /* The requested data is not all available in the in-memory buffer.
  74604. ** In this case, allocate space at p->aAlloc[] to copy the requested
  74605. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  74606. int nRem; /* Bytes remaining to copy */
  74607. /* Extend the p->aAlloc[] allocation if required. */
  74608. if( p->nAlloc<nByte ){
  74609. u8 *aNew;
  74610. int nNew = MAX(128, p->nAlloc*2);
  74611. while( nByte>nNew ) nNew = nNew*2;
  74612. aNew = sqlite3Realloc(p->aAlloc, nNew);
  74613. if( !aNew ) return SQLITE_NOMEM;
  74614. p->nAlloc = nNew;
  74615. p->aAlloc = aNew;
  74616. }
  74617. /* Copy as much data as is available in the buffer into the start of
  74618. ** p->aAlloc[]. */
  74619. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  74620. p->iReadOff += nAvail;
  74621. nRem = nByte - nAvail;
  74622. /* The following loop copies up to p->nBuffer bytes per iteration into
  74623. ** the p->aAlloc[] buffer. */
  74624. while( nRem>0 ){
  74625. int rc; /* vdbePmaReadBlob() return code */
  74626. int nCopy; /* Number of bytes to copy */
  74627. u8 *aNext; /* Pointer to buffer to copy data from */
  74628. nCopy = nRem;
  74629. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  74630. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  74631. if( rc!=SQLITE_OK ) return rc;
  74632. assert( aNext!=p->aAlloc );
  74633. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  74634. nRem -= nCopy;
  74635. }
  74636. *ppOut = p->aAlloc;
  74637. }
  74638. return SQLITE_OK;
  74639. }
  74640. /*
  74641. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  74642. ** the value read.
  74643. */
  74644. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  74645. int iBuf;
  74646. if( p->aMap ){
  74647. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  74648. }else{
  74649. iBuf = p->iReadOff % p->nBuffer;
  74650. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  74651. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  74652. }else{
  74653. u8 aVarint[16], *a;
  74654. int i = 0, rc;
  74655. do{
  74656. rc = vdbePmaReadBlob(p, 1, &a);
  74657. if( rc ) return rc;
  74658. aVarint[(i++)&0xf] = a[0];
  74659. }while( (a[0]&0x80)!=0 );
  74660. sqlite3GetVarint(aVarint, pnOut);
  74661. }
  74662. }
  74663. return SQLITE_OK;
  74664. }
  74665. /*
  74666. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  74667. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  74668. ** (because the file is too large or the VFS layer is configured not to use
  74669. ** mmap), return SQLITE_OK and set *pp to NULL.
  74670. **
  74671. ** Or, if an error occurs, return an SQLite error code. The final value of
  74672. ** *pp is undefined in this case.
  74673. */
  74674. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  74675. int rc = SQLITE_OK;
  74676. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  74677. sqlite3_file *pFd = pFile->pFd;
  74678. if( pFd->pMethods->iVersion>=3 ){
  74679. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  74680. testcase( rc!=SQLITE_OK );
  74681. }
  74682. }
  74683. return rc;
  74684. }
  74685. /*
  74686. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  74687. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  74688. ** if successful, or an SQLite error code if an error occurs.
  74689. */
  74690. static int vdbePmaReaderSeek(
  74691. SortSubtask *pTask, /* Task context */
  74692. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  74693. SorterFile *pFile, /* Sorter file to read from */
  74694. i64 iOff /* Offset in pFile */
  74695. ){
  74696. int rc = SQLITE_OK;
  74697. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  74698. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  74699. if( pReadr->aMap ){
  74700. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  74701. pReadr->aMap = 0;
  74702. }
  74703. pReadr->iReadOff = iOff;
  74704. pReadr->iEof = pFile->iEof;
  74705. pReadr->pFd = pFile->pFd;
  74706. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  74707. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  74708. int pgsz = pTask->pSorter->pgsz;
  74709. int iBuf = pReadr->iReadOff % pgsz;
  74710. if( pReadr->aBuffer==0 ){
  74711. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  74712. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
  74713. pReadr->nBuffer = pgsz;
  74714. }
  74715. if( rc==SQLITE_OK && iBuf ){
  74716. int nRead = pgsz - iBuf;
  74717. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  74718. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  74719. }
  74720. rc = sqlite3OsRead(
  74721. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  74722. );
  74723. testcase( rc!=SQLITE_OK );
  74724. }
  74725. }
  74726. return rc;
  74727. }
  74728. /*
  74729. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  74730. ** no error occurs, or an SQLite error code if one does.
  74731. */
  74732. static int vdbePmaReaderNext(PmaReader *pReadr){
  74733. int rc = SQLITE_OK; /* Return Code */
  74734. u64 nRec = 0; /* Size of record in bytes */
  74735. if( pReadr->iReadOff>=pReadr->iEof ){
  74736. IncrMerger *pIncr = pReadr->pIncr;
  74737. int bEof = 1;
  74738. if( pIncr ){
  74739. rc = vdbeIncrSwap(pIncr);
  74740. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  74741. rc = vdbePmaReaderSeek(
  74742. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  74743. );
  74744. bEof = 0;
  74745. }
  74746. }
  74747. if( bEof ){
  74748. /* This is an EOF condition */
  74749. vdbePmaReaderClear(pReadr);
  74750. testcase( rc!=SQLITE_OK );
  74751. return rc;
  74752. }
  74753. }
  74754. if( rc==SQLITE_OK ){
  74755. rc = vdbePmaReadVarint(pReadr, &nRec);
  74756. }
  74757. if( rc==SQLITE_OK ){
  74758. pReadr->nKey = (int)nRec;
  74759. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  74760. testcase( rc!=SQLITE_OK );
  74761. }
  74762. return rc;
  74763. }
  74764. /*
  74765. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  74766. ** starting at offset iStart and ending at offset iEof-1. This function
  74767. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  74768. ** PMA is empty).
  74769. **
  74770. ** If the pnByte parameter is NULL, then it is assumed that the file
  74771. ** contains a single PMA, and that that PMA omits the initial length varint.
  74772. */
  74773. static int vdbePmaReaderInit(
  74774. SortSubtask *pTask, /* Task context */
  74775. SorterFile *pFile, /* Sorter file to read from */
  74776. i64 iStart, /* Start offset in pFile */
  74777. PmaReader *pReadr, /* PmaReader to populate */
  74778. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  74779. ){
  74780. int rc;
  74781. assert( pFile->iEof>iStart );
  74782. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  74783. assert( pReadr->aBuffer==0 );
  74784. assert( pReadr->aMap==0 );
  74785. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  74786. if( rc==SQLITE_OK ){
  74787. u64 nByte; /* Size of PMA in bytes */
  74788. rc = vdbePmaReadVarint(pReadr, &nByte);
  74789. pReadr->iEof = pReadr->iReadOff + nByte;
  74790. *pnByte += nByte;
  74791. }
  74792. if( rc==SQLITE_OK ){
  74793. rc = vdbePmaReaderNext(pReadr);
  74794. }
  74795. return rc;
  74796. }
  74797. /*
  74798. ** A version of vdbeSorterCompare() that assumes that it has already been
  74799. ** determined that the first field of key1 is equal to the first field of
  74800. ** key2.
  74801. */
  74802. static int vdbeSorterCompareTail(
  74803. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  74804. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  74805. const void *pKey1, int nKey1, /* Left side of comparison */
  74806. const void *pKey2, int nKey2 /* Right side of comparison */
  74807. ){
  74808. UnpackedRecord *r2 = pTask->pUnpacked;
  74809. if( *pbKey2Cached==0 ){
  74810. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  74811. *pbKey2Cached = 1;
  74812. }
  74813. return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
  74814. }
  74815. /*
  74816. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  74817. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  74818. ** used by the comparison. Return the result of the comparison.
  74819. **
  74820. ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
  74821. ** it is assumed that (pTask->pUnpacked) contains the unpacked version
  74822. ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
  74823. ** version of key2 and *pbKey2Cached set to true before returning.
  74824. **
  74825. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  74826. ** to SQLITE_NOMEM.
  74827. */
  74828. static int vdbeSorterCompare(
  74829. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  74830. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  74831. const void *pKey1, int nKey1, /* Left side of comparison */
  74832. const void *pKey2, int nKey2 /* Right side of comparison */
  74833. ){
  74834. UnpackedRecord *r2 = pTask->pUnpacked;
  74835. if( !*pbKey2Cached ){
  74836. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  74837. *pbKey2Cached = 1;
  74838. }
  74839. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  74840. }
  74841. /*
  74842. ** A specially optimized version of vdbeSorterCompare() that assumes that
  74843. ** the first field of each key is a TEXT value and that the collation
  74844. ** sequence to compare them with is BINARY.
  74845. */
  74846. static int vdbeSorterCompareText(
  74847. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  74848. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  74849. const void *pKey1, int nKey1, /* Left side of comparison */
  74850. const void *pKey2, int nKey2 /* Right side of comparison */
  74851. ){
  74852. const u8 * const p1 = (const u8 * const)pKey1;
  74853. const u8 * const p2 = (const u8 * const)pKey2;
  74854. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  74855. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  74856. int n1;
  74857. int n2;
  74858. int res;
  74859. getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
  74860. getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
  74861. res = memcmp(v1, v2, MIN(n1, n2));
  74862. if( res==0 ){
  74863. res = n1 - n2;
  74864. }
  74865. if( res==0 ){
  74866. if( pTask->pSorter->pKeyInfo->nField>1 ){
  74867. res = vdbeSorterCompareTail(
  74868. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  74869. );
  74870. }
  74871. }else{
  74872. if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  74873. res = res * -1;
  74874. }
  74875. }
  74876. return res;
  74877. }
  74878. /*
  74879. ** A specially optimized version of vdbeSorterCompare() that assumes that
  74880. ** the first field of each key is an INTEGER value.
  74881. */
  74882. static int vdbeSorterCompareInt(
  74883. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  74884. int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
  74885. const void *pKey1, int nKey1, /* Left side of comparison */
  74886. const void *pKey2, int nKey2 /* Right side of comparison */
  74887. ){
  74888. const u8 * const p1 = (const u8 * const)pKey1;
  74889. const u8 * const p2 = (const u8 * const)pKey2;
  74890. const int s1 = p1[1]; /* Left hand serial type */
  74891. const int s2 = p2[1]; /* Right hand serial type */
  74892. const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
  74893. const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
  74894. int res; /* Return value */
  74895. assert( (s1>0 && s1<7) || s1==8 || s1==9 );
  74896. assert( (s2>0 && s2<7) || s2==8 || s2==9 );
  74897. if( s1>7 && s2>7 ){
  74898. res = s1 - s2;
  74899. }else{
  74900. if( s1==s2 ){
  74901. if( (*v1 ^ *v2) & 0x80 ){
  74902. /* The two values have different signs */
  74903. res = (*v1 & 0x80) ? -1 : +1;
  74904. }else{
  74905. /* The two values have the same sign. Compare using memcmp(). */
  74906. static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
  74907. int i;
  74908. res = 0;
  74909. for(i=0; i<aLen[s1]; i++){
  74910. if( (res = v1[i] - v2[i]) ) break;
  74911. }
  74912. }
  74913. }else{
  74914. if( s2>7 ){
  74915. res = +1;
  74916. }else if( s1>7 ){
  74917. res = -1;
  74918. }else{
  74919. res = s1 - s2;
  74920. }
  74921. assert( res!=0 );
  74922. if( res>0 ){
  74923. if( *v1 & 0x80 ) res = -1;
  74924. }else{
  74925. if( *v2 & 0x80 ) res = +1;
  74926. }
  74927. }
  74928. }
  74929. if( res==0 ){
  74930. if( pTask->pSorter->pKeyInfo->nField>1 ){
  74931. res = vdbeSorterCompareTail(
  74932. pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
  74933. );
  74934. }
  74935. }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
  74936. res = res * -1;
  74937. }
  74938. return res;
  74939. }
  74940. /*
  74941. ** Initialize the temporary index cursor just opened as a sorter cursor.
  74942. **
  74943. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  74944. ** to determine the number of fields that should be compared from the
  74945. ** records being sorted. However, if the value passed as argument nField
  74946. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  74947. ** is used instead. This is used when sorting records for a CREATE INDEX
  74948. ** statement. In this case, keys are always delivered to the sorter in
  74949. ** order of the primary key, which happens to be make up the final part
  74950. ** of the records being sorted. So if the sort is stable, there is never
  74951. ** any reason to compare PK fields and they can be ignored for a small
  74952. ** performance boost.
  74953. **
  74954. ** The sorter can guarantee a stable sort when running in single-threaded
  74955. ** mode, but not in multi-threaded mode.
  74956. **
  74957. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  74958. */
  74959. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  74960. sqlite3 *db, /* Database connection (for malloc()) */
  74961. int nField, /* Number of key fields in each record */
  74962. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  74963. ){
  74964. int pgsz; /* Page size of main database */
  74965. int i; /* Used to iterate through aTask[] */
  74966. int mxCache; /* Cache size */
  74967. VdbeSorter *pSorter; /* The new sorter */
  74968. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  74969. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  74970. int sz; /* Size of pSorter in bytes */
  74971. int rc = SQLITE_OK;
  74972. #if SQLITE_MAX_WORKER_THREADS==0
  74973. # define nWorker 0
  74974. #else
  74975. int nWorker;
  74976. #endif
  74977. /* Initialize the upper limit on the number of worker threads */
  74978. #if SQLITE_MAX_WORKER_THREADS>0
  74979. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  74980. nWorker = 0;
  74981. }else{
  74982. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  74983. }
  74984. #endif
  74985. /* Do not allow the total number of threads (main thread + all workers)
  74986. ** to exceed the maximum merge count */
  74987. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  74988. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  74989. nWorker = SORTER_MAX_MERGE_COUNT-1;
  74990. }
  74991. #endif
  74992. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  74993. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  74994. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  74995. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  74996. pCsr->pSorter = pSorter;
  74997. if( pSorter==0 ){
  74998. rc = SQLITE_NOMEM;
  74999. }else{
  75000. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  75001. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  75002. pKeyInfo->db = 0;
  75003. if( nField && nWorker==0 ){
  75004. pKeyInfo->nXField += (pKeyInfo->nField - nField);
  75005. pKeyInfo->nField = nField;
  75006. }
  75007. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  75008. pSorter->nTask = nWorker + 1;
  75009. pSorter->iPrev = nWorker-1;
  75010. pSorter->bUseThreads = (pSorter->nTask>1);
  75011. pSorter->db = db;
  75012. for(i=0; i<pSorter->nTask; i++){
  75013. SortSubtask *pTask = &pSorter->aTask[i];
  75014. pTask->pSorter = pSorter;
  75015. }
  75016. if( !sqlite3TempInMemory(db) ){
  75017. u32 szPma = sqlite3GlobalConfig.szPma;
  75018. pSorter->mnPmaSize = szPma * pgsz;
  75019. mxCache = db->aDb[0].pSchema->cache_size;
  75020. if( mxCache<(int)szPma ) mxCache = (int)szPma;
  75021. pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
  75022. /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
  75023. ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
  75024. ** large heap allocations.
  75025. */
  75026. if( sqlite3GlobalConfig.pScratch==0 ){
  75027. assert( pSorter->iMemory==0 );
  75028. pSorter->nMemory = pgsz;
  75029. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  75030. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
  75031. }
  75032. }
  75033. if( (pKeyInfo->nField+pKeyInfo->nXField)<13
  75034. && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
  75035. ){
  75036. pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
  75037. }
  75038. }
  75039. return rc;
  75040. }
  75041. #undef nWorker /* Defined at the top of this function */
  75042. /*
  75043. ** Free the list of sorted records starting at pRecord.
  75044. */
  75045. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  75046. SorterRecord *p;
  75047. SorterRecord *pNext;
  75048. for(p=pRecord; p; p=pNext){
  75049. pNext = p->u.pNext;
  75050. sqlite3DbFree(db, p);
  75051. }
  75052. }
  75053. /*
  75054. ** Free all resources owned by the object indicated by argument pTask. All
  75055. ** fields of *pTask are zeroed before returning.
  75056. */
  75057. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  75058. sqlite3DbFree(db, pTask->pUnpacked);
  75059. #if SQLITE_MAX_WORKER_THREADS>0
  75060. /* pTask->list.aMemory can only be non-zero if it was handed memory
  75061. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  75062. if( pTask->list.aMemory ){
  75063. sqlite3_free(pTask->list.aMemory);
  75064. }else
  75065. #endif
  75066. {
  75067. assert( pTask->list.aMemory==0 );
  75068. vdbeSorterRecordFree(0, pTask->list.pList);
  75069. }
  75070. if( pTask->file.pFd ){
  75071. sqlite3OsCloseFree(pTask->file.pFd);
  75072. }
  75073. if( pTask->file2.pFd ){
  75074. sqlite3OsCloseFree(pTask->file2.pFd);
  75075. }
  75076. memset(pTask, 0, sizeof(SortSubtask));
  75077. }
  75078. #ifdef SQLITE_DEBUG_SORTER_THREADS
  75079. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  75080. i64 t;
  75081. int iTask = (pTask - pTask->pSorter->aTask);
  75082. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  75083. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  75084. }
  75085. static void vdbeSorterRewindDebug(const char *zEvent){
  75086. i64 t;
  75087. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  75088. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  75089. }
  75090. static void vdbeSorterPopulateDebug(
  75091. SortSubtask *pTask,
  75092. const char *zEvent
  75093. ){
  75094. i64 t;
  75095. int iTask = (pTask - pTask->pSorter->aTask);
  75096. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  75097. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  75098. }
  75099. static void vdbeSorterBlockDebug(
  75100. SortSubtask *pTask,
  75101. int bBlocked,
  75102. const char *zEvent
  75103. ){
  75104. if( bBlocked ){
  75105. i64 t;
  75106. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  75107. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  75108. }
  75109. }
  75110. #else
  75111. # define vdbeSorterWorkDebug(x,y)
  75112. # define vdbeSorterRewindDebug(y)
  75113. # define vdbeSorterPopulateDebug(x,y)
  75114. # define vdbeSorterBlockDebug(x,y,z)
  75115. #endif
  75116. #if SQLITE_MAX_WORKER_THREADS>0
  75117. /*
  75118. ** Join thread pTask->thread.
  75119. */
  75120. static int vdbeSorterJoinThread(SortSubtask *pTask){
  75121. int rc = SQLITE_OK;
  75122. if( pTask->pThread ){
  75123. #ifdef SQLITE_DEBUG_SORTER_THREADS
  75124. int bDone = pTask->bDone;
  75125. #endif
  75126. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  75127. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  75128. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  75129. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  75130. rc = SQLITE_PTR_TO_INT(pRet);
  75131. assert( pTask->bDone==1 );
  75132. pTask->bDone = 0;
  75133. pTask->pThread = 0;
  75134. }
  75135. return rc;
  75136. }
  75137. /*
  75138. ** Launch a background thread to run xTask(pIn).
  75139. */
  75140. static int vdbeSorterCreateThread(
  75141. SortSubtask *pTask, /* Thread will use this task object */
  75142. void *(*xTask)(void*), /* Routine to run in a separate thread */
  75143. void *pIn /* Argument passed into xTask() */
  75144. ){
  75145. assert( pTask->pThread==0 && pTask->bDone==0 );
  75146. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  75147. }
  75148. /*
  75149. ** Join all outstanding threads launched by SorterWrite() to create
  75150. ** level-0 PMAs.
  75151. */
  75152. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  75153. int rc = rcin;
  75154. int i;
  75155. /* This function is always called by the main user thread.
  75156. **
  75157. ** If this function is being called after SorterRewind() has been called,
  75158. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  75159. ** is currently attempt to join one of the other threads. To avoid a race
  75160. ** condition where this thread also attempts to join the same object, join
  75161. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  75162. for(i=pSorter->nTask-1; i>=0; i--){
  75163. SortSubtask *pTask = &pSorter->aTask[i];
  75164. int rc2 = vdbeSorterJoinThread(pTask);
  75165. if( rc==SQLITE_OK ) rc = rc2;
  75166. }
  75167. return rc;
  75168. }
  75169. #else
  75170. # define vdbeSorterJoinAll(x,rcin) (rcin)
  75171. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  75172. #endif
  75173. /*
  75174. ** Allocate a new MergeEngine object capable of handling up to
  75175. ** nReader PmaReader inputs.
  75176. **
  75177. ** nReader is automatically rounded up to the next power of two.
  75178. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  75179. */
  75180. static MergeEngine *vdbeMergeEngineNew(int nReader){
  75181. int N = 2; /* Smallest power of two >= nReader */
  75182. int nByte; /* Total bytes of space to allocate */
  75183. MergeEngine *pNew; /* Pointer to allocated object to return */
  75184. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  75185. while( N<nReader ) N += N;
  75186. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  75187. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  75188. if( pNew ){
  75189. pNew->nTree = N;
  75190. pNew->pTask = 0;
  75191. pNew->aReadr = (PmaReader*)&pNew[1];
  75192. pNew->aTree = (int*)&pNew->aReadr[N];
  75193. }
  75194. return pNew;
  75195. }
  75196. /*
  75197. ** Free the MergeEngine object passed as the only argument.
  75198. */
  75199. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  75200. int i;
  75201. if( pMerger ){
  75202. for(i=0; i<pMerger->nTree; i++){
  75203. vdbePmaReaderClear(&pMerger->aReadr[i]);
  75204. }
  75205. }
  75206. sqlite3_free(pMerger);
  75207. }
  75208. /*
  75209. ** Free all resources associated with the IncrMerger object indicated by
  75210. ** the first argument.
  75211. */
  75212. static void vdbeIncrFree(IncrMerger *pIncr){
  75213. if( pIncr ){
  75214. #if SQLITE_MAX_WORKER_THREADS>0
  75215. if( pIncr->bUseThread ){
  75216. vdbeSorterJoinThread(pIncr->pTask);
  75217. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  75218. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  75219. }
  75220. #endif
  75221. vdbeMergeEngineFree(pIncr->pMerger);
  75222. sqlite3_free(pIncr);
  75223. }
  75224. }
  75225. /*
  75226. ** Reset a sorting cursor back to its original empty state.
  75227. */
  75228. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  75229. int i;
  75230. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  75231. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  75232. #if SQLITE_MAX_WORKER_THREADS>0
  75233. if( pSorter->pReader ){
  75234. vdbePmaReaderClear(pSorter->pReader);
  75235. sqlite3DbFree(db, pSorter->pReader);
  75236. pSorter->pReader = 0;
  75237. }
  75238. #endif
  75239. vdbeMergeEngineFree(pSorter->pMerger);
  75240. pSorter->pMerger = 0;
  75241. for(i=0; i<pSorter->nTask; i++){
  75242. SortSubtask *pTask = &pSorter->aTask[i];
  75243. vdbeSortSubtaskCleanup(db, pTask);
  75244. pTask->pSorter = pSorter;
  75245. }
  75246. if( pSorter->list.aMemory==0 ){
  75247. vdbeSorterRecordFree(0, pSorter->list.pList);
  75248. }
  75249. pSorter->list.pList = 0;
  75250. pSorter->list.szPMA = 0;
  75251. pSorter->bUsePMA = 0;
  75252. pSorter->iMemory = 0;
  75253. pSorter->mxKeysize = 0;
  75254. sqlite3DbFree(db, pSorter->pUnpacked);
  75255. pSorter->pUnpacked = 0;
  75256. }
  75257. /*
  75258. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  75259. */
  75260. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  75261. VdbeSorter *pSorter = pCsr->pSorter;
  75262. if( pSorter ){
  75263. sqlite3VdbeSorterReset(db, pSorter);
  75264. sqlite3_free(pSorter->list.aMemory);
  75265. sqlite3DbFree(db, pSorter);
  75266. pCsr->pSorter = 0;
  75267. }
  75268. }
  75269. #if SQLITE_MAX_MMAP_SIZE>0
  75270. /*
  75271. ** The first argument is a file-handle open on a temporary file. The file
  75272. ** is guaranteed to be nByte bytes or smaller in size. This function
  75273. ** attempts to extend the file to nByte bytes in size and to ensure that
  75274. ** the VFS has memory mapped it.
  75275. **
  75276. ** Whether or not the file does end up memory mapped of course depends on
  75277. ** the specific VFS implementation.
  75278. */
  75279. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  75280. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  75281. void *p = 0;
  75282. int chunksize = 4*1024;
  75283. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
  75284. sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
  75285. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  75286. sqlite3OsUnfetch(pFd, 0, p);
  75287. }
  75288. }
  75289. #else
  75290. # define vdbeSorterExtendFile(x,y,z)
  75291. #endif
  75292. /*
  75293. ** Allocate space for a file-handle and open a temporary file. If successful,
  75294. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  75295. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  75296. */
  75297. static int vdbeSorterOpenTempFile(
  75298. sqlite3 *db, /* Database handle doing sort */
  75299. i64 nExtend, /* Attempt to extend file to this size */
  75300. sqlite3_file **ppFd
  75301. ){
  75302. int rc;
  75303. if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
  75304. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  75305. SQLITE_OPEN_TEMP_JOURNAL |
  75306. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  75307. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  75308. );
  75309. if( rc==SQLITE_OK ){
  75310. i64 max = SQLITE_MAX_MMAP_SIZE;
  75311. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  75312. if( nExtend>0 ){
  75313. vdbeSorterExtendFile(db, *ppFd, nExtend);
  75314. }
  75315. }
  75316. return rc;
  75317. }
  75318. /*
  75319. ** If it has not already been allocated, allocate the UnpackedRecord
  75320. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  75321. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  75322. */
  75323. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  75324. if( pTask->pUnpacked==0 ){
  75325. char *pFree;
  75326. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
  75327. pTask->pSorter->pKeyInfo, 0, 0, &pFree
  75328. );
  75329. assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
  75330. if( pFree==0 ) return SQLITE_NOMEM;
  75331. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  75332. pTask->pUnpacked->errCode = 0;
  75333. }
  75334. return SQLITE_OK;
  75335. }
  75336. /*
  75337. ** Merge the two sorted lists p1 and p2 into a single list.
  75338. ** Set *ppOut to the head of the new list.
  75339. */
  75340. static void vdbeSorterMerge(
  75341. SortSubtask *pTask, /* Calling thread context */
  75342. SorterRecord *p1, /* First list to merge */
  75343. SorterRecord *p2, /* Second list to merge */
  75344. SorterRecord **ppOut /* OUT: Head of merged list */
  75345. ){
  75346. SorterRecord *pFinal = 0;
  75347. SorterRecord **pp = &pFinal;
  75348. int bCached = 0;
  75349. while( p1 && p2 ){
  75350. int res;
  75351. res = pTask->xCompare(
  75352. pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
  75353. );
  75354. if( res<=0 ){
  75355. *pp = p1;
  75356. pp = &p1->u.pNext;
  75357. p1 = p1->u.pNext;
  75358. }else{
  75359. *pp = p2;
  75360. pp = &p2->u.pNext;
  75361. p2 = p2->u.pNext;
  75362. bCached = 0;
  75363. }
  75364. }
  75365. *pp = p1 ? p1 : p2;
  75366. *ppOut = pFinal;
  75367. }
  75368. /*
  75369. ** Return the SorterCompare function to compare values collected by the
  75370. ** sorter object passed as the only argument.
  75371. */
  75372. static SorterCompare vdbeSorterGetCompare(VdbeSorter *p){
  75373. if( p->typeMask==SORTER_TYPE_INTEGER ){
  75374. return vdbeSorterCompareInt;
  75375. }else if( p->typeMask==SORTER_TYPE_TEXT ){
  75376. return vdbeSorterCompareText;
  75377. }
  75378. return vdbeSorterCompare;
  75379. }
  75380. /*
  75381. ** Sort the linked list of records headed at pTask->pList. Return
  75382. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  75383. ** an error occurs.
  75384. */
  75385. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  75386. int i;
  75387. SorterRecord **aSlot;
  75388. SorterRecord *p;
  75389. int rc;
  75390. rc = vdbeSortAllocUnpacked(pTask);
  75391. if( rc!=SQLITE_OK ) return rc;
  75392. p = pList->pList;
  75393. pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
  75394. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  75395. if( !aSlot ){
  75396. return SQLITE_NOMEM;
  75397. }
  75398. while( p ){
  75399. SorterRecord *pNext;
  75400. if( pList->aMemory ){
  75401. if( (u8*)p==pList->aMemory ){
  75402. pNext = 0;
  75403. }else{
  75404. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  75405. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  75406. }
  75407. }else{
  75408. pNext = p->u.pNext;
  75409. }
  75410. p->u.pNext = 0;
  75411. for(i=0; aSlot[i]; i++){
  75412. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  75413. aSlot[i] = 0;
  75414. }
  75415. aSlot[i] = p;
  75416. p = pNext;
  75417. }
  75418. p = 0;
  75419. for(i=0; i<64; i++){
  75420. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  75421. }
  75422. pList->pList = p;
  75423. sqlite3_free(aSlot);
  75424. assert( pTask->pUnpacked->errCode==SQLITE_OK
  75425. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  75426. );
  75427. return pTask->pUnpacked->errCode;
  75428. }
  75429. /*
  75430. ** Initialize a PMA-writer object.
  75431. */
  75432. static void vdbePmaWriterInit(
  75433. sqlite3_file *pFd, /* File handle to write to */
  75434. PmaWriter *p, /* Object to populate */
  75435. int nBuf, /* Buffer size */
  75436. i64 iStart /* Offset of pFd to begin writing at */
  75437. ){
  75438. memset(p, 0, sizeof(PmaWriter));
  75439. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  75440. if( !p->aBuffer ){
  75441. p->eFWErr = SQLITE_NOMEM;
  75442. }else{
  75443. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  75444. p->iWriteOff = iStart - p->iBufStart;
  75445. p->nBuffer = nBuf;
  75446. p->pFd = pFd;
  75447. }
  75448. }
  75449. /*
  75450. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  75451. ** if successful, or an SQLite error code if an error occurs.
  75452. */
  75453. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  75454. int nRem = nData;
  75455. while( nRem>0 && p->eFWErr==0 ){
  75456. int nCopy = nRem;
  75457. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  75458. nCopy = p->nBuffer - p->iBufEnd;
  75459. }
  75460. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  75461. p->iBufEnd += nCopy;
  75462. if( p->iBufEnd==p->nBuffer ){
  75463. p->eFWErr = sqlite3OsWrite(p->pFd,
  75464. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  75465. p->iWriteOff + p->iBufStart
  75466. );
  75467. p->iBufStart = p->iBufEnd = 0;
  75468. p->iWriteOff += p->nBuffer;
  75469. }
  75470. assert( p->iBufEnd<p->nBuffer );
  75471. nRem -= nCopy;
  75472. }
  75473. }
  75474. /*
  75475. ** Flush any buffered data to disk and clean up the PMA-writer object.
  75476. ** The results of using the PMA-writer after this call are undefined.
  75477. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  75478. ** required. Otherwise, return an SQLite error code.
  75479. **
  75480. ** Before returning, set *piEof to the offset immediately following the
  75481. ** last byte written to the file.
  75482. */
  75483. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  75484. int rc;
  75485. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  75486. p->eFWErr = sqlite3OsWrite(p->pFd,
  75487. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  75488. p->iWriteOff + p->iBufStart
  75489. );
  75490. }
  75491. *piEof = (p->iWriteOff + p->iBufEnd);
  75492. sqlite3_free(p->aBuffer);
  75493. rc = p->eFWErr;
  75494. memset(p, 0, sizeof(PmaWriter));
  75495. return rc;
  75496. }
  75497. /*
  75498. ** Write value iVal encoded as a varint to the PMA. Return
  75499. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  75500. */
  75501. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  75502. int nByte;
  75503. u8 aByte[10];
  75504. nByte = sqlite3PutVarint(aByte, iVal);
  75505. vdbePmaWriteBlob(p, aByte, nByte);
  75506. }
  75507. /*
  75508. ** Write the current contents of in-memory linked-list pList to a level-0
  75509. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  75510. ** successful, or an SQLite error code otherwise.
  75511. **
  75512. ** The format of a PMA is:
  75513. **
  75514. ** * A varint. This varint contains the total number of bytes of content
  75515. ** in the PMA (not including the varint itself).
  75516. **
  75517. ** * One or more records packed end-to-end in order of ascending keys.
  75518. ** Each record consists of a varint followed by a blob of data (the
  75519. ** key). The varint is the number of bytes in the blob of data.
  75520. */
  75521. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  75522. sqlite3 *db = pTask->pSorter->db;
  75523. int rc = SQLITE_OK; /* Return code */
  75524. PmaWriter writer; /* Object used to write to the file */
  75525. #ifdef SQLITE_DEBUG
  75526. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  75527. ** This is used by an assert() statement at the end of this function. */
  75528. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  75529. #endif
  75530. vdbeSorterWorkDebug(pTask, "enter");
  75531. memset(&writer, 0, sizeof(PmaWriter));
  75532. assert( pList->szPMA>0 );
  75533. /* If the first temporary PMA file has not been opened, open it now. */
  75534. if( pTask->file.pFd==0 ){
  75535. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  75536. assert( rc!=SQLITE_OK || pTask->file.pFd );
  75537. assert( pTask->file.iEof==0 );
  75538. assert( pTask->nPMA==0 );
  75539. }
  75540. /* Try to get the file to memory map */
  75541. if( rc==SQLITE_OK ){
  75542. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  75543. }
  75544. /* Sort the list */
  75545. if( rc==SQLITE_OK ){
  75546. rc = vdbeSorterSort(pTask, pList);
  75547. }
  75548. if( rc==SQLITE_OK ){
  75549. SorterRecord *p;
  75550. SorterRecord *pNext = 0;
  75551. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  75552. pTask->file.iEof);
  75553. pTask->nPMA++;
  75554. vdbePmaWriteVarint(&writer, pList->szPMA);
  75555. for(p=pList->pList; p; p=pNext){
  75556. pNext = p->u.pNext;
  75557. vdbePmaWriteVarint(&writer, p->nVal);
  75558. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  75559. if( pList->aMemory==0 ) sqlite3_free(p);
  75560. }
  75561. pList->pList = p;
  75562. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  75563. }
  75564. vdbeSorterWorkDebug(pTask, "exit");
  75565. assert( rc!=SQLITE_OK || pList->pList==0 );
  75566. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  75567. return rc;
  75568. }
  75569. /*
  75570. ** Advance the MergeEngine to its next entry.
  75571. ** Set *pbEof to true there is no next entry because
  75572. ** the MergeEngine has reached the end of all its inputs.
  75573. **
  75574. ** Return SQLITE_OK if successful or an error code if an error occurs.
  75575. */
  75576. static int vdbeMergeEngineStep(
  75577. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  75578. int *pbEof /* Set TRUE at EOF. Set false for more content */
  75579. ){
  75580. int rc;
  75581. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  75582. SortSubtask *pTask = pMerger->pTask;
  75583. /* Advance the current PmaReader */
  75584. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  75585. /* Update contents of aTree[] */
  75586. if( rc==SQLITE_OK ){
  75587. int i; /* Index of aTree[] to recalculate */
  75588. PmaReader *pReadr1; /* First PmaReader to compare */
  75589. PmaReader *pReadr2; /* Second PmaReader to compare */
  75590. int bCached = 0;
  75591. /* Find the first two PmaReaders to compare. The one that was just
  75592. ** advanced (iPrev) and the one next to it in the array. */
  75593. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  75594. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  75595. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  75596. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  75597. int iRes;
  75598. if( pReadr1->pFd==0 ){
  75599. iRes = +1;
  75600. }else if( pReadr2->pFd==0 ){
  75601. iRes = -1;
  75602. }else{
  75603. iRes = pTask->xCompare(pTask, &bCached,
  75604. pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
  75605. );
  75606. }
  75607. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  75608. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  75609. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  75610. ** pKey2 to point to the record belonging to pReadr2.
  75611. **
  75612. ** Alternatively, if pReadr2 contains the smaller of the two values,
  75613. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  75614. ** was actually called above, then pTask->pUnpacked now contains
  75615. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  75616. ** vdbeSorterCompare() from decoding pReadr2 again.
  75617. **
  75618. ** If the two values were equal, then the value from the oldest
  75619. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  75620. ** is sorted from oldest to newest, so pReadr1 contains older values
  75621. ** than pReadr2 iff (pReadr1<pReadr2). */
  75622. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  75623. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  75624. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  75625. bCached = 0;
  75626. }else{
  75627. if( pReadr1->pFd ) bCached = 0;
  75628. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  75629. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  75630. }
  75631. }
  75632. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  75633. }
  75634. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  75635. }
  75636. #if SQLITE_MAX_WORKER_THREADS>0
  75637. /*
  75638. ** The main routine for background threads that write level-0 PMAs.
  75639. */
  75640. static void *vdbeSorterFlushThread(void *pCtx){
  75641. SortSubtask *pTask = (SortSubtask*)pCtx;
  75642. int rc; /* Return code */
  75643. assert( pTask->bDone==0 );
  75644. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  75645. pTask->bDone = 1;
  75646. return SQLITE_INT_TO_PTR(rc);
  75647. }
  75648. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  75649. /*
  75650. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  75651. ** using a background thread.
  75652. */
  75653. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  75654. #if SQLITE_MAX_WORKER_THREADS==0
  75655. pSorter->bUsePMA = 1;
  75656. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  75657. #else
  75658. int rc = SQLITE_OK;
  75659. int i;
  75660. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  75661. int nWorker = (pSorter->nTask-1);
  75662. /* Set the flag to indicate that at least one PMA has been written.
  75663. ** Or will be, anyhow. */
  75664. pSorter->bUsePMA = 1;
  75665. /* Select a sub-task to sort and flush the current list of in-memory
  75666. ** records to disk. If the sorter is running in multi-threaded mode,
  75667. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  75668. ** the background thread from a sub-tasks previous turn is still running,
  75669. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  75670. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  75671. ** sub-tasks are prefered as they use background threads - the final
  75672. ** sub-task uses the main thread. */
  75673. for(i=0; i<nWorker; i++){
  75674. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  75675. pTask = &pSorter->aTask[iTest];
  75676. if( pTask->bDone ){
  75677. rc = vdbeSorterJoinThread(pTask);
  75678. }
  75679. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  75680. }
  75681. if( rc==SQLITE_OK ){
  75682. if( i==nWorker ){
  75683. /* Use the foreground thread for this operation */
  75684. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  75685. }else{
  75686. /* Launch a background thread for this operation */
  75687. u8 *aMem = pTask->list.aMemory;
  75688. void *pCtx = (void*)pTask;
  75689. assert( pTask->pThread==0 && pTask->bDone==0 );
  75690. assert( pTask->list.pList==0 );
  75691. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  75692. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  75693. pTask->list = pSorter->list;
  75694. pSorter->list.pList = 0;
  75695. pSorter->list.szPMA = 0;
  75696. if( aMem ){
  75697. pSorter->list.aMemory = aMem;
  75698. pSorter->nMemory = sqlite3MallocSize(aMem);
  75699. }else if( pSorter->list.aMemory ){
  75700. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  75701. if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
  75702. }
  75703. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  75704. }
  75705. }
  75706. return rc;
  75707. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  75708. }
  75709. /*
  75710. ** Add a record to the sorter.
  75711. */
  75712. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  75713. const VdbeCursor *pCsr, /* Sorter cursor */
  75714. Mem *pVal /* Memory cell containing record */
  75715. ){
  75716. VdbeSorter *pSorter = pCsr->pSorter;
  75717. int rc = SQLITE_OK; /* Return Code */
  75718. SorterRecord *pNew; /* New list element */
  75719. int bFlush; /* True to flush contents of memory to PMA */
  75720. int nReq; /* Bytes of memory required */
  75721. int nPMA; /* Bytes of PMA space required */
  75722. int t; /* serial type of first record field */
  75723. getVarint32((const u8*)&pVal->z[1], t);
  75724. if( t>0 && t<10 && t!=7 ){
  75725. pSorter->typeMask &= SORTER_TYPE_INTEGER;
  75726. }else if( t>10 && (t & 0x01) ){
  75727. pSorter->typeMask &= SORTER_TYPE_TEXT;
  75728. }else{
  75729. pSorter->typeMask = 0;
  75730. }
  75731. assert( pSorter );
  75732. /* Figure out whether or not the current contents of memory should be
  75733. ** flushed to a PMA before continuing. If so, do so.
  75734. **
  75735. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  75736. ** flush the contents of memory to a new PMA if (a) at least one value is
  75737. ** already in memory and (b) the new value will not fit in memory.
  75738. **
  75739. ** Or, if using separate allocations for each record, flush the contents
  75740. ** of memory to a PMA if either of the following are true:
  75741. **
  75742. ** * The total memory allocated for the in-memory list is greater
  75743. ** than (page-size * cache-size), or
  75744. **
  75745. ** * The total memory allocated for the in-memory list is greater
  75746. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  75747. */
  75748. nReq = pVal->n + sizeof(SorterRecord);
  75749. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  75750. if( pSorter->mxPmaSize ){
  75751. if( pSorter->list.aMemory ){
  75752. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  75753. }else{
  75754. bFlush = (
  75755. (pSorter->list.szPMA > pSorter->mxPmaSize)
  75756. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  75757. );
  75758. }
  75759. if( bFlush ){
  75760. rc = vdbeSorterFlushPMA(pSorter);
  75761. pSorter->list.szPMA = 0;
  75762. pSorter->iMemory = 0;
  75763. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  75764. }
  75765. }
  75766. pSorter->list.szPMA += nPMA;
  75767. if( nPMA>pSorter->mxKeysize ){
  75768. pSorter->mxKeysize = nPMA;
  75769. }
  75770. if( pSorter->list.aMemory ){
  75771. int nMin = pSorter->iMemory + nReq;
  75772. if( nMin>pSorter->nMemory ){
  75773. u8 *aNew;
  75774. int nNew = pSorter->nMemory * 2;
  75775. while( nNew < nMin ) nNew = nNew*2;
  75776. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  75777. if( nNew < nMin ) nNew = nMin;
  75778. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  75779. if( !aNew ) return SQLITE_NOMEM;
  75780. pSorter->list.pList = (SorterRecord*)(
  75781. aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
  75782. );
  75783. pSorter->list.aMemory = aNew;
  75784. pSorter->nMemory = nNew;
  75785. }
  75786. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  75787. pSorter->iMemory += ROUND8(nReq);
  75788. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  75789. }else{
  75790. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  75791. if( pNew==0 ){
  75792. return SQLITE_NOMEM;
  75793. }
  75794. pNew->u.pNext = pSorter->list.pList;
  75795. }
  75796. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  75797. pNew->nVal = pVal->n;
  75798. pSorter->list.pList = pNew;
  75799. return rc;
  75800. }
  75801. /*
  75802. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  75803. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  75804. ** except that the number-of-bytes varint is omitted from the start.
  75805. */
  75806. static int vdbeIncrPopulate(IncrMerger *pIncr){
  75807. int rc = SQLITE_OK;
  75808. int rc2;
  75809. i64 iStart = pIncr->iStartOff;
  75810. SorterFile *pOut = &pIncr->aFile[1];
  75811. SortSubtask *pTask = pIncr->pTask;
  75812. MergeEngine *pMerger = pIncr->pMerger;
  75813. PmaWriter writer;
  75814. assert( pIncr->bEof==0 );
  75815. vdbeSorterPopulateDebug(pTask, "enter");
  75816. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  75817. while( rc==SQLITE_OK ){
  75818. int dummy;
  75819. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  75820. int nKey = pReader->nKey;
  75821. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  75822. /* Check if the output file is full or if the input has been exhausted.
  75823. ** In either case exit the loop. */
  75824. if( pReader->pFd==0 ) break;
  75825. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  75826. /* Write the next key to the output. */
  75827. vdbePmaWriteVarint(&writer, nKey);
  75828. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  75829. assert( pIncr->pMerger->pTask==pTask );
  75830. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  75831. }
  75832. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  75833. if( rc==SQLITE_OK ) rc = rc2;
  75834. vdbeSorterPopulateDebug(pTask, "exit");
  75835. return rc;
  75836. }
  75837. #if SQLITE_MAX_WORKER_THREADS>0
  75838. /*
  75839. ** The main routine for background threads that populate aFile[1] of
  75840. ** multi-threaded IncrMerger objects.
  75841. */
  75842. static void *vdbeIncrPopulateThread(void *pCtx){
  75843. IncrMerger *pIncr = (IncrMerger*)pCtx;
  75844. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  75845. pIncr->pTask->bDone = 1;
  75846. return pRet;
  75847. }
  75848. /*
  75849. ** Launch a background thread to populate aFile[1] of pIncr.
  75850. */
  75851. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  75852. void *p = (void*)pIncr;
  75853. assert( pIncr->bUseThread );
  75854. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  75855. }
  75856. #endif
  75857. /*
  75858. ** This function is called when the PmaReader corresponding to pIncr has
  75859. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  75860. ** aFile[0] such that the PmaReader should start rereading it from the
  75861. ** beginning.
  75862. **
  75863. ** For single-threaded objects, this is accomplished by literally reading
  75864. ** keys from pIncr->pMerger and repopulating aFile[0].
  75865. **
  75866. ** For multi-threaded objects, all that is required is to wait until the
  75867. ** background thread is finished (if it is not already) and then swap
  75868. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  75869. ** been exhausted, this function also launches a new background thread
  75870. ** to populate the new aFile[1].
  75871. **
  75872. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  75873. */
  75874. static int vdbeIncrSwap(IncrMerger *pIncr){
  75875. int rc = SQLITE_OK;
  75876. #if SQLITE_MAX_WORKER_THREADS>0
  75877. if( pIncr->bUseThread ){
  75878. rc = vdbeSorterJoinThread(pIncr->pTask);
  75879. if( rc==SQLITE_OK ){
  75880. SorterFile f0 = pIncr->aFile[0];
  75881. pIncr->aFile[0] = pIncr->aFile[1];
  75882. pIncr->aFile[1] = f0;
  75883. }
  75884. if( rc==SQLITE_OK ){
  75885. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  75886. pIncr->bEof = 1;
  75887. }else{
  75888. rc = vdbeIncrBgPopulate(pIncr);
  75889. }
  75890. }
  75891. }else
  75892. #endif
  75893. {
  75894. rc = vdbeIncrPopulate(pIncr);
  75895. pIncr->aFile[0] = pIncr->aFile[1];
  75896. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  75897. pIncr->bEof = 1;
  75898. }
  75899. }
  75900. return rc;
  75901. }
  75902. /*
  75903. ** Allocate and return a new IncrMerger object to read data from pMerger.
  75904. **
  75905. ** If an OOM condition is encountered, return NULL. In this case free the
  75906. ** pMerger argument before returning.
  75907. */
  75908. static int vdbeIncrMergerNew(
  75909. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  75910. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  75911. IncrMerger **ppOut /* Write the new IncrMerger here */
  75912. ){
  75913. int rc = SQLITE_OK;
  75914. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  75915. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  75916. if( pIncr ){
  75917. pIncr->pMerger = pMerger;
  75918. pIncr->pTask = pTask;
  75919. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  75920. pTask->file2.iEof += pIncr->mxSz;
  75921. }else{
  75922. vdbeMergeEngineFree(pMerger);
  75923. rc = SQLITE_NOMEM;
  75924. }
  75925. return rc;
  75926. }
  75927. #if SQLITE_MAX_WORKER_THREADS>0
  75928. /*
  75929. ** Set the "use-threads" flag on object pIncr.
  75930. */
  75931. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  75932. pIncr->bUseThread = 1;
  75933. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  75934. }
  75935. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  75936. /*
  75937. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  75938. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  75939. ** are advanced. This routine merely does the comparison.
  75940. */
  75941. static void vdbeMergeEngineCompare(
  75942. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  75943. int iOut /* Store the result in pMerger->aTree[iOut] */
  75944. ){
  75945. int i1;
  75946. int i2;
  75947. int iRes;
  75948. PmaReader *p1;
  75949. PmaReader *p2;
  75950. assert( iOut<pMerger->nTree && iOut>0 );
  75951. if( iOut>=(pMerger->nTree/2) ){
  75952. i1 = (iOut - pMerger->nTree/2) * 2;
  75953. i2 = i1 + 1;
  75954. }else{
  75955. i1 = pMerger->aTree[iOut*2];
  75956. i2 = pMerger->aTree[iOut*2+1];
  75957. }
  75958. p1 = &pMerger->aReadr[i1];
  75959. p2 = &pMerger->aReadr[i2];
  75960. if( p1->pFd==0 ){
  75961. iRes = i2;
  75962. }else if( p2->pFd==0 ){
  75963. iRes = i1;
  75964. }else{
  75965. SortSubtask *pTask = pMerger->pTask;
  75966. int bCached = 0;
  75967. int res;
  75968. assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  75969. res = pTask->xCompare(
  75970. pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  75971. );
  75972. if( res<=0 ){
  75973. iRes = i1;
  75974. }else{
  75975. iRes = i2;
  75976. }
  75977. }
  75978. pMerger->aTree[iOut] = iRes;
  75979. }
  75980. /*
  75981. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  75982. ** and vdbePmaReaderIncrMergeInit().
  75983. **
  75984. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  75985. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  75986. ** when there exists one or more separate worker threads.
  75987. */
  75988. #define INCRINIT_NORMAL 0
  75989. #define INCRINIT_TASK 1
  75990. #define INCRINIT_ROOT 2
  75991. /*
  75992. ** Forward reference required as the vdbeIncrMergeInit() and
  75993. ** vdbePmaReaderIncrInit() routines are called mutually recursively when
  75994. ** building a merge tree.
  75995. */
  75996. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
  75997. /*
  75998. ** Initialize the MergeEngine object passed as the second argument. Once this
  75999. ** function returns, the first key of merged data may be read from the
  76000. ** MergeEngine object in the usual fashion.
  76001. **
  76002. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  76003. ** objects attached to the PmaReader objects that the merger reads from have
  76004. ** already been populated, but that they have not yet populated aFile[0] and
  76005. ** set the PmaReader objects up to read from it. In this case all that is
  76006. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  76007. ** its first key.
  76008. **
  76009. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  76010. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  76011. ** to pMerger.
  76012. **
  76013. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  76014. */
  76015. static int vdbeMergeEngineInit(
  76016. SortSubtask *pTask, /* Thread that will run pMerger */
  76017. MergeEngine *pMerger, /* MergeEngine to initialize */
  76018. int eMode /* One of the INCRINIT_XXX constants */
  76019. ){
  76020. int rc = SQLITE_OK; /* Return code */
  76021. int i; /* For looping over PmaReader objects */
  76022. int nTree = pMerger->nTree;
  76023. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  76024. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  76025. /* Verify that the MergeEngine is assigned to a single thread */
  76026. assert( pMerger->pTask==0 );
  76027. pMerger->pTask = pTask;
  76028. for(i=0; i<nTree; i++){
  76029. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  76030. /* PmaReaders should be normally initialized in order, as if they are
  76031. ** reading from the same temp file this makes for more linear file IO.
  76032. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  76033. ** in use it will block the vdbePmaReaderNext() call while it uses
  76034. ** the main thread to fill its buffer. So calling PmaReaderNext()
  76035. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  76036. ** better advantage of multi-processor hardware. */
  76037. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  76038. }else{
  76039. rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  76040. }
  76041. if( rc!=SQLITE_OK ) return rc;
  76042. }
  76043. for(i=pMerger->nTree-1; i>0; i--){
  76044. vdbeMergeEngineCompare(pMerger, i);
  76045. }
  76046. return pTask->pUnpacked->errCode;
  76047. }
  76048. /*
  76049. ** The PmaReader passed as the first argument is guaranteed to be an
  76050. ** incremental-reader (pReadr->pIncr!=0). This function serves to open
  76051. ** and/or initialize the temp file related fields of the IncrMerge
  76052. ** object at (pReadr->pIncr).
  76053. **
  76054. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  76055. ** in the sub-tree headed by pReadr are also initialized. Data is then
  76056. ** loaded into the buffers belonging to pReadr and it is set to point to
  76057. ** the first key in its range.
  76058. **
  76059. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  76060. ** to be a multi-threaded PmaReader and this function is being called in a
  76061. ** background thread. In this case all PmaReaders in the sub-tree are
  76062. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  76063. ** pReadr is populated. However, pReadr itself is not set up to point
  76064. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  76065. ** that.
  76066. **
  76067. ** The reason this function does not call vdbePmaReaderNext() immediately
  76068. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  76069. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  76070. ** this entire function is being run by thread (pTask->thread), that will
  76071. ** lead to the current background thread attempting to join itself.
  76072. **
  76073. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  76074. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  76075. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  76076. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  76077. ** the current PmaReader set to point to the first key in its range.
  76078. **
  76079. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  76080. */
  76081. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  76082. int rc = SQLITE_OK;
  76083. IncrMerger *pIncr = pReadr->pIncr;
  76084. SortSubtask *pTask = pIncr->pTask;
  76085. sqlite3 *db = pTask->pSorter->db;
  76086. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  76087. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  76088. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  76089. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  76090. ** requires two temp files to itself, whereas a single-threaded object
  76091. ** only requires a region of pTask->file2. */
  76092. if( rc==SQLITE_OK ){
  76093. int mxSz = pIncr->mxSz;
  76094. #if SQLITE_MAX_WORKER_THREADS>0
  76095. if( pIncr->bUseThread ){
  76096. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  76097. if( rc==SQLITE_OK ){
  76098. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  76099. }
  76100. }else
  76101. #endif
  76102. /*if( !pIncr->bUseThread )*/{
  76103. if( pTask->file2.pFd==0 ){
  76104. assert( pTask->file2.iEof>0 );
  76105. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  76106. pTask->file2.iEof = 0;
  76107. }
  76108. if( rc==SQLITE_OK ){
  76109. pIncr->aFile[1].pFd = pTask->file2.pFd;
  76110. pIncr->iStartOff = pTask->file2.iEof;
  76111. pTask->file2.iEof += mxSz;
  76112. }
  76113. }
  76114. }
  76115. #if SQLITE_MAX_WORKER_THREADS>0
  76116. if( rc==SQLITE_OK && pIncr->bUseThread ){
  76117. /* Use the current thread to populate aFile[1], even though this
  76118. ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
  76119. ** then this function is already running in background thread
  76120. ** pIncr->pTask->thread.
  76121. **
  76122. ** If this is the INCRINIT_ROOT object, then it is running in the
  76123. ** main VDBE thread. But that is Ok, as that thread cannot return
  76124. ** control to the VDBE or proceed with anything useful until the
  76125. ** first results are ready from this merger object anyway.
  76126. */
  76127. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  76128. rc = vdbeIncrPopulate(pIncr);
  76129. }
  76130. #endif
  76131. if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
  76132. rc = vdbePmaReaderNext(pReadr);
  76133. }
  76134. return rc;
  76135. }
  76136. #if SQLITE_MAX_WORKER_THREADS>0
  76137. /*
  76138. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  76139. ** background threads.
  76140. */
  76141. static void *vdbePmaReaderBgIncrInit(void *pCtx){
  76142. PmaReader *pReader = (PmaReader*)pCtx;
  76143. void *pRet = SQLITE_INT_TO_PTR(
  76144. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  76145. );
  76146. pReader->pIncr->pTask->bDone = 1;
  76147. return pRet;
  76148. }
  76149. #endif
  76150. /*
  76151. ** If the PmaReader passed as the first argument is not an incremental-reader
  76152. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
  76153. ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
  76154. ** this routine to initialize the incremental merge.
  76155. **
  76156. ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
  76157. ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
  76158. ** Or, if the IncrMerger is single threaded, the same function is called
  76159. ** using the current thread.
  76160. */
  76161. static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
  76162. IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
  76163. int rc = SQLITE_OK; /* Return code */
  76164. if( pIncr ){
  76165. #if SQLITE_MAX_WORKER_THREADS>0
  76166. assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
  76167. if( pIncr->bUseThread ){
  76168. void *pCtx = (void*)pReadr;
  76169. rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
  76170. }else
  76171. #endif
  76172. {
  76173. rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
  76174. }
  76175. }
  76176. return rc;
  76177. }
  76178. /*
  76179. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  76180. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  76181. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  76182. ** to NULL and return an SQLite error code.
  76183. **
  76184. ** When this function is called, *piOffset is set to the offset of the
  76185. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  76186. ** set to the offset immediately following the last byte of the last
  76187. ** PMA before returning. If an error does occur, then the final value of
  76188. ** *piOffset is undefined.
  76189. */
  76190. static int vdbeMergeEngineLevel0(
  76191. SortSubtask *pTask, /* Sorter task to read from */
  76192. int nPMA, /* Number of PMAs to read */
  76193. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  76194. MergeEngine **ppOut /* OUT: New merge-engine */
  76195. ){
  76196. MergeEngine *pNew; /* Merge engine to return */
  76197. i64 iOff = *piOffset;
  76198. int i;
  76199. int rc = SQLITE_OK;
  76200. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  76201. if( pNew==0 ) rc = SQLITE_NOMEM;
  76202. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  76203. i64 nDummy;
  76204. PmaReader *pReadr = &pNew->aReadr[i];
  76205. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  76206. iOff = pReadr->iEof;
  76207. }
  76208. if( rc!=SQLITE_OK ){
  76209. vdbeMergeEngineFree(pNew);
  76210. *ppOut = 0;
  76211. }
  76212. *piOffset = iOff;
  76213. return rc;
  76214. }
  76215. /*
  76216. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  76217. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  76218. **
  76219. ** i.e.
  76220. **
  76221. ** nPMA<=16 -> TreeDepth() == 0
  76222. ** nPMA<=256 -> TreeDepth() == 1
  76223. ** nPMA<=65536 -> TreeDepth() == 2
  76224. */
  76225. static int vdbeSorterTreeDepth(int nPMA){
  76226. int nDepth = 0;
  76227. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  76228. while( nDiv < (i64)nPMA ){
  76229. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  76230. nDepth++;
  76231. }
  76232. return nDepth;
  76233. }
  76234. /*
  76235. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  76236. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  76237. ** tree, counting from zero. This function adds pLeaf to the tree.
  76238. **
  76239. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  76240. ** code is returned and pLeaf is freed.
  76241. */
  76242. static int vdbeSorterAddToTree(
  76243. SortSubtask *pTask, /* Task context */
  76244. int nDepth, /* Depth of tree according to TreeDepth() */
  76245. int iSeq, /* Sequence number of leaf within tree */
  76246. MergeEngine *pRoot, /* Root of tree */
  76247. MergeEngine *pLeaf /* Leaf to add to tree */
  76248. ){
  76249. int rc = SQLITE_OK;
  76250. int nDiv = 1;
  76251. int i;
  76252. MergeEngine *p = pRoot;
  76253. IncrMerger *pIncr;
  76254. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  76255. for(i=1; i<nDepth; i++){
  76256. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  76257. }
  76258. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  76259. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  76260. PmaReader *pReadr = &p->aReadr[iIter];
  76261. if( pReadr->pIncr==0 ){
  76262. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  76263. if( pNew==0 ){
  76264. rc = SQLITE_NOMEM;
  76265. }else{
  76266. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  76267. }
  76268. }
  76269. if( rc==SQLITE_OK ){
  76270. p = pReadr->pIncr->pMerger;
  76271. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  76272. }
  76273. }
  76274. if( rc==SQLITE_OK ){
  76275. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  76276. }else{
  76277. vdbeIncrFree(pIncr);
  76278. }
  76279. return rc;
  76280. }
  76281. /*
  76282. ** This function is called as part of a SorterRewind() operation on a sorter
  76283. ** that has already written two or more level-0 PMAs to one or more temp
  76284. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  76285. ** can be used to incrementally merge all PMAs on disk.
  76286. **
  76287. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  76288. ** MergeEngine object at the root of the tree before returning. Or, if an
  76289. ** error occurs, an SQLite error code is returned and the final value
  76290. ** of *ppOut is undefined.
  76291. */
  76292. static int vdbeSorterMergeTreeBuild(
  76293. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  76294. MergeEngine **ppOut /* Write the MergeEngine here */
  76295. ){
  76296. MergeEngine *pMain = 0;
  76297. int rc = SQLITE_OK;
  76298. int iTask;
  76299. #if SQLITE_MAX_WORKER_THREADS>0
  76300. /* If the sorter uses more than one task, then create the top-level
  76301. ** MergeEngine here. This MergeEngine will read data from exactly
  76302. ** one PmaReader per sub-task. */
  76303. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  76304. if( pSorter->nTask>1 ){
  76305. pMain = vdbeMergeEngineNew(pSorter->nTask);
  76306. if( pMain==0 ) rc = SQLITE_NOMEM;
  76307. }
  76308. #endif
  76309. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  76310. SortSubtask *pTask = &pSorter->aTask[iTask];
  76311. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  76312. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  76313. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  76314. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  76315. i64 iReadOff = 0;
  76316. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  76317. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  76318. }else{
  76319. int i;
  76320. int iSeq = 0;
  76321. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  76322. if( pRoot==0 ) rc = SQLITE_NOMEM;
  76323. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  76324. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  76325. int nReader; /* Number of level-0 PMAs to merge */
  76326. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  76327. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  76328. if( rc==SQLITE_OK ){
  76329. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  76330. }
  76331. }
  76332. }
  76333. if( rc==SQLITE_OK ){
  76334. #if SQLITE_MAX_WORKER_THREADS>0
  76335. if( pMain!=0 ){
  76336. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  76337. }else
  76338. #endif
  76339. {
  76340. assert( pMain==0 );
  76341. pMain = pRoot;
  76342. }
  76343. }else{
  76344. vdbeMergeEngineFree(pRoot);
  76345. }
  76346. }
  76347. }
  76348. if( rc!=SQLITE_OK ){
  76349. vdbeMergeEngineFree(pMain);
  76350. pMain = 0;
  76351. }
  76352. *ppOut = pMain;
  76353. return rc;
  76354. }
  76355. /*
  76356. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  76357. ** on a sorter that has written two or more PMAs to temporary files. It sets
  76358. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  76359. ** (for multi-threaded sorters) so that it can be used to iterate through
  76360. ** all records stored in the sorter.
  76361. **
  76362. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  76363. */
  76364. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  76365. int rc; /* Return code */
  76366. SortSubtask *pTask0 = &pSorter->aTask[0];
  76367. MergeEngine *pMain = 0;
  76368. #if SQLITE_MAX_WORKER_THREADS
  76369. sqlite3 *db = pTask0->pSorter->db;
  76370. int i;
  76371. SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
  76372. for(i=0; i<pSorter->nTask; i++){
  76373. pSorter->aTask[i].xCompare = xCompare;
  76374. }
  76375. #endif
  76376. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  76377. if( rc==SQLITE_OK ){
  76378. #if SQLITE_MAX_WORKER_THREADS
  76379. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  76380. if( pSorter->bUseThreads ){
  76381. int iTask;
  76382. PmaReader *pReadr = 0;
  76383. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  76384. rc = vdbeSortAllocUnpacked(pLast);
  76385. if( rc==SQLITE_OK ){
  76386. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  76387. pSorter->pReader = pReadr;
  76388. if( pReadr==0 ) rc = SQLITE_NOMEM;
  76389. }
  76390. if( rc==SQLITE_OK ){
  76391. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  76392. if( rc==SQLITE_OK ){
  76393. vdbeIncrMergerSetThreads(pReadr->pIncr);
  76394. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  76395. IncrMerger *pIncr;
  76396. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  76397. vdbeIncrMergerSetThreads(pIncr);
  76398. assert( pIncr->pTask!=pLast );
  76399. }
  76400. }
  76401. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  76402. /* Check that:
  76403. **
  76404. ** a) The incremental merge object is configured to use the
  76405. ** right task, and
  76406. ** b) If it is using task (nTask-1), it is configured to run
  76407. ** in single-threaded mode. This is important, as the
  76408. ** root merge (INCRINIT_ROOT) will be using the same task
  76409. ** object.
  76410. */
  76411. PmaReader *p = &pMain->aReadr[iTask];
  76412. assert( p->pIncr==0 || (
  76413. (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
  76414. && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
  76415. ));
  76416. rc = vdbePmaReaderIncrInit(p, INCRINIT_TASK);
  76417. }
  76418. }
  76419. pMain = 0;
  76420. }
  76421. if( rc==SQLITE_OK ){
  76422. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  76423. }
  76424. }else
  76425. #endif
  76426. {
  76427. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  76428. pSorter->pMerger = pMain;
  76429. pMain = 0;
  76430. }
  76431. }
  76432. if( rc!=SQLITE_OK ){
  76433. vdbeMergeEngineFree(pMain);
  76434. }
  76435. return rc;
  76436. }
  76437. /*
  76438. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  76439. ** this function is called to prepare for iterating through the records
  76440. ** in sorted order.
  76441. */
  76442. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  76443. VdbeSorter *pSorter = pCsr->pSorter;
  76444. int rc = SQLITE_OK; /* Return code */
  76445. assert( pSorter );
  76446. /* If no data has been written to disk, then do not do so now. Instead,
  76447. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  76448. ** from the in-memory list. */
  76449. if( pSorter->bUsePMA==0 ){
  76450. if( pSorter->list.pList ){
  76451. *pbEof = 0;
  76452. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  76453. }else{
  76454. *pbEof = 1;
  76455. }
  76456. return rc;
  76457. }
  76458. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  76459. ** function flushes the contents of memory to disk, it immediately always
  76460. ** creates a new list consisting of a single key immediately afterwards.
  76461. ** So the list is never empty at this point. */
  76462. assert( pSorter->list.pList );
  76463. rc = vdbeSorterFlushPMA(pSorter);
  76464. /* Join all threads */
  76465. rc = vdbeSorterJoinAll(pSorter, rc);
  76466. vdbeSorterRewindDebug("rewind");
  76467. /* Assuming no errors have occurred, set up a merger structure to
  76468. ** incrementally read and merge all remaining PMAs. */
  76469. assert( pSorter->pReader==0 );
  76470. if( rc==SQLITE_OK ){
  76471. rc = vdbeSorterSetupMerge(pSorter);
  76472. *pbEof = 0;
  76473. }
  76474. vdbeSorterRewindDebug("rewinddone");
  76475. return rc;
  76476. }
  76477. /*
  76478. ** Advance to the next element in the sorter.
  76479. */
  76480. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  76481. VdbeSorter *pSorter = pCsr->pSorter;
  76482. int rc; /* Return code */
  76483. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  76484. if( pSorter->bUsePMA ){
  76485. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  76486. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  76487. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  76488. #if SQLITE_MAX_WORKER_THREADS>0
  76489. if( pSorter->bUseThreads ){
  76490. rc = vdbePmaReaderNext(pSorter->pReader);
  76491. *pbEof = (pSorter->pReader->pFd==0);
  76492. }else
  76493. #endif
  76494. /*if( !pSorter->bUseThreads )*/ {
  76495. assert( pSorter->pMerger!=0 );
  76496. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  76497. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  76498. }
  76499. }else{
  76500. SorterRecord *pFree = pSorter->list.pList;
  76501. pSorter->list.pList = pFree->u.pNext;
  76502. pFree->u.pNext = 0;
  76503. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  76504. *pbEof = !pSorter->list.pList;
  76505. rc = SQLITE_OK;
  76506. }
  76507. return rc;
  76508. }
  76509. /*
  76510. ** Return a pointer to a buffer owned by the sorter that contains the
  76511. ** current key.
  76512. */
  76513. static void *vdbeSorterRowkey(
  76514. const VdbeSorter *pSorter, /* Sorter object */
  76515. int *pnKey /* OUT: Size of current key in bytes */
  76516. ){
  76517. void *pKey;
  76518. if( pSorter->bUsePMA ){
  76519. PmaReader *pReader;
  76520. #if SQLITE_MAX_WORKER_THREADS>0
  76521. if( pSorter->bUseThreads ){
  76522. pReader = pSorter->pReader;
  76523. }else
  76524. #endif
  76525. /*if( !pSorter->bUseThreads )*/{
  76526. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  76527. }
  76528. *pnKey = pReader->nKey;
  76529. pKey = pReader->aKey;
  76530. }else{
  76531. *pnKey = pSorter->list.pList->nVal;
  76532. pKey = SRVAL(pSorter->list.pList);
  76533. }
  76534. return pKey;
  76535. }
  76536. /*
  76537. ** Copy the current sorter key into the memory cell pOut.
  76538. */
  76539. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  76540. VdbeSorter *pSorter = pCsr->pSorter;
  76541. void *pKey; int nKey; /* Sorter key to copy into pOut */
  76542. pKey = vdbeSorterRowkey(pSorter, &nKey);
  76543. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  76544. return SQLITE_NOMEM;
  76545. }
  76546. pOut->n = nKey;
  76547. MemSetTypeFlag(pOut, MEM_Blob);
  76548. memcpy(pOut->z, pKey, nKey);
  76549. return SQLITE_OK;
  76550. }
  76551. /*
  76552. ** Compare the key in memory cell pVal with the key that the sorter cursor
  76553. ** passed as the first argument currently points to. For the purposes of
  76554. ** the comparison, ignore the rowid field at the end of each record.
  76555. **
  76556. ** If the sorter cursor key contains any NULL values, consider it to be
  76557. ** less than pVal. Even if pVal also contains NULL values.
  76558. **
  76559. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  76560. ** Otherwise, set *pRes to a negative, zero or positive value if the
  76561. ** key in pVal is smaller than, equal to or larger than the current sorter
  76562. ** key.
  76563. **
  76564. ** This routine forms the core of the OP_SorterCompare opcode, which in
  76565. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  76566. */
  76567. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  76568. const VdbeCursor *pCsr, /* Sorter cursor */
  76569. Mem *pVal, /* Value to compare to current sorter key */
  76570. int nKeyCol, /* Compare this many columns */
  76571. int *pRes /* OUT: Result of comparison */
  76572. ){
  76573. VdbeSorter *pSorter = pCsr->pSorter;
  76574. UnpackedRecord *r2 = pSorter->pUnpacked;
  76575. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  76576. int i;
  76577. void *pKey; int nKey; /* Sorter key to compare pVal with */
  76578. if( r2==0 ){
  76579. char *p;
  76580. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
  76581. assert( pSorter->pUnpacked==(UnpackedRecord*)p );
  76582. if( r2==0 ) return SQLITE_NOMEM;
  76583. r2->nField = nKeyCol;
  76584. }
  76585. assert( r2->nField==nKeyCol );
  76586. pKey = vdbeSorterRowkey(pSorter, &nKey);
  76587. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  76588. for(i=0; i<nKeyCol; i++){
  76589. if( r2->aMem[i].flags & MEM_Null ){
  76590. *pRes = -1;
  76591. return SQLITE_OK;
  76592. }
  76593. }
  76594. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  76595. return SQLITE_OK;
  76596. }
  76597. /************** End of vdbesort.c ********************************************/
  76598. /************** Begin file journal.c *****************************************/
  76599. /*
  76600. ** 2007 August 22
  76601. **
  76602. ** The author disclaims copyright to this source code. In place of
  76603. ** a legal notice, here is a blessing:
  76604. **
  76605. ** May you do good and not evil.
  76606. ** May you find forgiveness for yourself and forgive others.
  76607. ** May you share freely, never taking more than you give.
  76608. **
  76609. *************************************************************************
  76610. **
  76611. ** This file implements a special kind of sqlite3_file object used
  76612. ** by SQLite to create journal files if the atomic-write optimization
  76613. ** is enabled.
  76614. **
  76615. ** The distinctive characteristic of this sqlite3_file is that the
  76616. ** actual on disk file is created lazily. When the file is created,
  76617. ** the caller specifies a buffer size for an in-memory buffer to
  76618. ** be used to service read() and write() requests. The actual file
  76619. ** on disk is not created or populated until either:
  76620. **
  76621. ** 1) The in-memory representation grows too large for the allocated
  76622. ** buffer, or
  76623. ** 2) The sqlite3JournalCreate() function is called.
  76624. */
  76625. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  76626. /* #include "sqliteInt.h" */
  76627. /*
  76628. ** A JournalFile object is a subclass of sqlite3_file used by
  76629. ** as an open file handle for journal files.
  76630. */
  76631. struct JournalFile {
  76632. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  76633. int nBuf; /* Size of zBuf[] in bytes */
  76634. char *zBuf; /* Space to buffer journal writes */
  76635. int iSize; /* Amount of zBuf[] currently used */
  76636. int flags; /* xOpen flags */
  76637. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  76638. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  76639. const char *zJournal; /* Name of the journal file */
  76640. };
  76641. typedef struct JournalFile JournalFile;
  76642. /*
  76643. ** If it does not already exists, create and populate the on-disk file
  76644. ** for JournalFile p.
  76645. */
  76646. static int createFile(JournalFile *p){
  76647. int rc = SQLITE_OK;
  76648. if( !p->pReal ){
  76649. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  76650. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  76651. if( rc==SQLITE_OK ){
  76652. p->pReal = pReal;
  76653. if( p->iSize>0 ){
  76654. assert(p->iSize<=p->nBuf);
  76655. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  76656. }
  76657. if( rc!=SQLITE_OK ){
  76658. /* If an error occurred while writing to the file, close it before
  76659. ** returning. This way, SQLite uses the in-memory journal data to
  76660. ** roll back changes made to the internal page-cache before this
  76661. ** function was called. */
  76662. sqlite3OsClose(pReal);
  76663. p->pReal = 0;
  76664. }
  76665. }
  76666. }
  76667. return rc;
  76668. }
  76669. /*
  76670. ** Close the file.
  76671. */
  76672. static int jrnlClose(sqlite3_file *pJfd){
  76673. JournalFile *p = (JournalFile *)pJfd;
  76674. if( p->pReal ){
  76675. sqlite3OsClose(p->pReal);
  76676. }
  76677. sqlite3_free(p->zBuf);
  76678. return SQLITE_OK;
  76679. }
  76680. /*
  76681. ** Read data from the file.
  76682. */
  76683. static int jrnlRead(
  76684. sqlite3_file *pJfd, /* The journal file from which to read */
  76685. void *zBuf, /* Put the results here */
  76686. int iAmt, /* Number of bytes to read */
  76687. sqlite_int64 iOfst /* Begin reading at this offset */
  76688. ){
  76689. int rc = SQLITE_OK;
  76690. JournalFile *p = (JournalFile *)pJfd;
  76691. if( p->pReal ){
  76692. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  76693. }else if( (iAmt+iOfst)>p->iSize ){
  76694. rc = SQLITE_IOERR_SHORT_READ;
  76695. }else{
  76696. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  76697. }
  76698. return rc;
  76699. }
  76700. /*
  76701. ** Write data to the file.
  76702. */
  76703. static int jrnlWrite(
  76704. sqlite3_file *pJfd, /* The journal file into which to write */
  76705. const void *zBuf, /* Take data to be written from here */
  76706. int iAmt, /* Number of bytes to write */
  76707. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  76708. ){
  76709. int rc = SQLITE_OK;
  76710. JournalFile *p = (JournalFile *)pJfd;
  76711. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  76712. rc = createFile(p);
  76713. }
  76714. if( rc==SQLITE_OK ){
  76715. if( p->pReal ){
  76716. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  76717. }else{
  76718. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  76719. if( p->iSize<(iOfst+iAmt) ){
  76720. p->iSize = (iOfst+iAmt);
  76721. }
  76722. }
  76723. }
  76724. return rc;
  76725. }
  76726. /*
  76727. ** Truncate the file.
  76728. */
  76729. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  76730. int rc = SQLITE_OK;
  76731. JournalFile *p = (JournalFile *)pJfd;
  76732. if( p->pReal ){
  76733. rc = sqlite3OsTruncate(p->pReal, size);
  76734. }else if( size<p->iSize ){
  76735. p->iSize = size;
  76736. }
  76737. return rc;
  76738. }
  76739. /*
  76740. ** Sync the file.
  76741. */
  76742. static int jrnlSync(sqlite3_file *pJfd, int flags){
  76743. int rc;
  76744. JournalFile *p = (JournalFile *)pJfd;
  76745. if( p->pReal ){
  76746. rc = sqlite3OsSync(p->pReal, flags);
  76747. }else{
  76748. rc = SQLITE_OK;
  76749. }
  76750. return rc;
  76751. }
  76752. /*
  76753. ** Query the size of the file in bytes.
  76754. */
  76755. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  76756. int rc = SQLITE_OK;
  76757. JournalFile *p = (JournalFile *)pJfd;
  76758. if( p->pReal ){
  76759. rc = sqlite3OsFileSize(p->pReal, pSize);
  76760. }else{
  76761. *pSize = (sqlite_int64) p->iSize;
  76762. }
  76763. return rc;
  76764. }
  76765. /*
  76766. ** Table of methods for JournalFile sqlite3_file object.
  76767. */
  76768. static struct sqlite3_io_methods JournalFileMethods = {
  76769. 1, /* iVersion */
  76770. jrnlClose, /* xClose */
  76771. jrnlRead, /* xRead */
  76772. jrnlWrite, /* xWrite */
  76773. jrnlTruncate, /* xTruncate */
  76774. jrnlSync, /* xSync */
  76775. jrnlFileSize, /* xFileSize */
  76776. 0, /* xLock */
  76777. 0, /* xUnlock */
  76778. 0, /* xCheckReservedLock */
  76779. 0, /* xFileControl */
  76780. 0, /* xSectorSize */
  76781. 0, /* xDeviceCharacteristics */
  76782. 0, /* xShmMap */
  76783. 0, /* xShmLock */
  76784. 0, /* xShmBarrier */
  76785. 0 /* xShmUnmap */
  76786. };
  76787. /*
  76788. ** Open a journal file.
  76789. */
  76790. SQLITE_PRIVATE int sqlite3JournalOpen(
  76791. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  76792. const char *zName, /* Name of the journal file */
  76793. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  76794. int flags, /* Opening flags */
  76795. int nBuf /* Bytes buffered before opening the file */
  76796. ){
  76797. JournalFile *p = (JournalFile *)pJfd;
  76798. memset(p, 0, sqlite3JournalSize(pVfs));
  76799. if( nBuf>0 ){
  76800. p->zBuf = sqlite3MallocZero(nBuf);
  76801. if( !p->zBuf ){
  76802. return SQLITE_NOMEM;
  76803. }
  76804. }else{
  76805. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  76806. }
  76807. p->pMethod = &JournalFileMethods;
  76808. p->nBuf = nBuf;
  76809. p->flags = flags;
  76810. p->zJournal = zName;
  76811. p->pVfs = pVfs;
  76812. return SQLITE_OK;
  76813. }
  76814. /*
  76815. ** If the argument p points to a JournalFile structure, and the underlying
  76816. ** file has not yet been created, create it now.
  76817. */
  76818. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  76819. if( p->pMethods!=&JournalFileMethods ){
  76820. return SQLITE_OK;
  76821. }
  76822. return createFile((JournalFile *)p);
  76823. }
  76824. /*
  76825. ** The file-handle passed as the only argument is guaranteed to be an open
  76826. ** file. It may or may not be of class JournalFile. If the file is a
  76827. ** JournalFile, and the underlying file on disk has not yet been opened,
  76828. ** return 0. Otherwise, return 1.
  76829. */
  76830. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  76831. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  76832. }
  76833. /*
  76834. ** Return the number of bytes required to store a JournalFile that uses vfs
  76835. ** pVfs to create the underlying on-disk files.
  76836. */
  76837. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  76838. return (pVfs->szOsFile+sizeof(JournalFile));
  76839. }
  76840. #endif
  76841. /************** End of journal.c *********************************************/
  76842. /************** Begin file memjournal.c **************************************/
  76843. /*
  76844. ** 2008 October 7
  76845. **
  76846. ** The author disclaims copyright to this source code. In place of
  76847. ** a legal notice, here is a blessing:
  76848. **
  76849. ** May you do good and not evil.
  76850. ** May you find forgiveness for yourself and forgive others.
  76851. ** May you share freely, never taking more than you give.
  76852. **
  76853. *************************************************************************
  76854. **
  76855. ** This file contains code use to implement an in-memory rollback journal.
  76856. ** The in-memory rollback journal is used to journal transactions for
  76857. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  76858. */
  76859. /* #include "sqliteInt.h" */
  76860. /* Forward references to internal structures */
  76861. typedef struct MemJournal MemJournal;
  76862. typedef struct FilePoint FilePoint;
  76863. typedef struct FileChunk FileChunk;
  76864. /* Space to hold the rollback journal is allocated in increments of
  76865. ** this many bytes.
  76866. **
  76867. ** The size chosen is a little less than a power of two. That way,
  76868. ** the FileChunk object will have a size that almost exactly fills
  76869. ** a power-of-two allocation. This minimizes wasted space in power-of-two
  76870. ** memory allocators.
  76871. */
  76872. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  76873. /*
  76874. ** The rollback journal is composed of a linked list of these structures.
  76875. */
  76876. struct FileChunk {
  76877. FileChunk *pNext; /* Next chunk in the journal */
  76878. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  76879. };
  76880. /*
  76881. ** An instance of this object serves as a cursor into the rollback journal.
  76882. ** The cursor can be either for reading or writing.
  76883. */
  76884. struct FilePoint {
  76885. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  76886. FileChunk *pChunk; /* Specific chunk into which cursor points */
  76887. };
  76888. /*
  76889. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  76890. ** is an instance of this class.
  76891. */
  76892. struct MemJournal {
  76893. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  76894. FileChunk *pFirst; /* Head of in-memory chunk-list */
  76895. FilePoint endpoint; /* Pointer to the end of the file */
  76896. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  76897. };
  76898. /*
  76899. ** Read data from the in-memory journal file. This is the implementation
  76900. ** of the sqlite3_vfs.xRead method.
  76901. */
  76902. static int memjrnlRead(
  76903. sqlite3_file *pJfd, /* The journal file from which to read */
  76904. void *zBuf, /* Put the results here */
  76905. int iAmt, /* Number of bytes to read */
  76906. sqlite_int64 iOfst /* Begin reading at this offset */
  76907. ){
  76908. MemJournal *p = (MemJournal *)pJfd;
  76909. u8 *zOut = zBuf;
  76910. int nRead = iAmt;
  76911. int iChunkOffset;
  76912. FileChunk *pChunk;
  76913. /* SQLite never tries to read past the end of a rollback journal file */
  76914. assert( iOfst+iAmt<=p->endpoint.iOffset );
  76915. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  76916. sqlite3_int64 iOff = 0;
  76917. for(pChunk=p->pFirst;
  76918. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  76919. pChunk=pChunk->pNext
  76920. ){
  76921. iOff += JOURNAL_CHUNKSIZE;
  76922. }
  76923. }else{
  76924. pChunk = p->readpoint.pChunk;
  76925. }
  76926. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  76927. do {
  76928. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  76929. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  76930. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  76931. zOut += nCopy;
  76932. nRead -= iSpace;
  76933. iChunkOffset = 0;
  76934. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  76935. p->readpoint.iOffset = iOfst+iAmt;
  76936. p->readpoint.pChunk = pChunk;
  76937. return SQLITE_OK;
  76938. }
  76939. /*
  76940. ** Write data to the file.
  76941. */
  76942. static int memjrnlWrite(
  76943. sqlite3_file *pJfd, /* The journal file into which to write */
  76944. const void *zBuf, /* Take data to be written from here */
  76945. int iAmt, /* Number of bytes to write */
  76946. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  76947. ){
  76948. MemJournal *p = (MemJournal *)pJfd;
  76949. int nWrite = iAmt;
  76950. u8 *zWrite = (u8 *)zBuf;
  76951. /* An in-memory journal file should only ever be appended to. Random
  76952. ** access writes are not required by sqlite.
  76953. */
  76954. assert( iOfst==p->endpoint.iOffset );
  76955. UNUSED_PARAMETER(iOfst);
  76956. while( nWrite>0 ){
  76957. FileChunk *pChunk = p->endpoint.pChunk;
  76958. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  76959. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  76960. if( iChunkOffset==0 ){
  76961. /* New chunk is required to extend the file. */
  76962. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  76963. if( !pNew ){
  76964. return SQLITE_IOERR_NOMEM;
  76965. }
  76966. pNew->pNext = 0;
  76967. if( pChunk ){
  76968. assert( p->pFirst );
  76969. pChunk->pNext = pNew;
  76970. }else{
  76971. assert( !p->pFirst );
  76972. p->pFirst = pNew;
  76973. }
  76974. p->endpoint.pChunk = pNew;
  76975. }
  76976. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  76977. zWrite += iSpace;
  76978. nWrite -= iSpace;
  76979. p->endpoint.iOffset += iSpace;
  76980. }
  76981. return SQLITE_OK;
  76982. }
  76983. /*
  76984. ** Truncate the file.
  76985. */
  76986. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  76987. MemJournal *p = (MemJournal *)pJfd;
  76988. FileChunk *pChunk;
  76989. assert(size==0);
  76990. UNUSED_PARAMETER(size);
  76991. pChunk = p->pFirst;
  76992. while( pChunk ){
  76993. FileChunk *pTmp = pChunk;
  76994. pChunk = pChunk->pNext;
  76995. sqlite3_free(pTmp);
  76996. }
  76997. sqlite3MemJournalOpen(pJfd);
  76998. return SQLITE_OK;
  76999. }
  77000. /*
  77001. ** Close the file.
  77002. */
  77003. static int memjrnlClose(sqlite3_file *pJfd){
  77004. memjrnlTruncate(pJfd, 0);
  77005. return SQLITE_OK;
  77006. }
  77007. /*
  77008. ** Sync the file.
  77009. **
  77010. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  77011. ** is never called in a working implementation. This implementation
  77012. ** exists purely as a contingency, in case some malfunction in some other
  77013. ** part of SQLite causes Sync to be called by mistake.
  77014. */
  77015. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  77016. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  77017. return SQLITE_OK;
  77018. }
  77019. /*
  77020. ** Query the size of the file in bytes.
  77021. */
  77022. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  77023. MemJournal *p = (MemJournal *)pJfd;
  77024. *pSize = (sqlite_int64) p->endpoint.iOffset;
  77025. return SQLITE_OK;
  77026. }
  77027. /*
  77028. ** Table of methods for MemJournal sqlite3_file object.
  77029. */
  77030. static const struct sqlite3_io_methods MemJournalMethods = {
  77031. 1, /* iVersion */
  77032. memjrnlClose, /* xClose */
  77033. memjrnlRead, /* xRead */
  77034. memjrnlWrite, /* xWrite */
  77035. memjrnlTruncate, /* xTruncate */
  77036. memjrnlSync, /* xSync */
  77037. memjrnlFileSize, /* xFileSize */
  77038. 0, /* xLock */
  77039. 0, /* xUnlock */
  77040. 0, /* xCheckReservedLock */
  77041. 0, /* xFileControl */
  77042. 0, /* xSectorSize */
  77043. 0, /* xDeviceCharacteristics */
  77044. 0, /* xShmMap */
  77045. 0, /* xShmLock */
  77046. 0, /* xShmBarrier */
  77047. 0, /* xShmUnmap */
  77048. 0, /* xFetch */
  77049. 0 /* xUnfetch */
  77050. };
  77051. /*
  77052. ** Open a journal file.
  77053. */
  77054. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  77055. MemJournal *p = (MemJournal *)pJfd;
  77056. assert( EIGHT_BYTE_ALIGNMENT(p) );
  77057. memset(p, 0, sqlite3MemJournalSize());
  77058. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  77059. }
  77060. /*
  77061. ** Return true if the file-handle passed as an argument is
  77062. ** an in-memory journal
  77063. */
  77064. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  77065. return pJfd->pMethods==&MemJournalMethods;
  77066. }
  77067. /*
  77068. ** Return the number of bytes required to store a MemJournal file descriptor.
  77069. */
  77070. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  77071. return sizeof(MemJournal);
  77072. }
  77073. /************** End of memjournal.c ******************************************/
  77074. /************** Begin file walker.c ******************************************/
  77075. /*
  77076. ** 2008 August 16
  77077. **
  77078. ** The author disclaims copyright to this source code. In place of
  77079. ** a legal notice, here is a blessing:
  77080. **
  77081. ** May you do good and not evil.
  77082. ** May you find forgiveness for yourself and forgive others.
  77083. ** May you share freely, never taking more than you give.
  77084. **
  77085. *************************************************************************
  77086. ** This file contains routines used for walking the parser tree for
  77087. ** an SQL statement.
  77088. */
  77089. /* #include "sqliteInt.h" */
  77090. /* #include <stdlib.h> */
  77091. /* #include <string.h> */
  77092. /*
  77093. ** Walk an expression tree. Invoke the callback once for each node
  77094. ** of the expression, while descending. (In other words, the callback
  77095. ** is invoked before visiting children.)
  77096. **
  77097. ** The return value from the callback should be one of the WRC_*
  77098. ** constants to specify how to proceed with the walk.
  77099. **
  77100. ** WRC_Continue Continue descending down the tree.
  77101. **
  77102. ** WRC_Prune Do not descend into child nodes. But allow
  77103. ** the walk to continue with sibling nodes.
  77104. **
  77105. ** WRC_Abort Do no more callbacks. Unwind the stack and
  77106. ** return the top-level walk call.
  77107. **
  77108. ** The return value from this routine is WRC_Abort to abandon the tree walk
  77109. ** and WRC_Continue to continue.
  77110. */
  77111. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  77112. int rc;
  77113. if( pExpr==0 ) return WRC_Continue;
  77114. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  77115. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  77116. rc = pWalker->xExprCallback(pWalker, pExpr);
  77117. if( rc==WRC_Continue
  77118. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  77119. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  77120. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  77121. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77122. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  77123. }else{
  77124. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  77125. }
  77126. }
  77127. return rc & WRC_Abort;
  77128. }
  77129. /*
  77130. ** Call sqlite3WalkExpr() for every expression in list p or until
  77131. ** an abort request is seen.
  77132. */
  77133. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  77134. int i;
  77135. struct ExprList_item *pItem;
  77136. if( p ){
  77137. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  77138. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  77139. }
  77140. }
  77141. return WRC_Continue;
  77142. }
  77143. /*
  77144. ** Walk all expressions associated with SELECT statement p. Do
  77145. ** not invoke the SELECT callback on p, but do (of course) invoke
  77146. ** any expr callbacks and SELECT callbacks that come from subqueries.
  77147. ** Return WRC_Abort or WRC_Continue.
  77148. */
  77149. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  77150. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  77151. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  77152. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  77153. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  77154. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  77155. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  77156. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  77157. return WRC_Continue;
  77158. }
  77159. /*
  77160. ** Walk the parse trees associated with all subqueries in the
  77161. ** FROM clause of SELECT statement p. Do not invoke the select
  77162. ** callback on p, but do invoke it on each FROM clause subquery
  77163. ** and on any subqueries further down in the tree. Return
  77164. ** WRC_Abort or WRC_Continue;
  77165. */
  77166. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  77167. SrcList *pSrc;
  77168. int i;
  77169. struct SrcList_item *pItem;
  77170. pSrc = p->pSrc;
  77171. if( ALWAYS(pSrc) ){
  77172. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  77173. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  77174. return WRC_Abort;
  77175. }
  77176. }
  77177. }
  77178. return WRC_Continue;
  77179. }
  77180. /*
  77181. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  77182. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  77183. ** on the compound select chain, p->pPrior.
  77184. **
  77185. ** If it is not NULL, the xSelectCallback() callback is invoked before
  77186. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  77187. ** method, if it is not NULL, is invoked following the walk of the
  77188. ** expressions and FROM clause.
  77189. **
  77190. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  77191. ** there is an abort request.
  77192. **
  77193. ** If the Walker does not have an xSelectCallback() then this routine
  77194. ** is a no-op returning WRC_Continue.
  77195. */
  77196. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  77197. int rc;
  77198. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  77199. return WRC_Continue;
  77200. }
  77201. rc = WRC_Continue;
  77202. pWalker->walkerDepth++;
  77203. while( p ){
  77204. if( pWalker->xSelectCallback ){
  77205. rc = pWalker->xSelectCallback(pWalker, p);
  77206. if( rc ) break;
  77207. }
  77208. if( sqlite3WalkSelectExpr(pWalker, p)
  77209. || sqlite3WalkSelectFrom(pWalker, p)
  77210. ){
  77211. pWalker->walkerDepth--;
  77212. return WRC_Abort;
  77213. }
  77214. if( pWalker->xSelectCallback2 ){
  77215. pWalker->xSelectCallback2(pWalker, p);
  77216. }
  77217. p = p->pPrior;
  77218. }
  77219. pWalker->walkerDepth--;
  77220. return rc & WRC_Abort;
  77221. }
  77222. /************** End of walker.c **********************************************/
  77223. /************** Begin file resolve.c *****************************************/
  77224. /*
  77225. ** 2008 August 18
  77226. **
  77227. ** The author disclaims copyright to this source code. In place of
  77228. ** a legal notice, here is a blessing:
  77229. **
  77230. ** May you do good and not evil.
  77231. ** May you find forgiveness for yourself and forgive others.
  77232. ** May you share freely, never taking more than you give.
  77233. **
  77234. *************************************************************************
  77235. **
  77236. ** This file contains routines used for walking the parser tree and
  77237. ** resolve all identifiers by associating them with a particular
  77238. ** table and column.
  77239. */
  77240. /* #include "sqliteInt.h" */
  77241. /* #include <stdlib.h> */
  77242. /* #include <string.h> */
  77243. /*
  77244. ** Walk the expression tree pExpr and increase the aggregate function
  77245. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  77246. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  77247. ** outer query into an inner subquery.
  77248. **
  77249. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  77250. ** is a helper function - a callback for the tree walker.
  77251. */
  77252. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  77253. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
  77254. return WRC_Continue;
  77255. }
  77256. static void incrAggFunctionDepth(Expr *pExpr, int N){
  77257. if( N>0 ){
  77258. Walker w;
  77259. memset(&w, 0, sizeof(w));
  77260. w.xExprCallback = incrAggDepth;
  77261. w.u.n = N;
  77262. sqlite3WalkExpr(&w, pExpr);
  77263. }
  77264. }
  77265. /*
  77266. ** Turn the pExpr expression into an alias for the iCol-th column of the
  77267. ** result set in pEList.
  77268. **
  77269. ** If the result set column is a simple column reference, then this routine
  77270. ** makes an exact copy. But for any other kind of expression, this
  77271. ** routine make a copy of the result set column as the argument to the
  77272. ** TK_AS operator. The TK_AS operator causes the expression to be
  77273. ** evaluated just once and then reused for each alias.
  77274. **
  77275. ** The reason for suppressing the TK_AS term when the expression is a simple
  77276. ** column reference is so that the column reference will be recognized as
  77277. ** usable by indices within the WHERE clause processing logic.
  77278. **
  77279. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  77280. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  77281. **
  77282. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  77283. **
  77284. ** Is equivalent to:
  77285. **
  77286. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  77287. **
  77288. ** The result of random()%5 in the GROUP BY clause is probably different
  77289. ** from the result in the result-set. On the other hand Standard SQL does
  77290. ** not allow the GROUP BY clause to contain references to result-set columns.
  77291. ** So this should never come up in well-formed queries.
  77292. **
  77293. ** If the reference is followed by a COLLATE operator, then make sure
  77294. ** the COLLATE operator is preserved. For example:
  77295. **
  77296. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  77297. **
  77298. ** Should be transformed into:
  77299. **
  77300. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  77301. **
  77302. ** The nSubquery parameter specifies how many levels of subquery the
  77303. ** alias is removed from the original expression. The usual value is
  77304. ** zero but it might be more if the alias is contained within a subquery
  77305. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  77306. ** structures must be increased by the nSubquery amount.
  77307. */
  77308. static void resolveAlias(
  77309. Parse *pParse, /* Parsing context */
  77310. ExprList *pEList, /* A result set */
  77311. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  77312. Expr *pExpr, /* Transform this into an alias to the result set */
  77313. const char *zType, /* "GROUP" or "ORDER" or "" */
  77314. int nSubquery /* Number of subqueries that the label is moving */
  77315. ){
  77316. Expr *pOrig; /* The iCol-th column of the result set */
  77317. Expr *pDup; /* Copy of pOrig */
  77318. sqlite3 *db; /* The database connection */
  77319. assert( iCol>=0 && iCol<pEList->nExpr );
  77320. pOrig = pEList->a[iCol].pExpr;
  77321. assert( pOrig!=0 );
  77322. db = pParse->db;
  77323. pDup = sqlite3ExprDup(db, pOrig, 0);
  77324. if( pDup==0 ) return;
  77325. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  77326. incrAggFunctionDepth(pDup, nSubquery);
  77327. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  77328. if( pDup==0 ) return;
  77329. ExprSetProperty(pDup, EP_Skip);
  77330. if( pEList->a[iCol].u.x.iAlias==0 ){
  77331. pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
  77332. }
  77333. pDup->iTable = pEList->a[iCol].u.x.iAlias;
  77334. }
  77335. if( pExpr->op==TK_COLLATE ){
  77336. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  77337. }
  77338. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  77339. ** prevents ExprDelete() from deleting the Expr structure itself,
  77340. ** allowing it to be repopulated by the memcpy() on the following line.
  77341. ** The pExpr->u.zToken might point into memory that will be freed by the
  77342. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  77343. ** make a copy of the token before doing the sqlite3DbFree().
  77344. */
  77345. ExprSetProperty(pExpr, EP_Static);
  77346. sqlite3ExprDelete(db, pExpr);
  77347. memcpy(pExpr, pDup, sizeof(*pExpr));
  77348. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  77349. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  77350. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  77351. pExpr->flags |= EP_MemToken;
  77352. }
  77353. sqlite3DbFree(db, pDup);
  77354. }
  77355. /*
  77356. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  77357. **
  77358. ** Return FALSE if the USING clause is NULL or if it does not contain
  77359. ** zCol.
  77360. */
  77361. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  77362. if( pUsing ){
  77363. int k;
  77364. for(k=0; k<pUsing->nId; k++){
  77365. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  77366. }
  77367. }
  77368. return 0;
  77369. }
  77370. /*
  77371. ** Subqueries stores the original database, table and column names for their
  77372. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  77373. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  77374. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  77375. ** match anything.
  77376. */
  77377. SQLITE_PRIVATE int sqlite3MatchSpanName(
  77378. const char *zSpan,
  77379. const char *zCol,
  77380. const char *zTab,
  77381. const char *zDb
  77382. ){
  77383. int n;
  77384. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  77385. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  77386. return 0;
  77387. }
  77388. zSpan += n+1;
  77389. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  77390. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  77391. return 0;
  77392. }
  77393. zSpan += n+1;
  77394. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  77395. return 0;
  77396. }
  77397. return 1;
  77398. }
  77399. /*
  77400. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  77401. ** that name in the set of source tables in pSrcList and make the pExpr
  77402. ** expression node refer back to that source column. The following changes
  77403. ** are made to pExpr:
  77404. **
  77405. ** pExpr->iDb Set the index in db->aDb[] of the database X
  77406. ** (even if X is implied).
  77407. ** pExpr->iTable Set to the cursor number for the table obtained
  77408. ** from pSrcList.
  77409. ** pExpr->pTab Points to the Table structure of X.Y (even if
  77410. ** X and/or Y are implied.)
  77411. ** pExpr->iColumn Set to the column number within the table.
  77412. ** pExpr->op Set to TK_COLUMN.
  77413. ** pExpr->pLeft Any expression this points to is deleted
  77414. ** pExpr->pRight Any expression this points to is deleted.
  77415. **
  77416. ** The zDb variable is the name of the database (the "X"). This value may be
  77417. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  77418. ** can be used. The zTable variable is the name of the table (the "Y"). This
  77419. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  77420. ** means that the form of the name is Z and that columns from any table
  77421. ** can be used.
  77422. **
  77423. ** If the name cannot be resolved unambiguously, leave an error message
  77424. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  77425. */
  77426. static int lookupName(
  77427. Parse *pParse, /* The parsing context */
  77428. const char *zDb, /* Name of the database containing table, or NULL */
  77429. const char *zTab, /* Name of table containing column, or NULL */
  77430. const char *zCol, /* Name of the column. */
  77431. NameContext *pNC, /* The name context used to resolve the name */
  77432. Expr *pExpr /* Make this EXPR node point to the selected column */
  77433. ){
  77434. int i, j; /* Loop counters */
  77435. int cnt = 0; /* Number of matching column names */
  77436. int cntTab = 0; /* Number of matching table names */
  77437. int nSubquery = 0; /* How many levels of subquery */
  77438. sqlite3 *db = pParse->db; /* The database connection */
  77439. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  77440. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  77441. NameContext *pTopNC = pNC; /* First namecontext in the list */
  77442. Schema *pSchema = 0; /* Schema of the expression */
  77443. int isTrigger = 0; /* True if resolved to a trigger column */
  77444. Table *pTab = 0; /* Table hold the row */
  77445. Column *pCol; /* A column of pTab */
  77446. assert( pNC ); /* the name context cannot be NULL. */
  77447. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  77448. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  77449. /* Initialize the node to no-match */
  77450. pExpr->iTable = -1;
  77451. pExpr->pTab = 0;
  77452. ExprSetVVAProperty(pExpr, EP_NoReduce);
  77453. /* Translate the schema name in zDb into a pointer to the corresponding
  77454. ** schema. If not found, pSchema will remain NULL and nothing will match
  77455. ** resulting in an appropriate error message toward the end of this routine
  77456. */
  77457. if( zDb ){
  77458. testcase( pNC->ncFlags & NC_PartIdx );
  77459. testcase( pNC->ncFlags & NC_IsCheck );
  77460. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  77461. /* Silently ignore database qualifiers inside CHECK constraints and
  77462. ** partial indices. Do not raise errors because that might break
  77463. ** legacy and because it does not hurt anything to just ignore the
  77464. ** database name. */
  77465. zDb = 0;
  77466. }else{
  77467. for(i=0; i<db->nDb; i++){
  77468. assert( db->aDb[i].zName );
  77469. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  77470. pSchema = db->aDb[i].pSchema;
  77471. break;
  77472. }
  77473. }
  77474. }
  77475. }
  77476. /* Start at the inner-most context and move outward until a match is found */
  77477. while( pNC && cnt==0 ){
  77478. ExprList *pEList;
  77479. SrcList *pSrcList = pNC->pSrcList;
  77480. if( pSrcList ){
  77481. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  77482. pTab = pItem->pTab;
  77483. assert( pTab!=0 && pTab->zName!=0 );
  77484. assert( pTab->nCol>0 );
  77485. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  77486. int hit = 0;
  77487. pEList = pItem->pSelect->pEList;
  77488. for(j=0; j<pEList->nExpr; j++){
  77489. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  77490. cnt++;
  77491. cntTab = 2;
  77492. pMatch = pItem;
  77493. pExpr->iColumn = j;
  77494. hit = 1;
  77495. }
  77496. }
  77497. if( hit || zTab==0 ) continue;
  77498. }
  77499. if( zDb && pTab->pSchema!=pSchema ){
  77500. continue;
  77501. }
  77502. if( zTab ){
  77503. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  77504. assert( zTabName!=0 );
  77505. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  77506. continue;
  77507. }
  77508. }
  77509. if( 0==(cntTab++) ){
  77510. pMatch = pItem;
  77511. }
  77512. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  77513. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  77514. /* If there has been exactly one prior match and this match
  77515. ** is for the right-hand table of a NATURAL JOIN or is in a
  77516. ** USING clause, then skip this match.
  77517. */
  77518. if( cnt==1 ){
  77519. if( pItem->jointype & JT_NATURAL ) continue;
  77520. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  77521. }
  77522. cnt++;
  77523. pMatch = pItem;
  77524. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  77525. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  77526. break;
  77527. }
  77528. }
  77529. }
  77530. if( pMatch ){
  77531. pExpr->iTable = pMatch->iCursor;
  77532. pExpr->pTab = pMatch->pTab;
  77533. /* RIGHT JOIN not (yet) supported */
  77534. assert( (pMatch->jointype & JT_RIGHT)==0 );
  77535. if( (pMatch->jointype & JT_LEFT)!=0 ){
  77536. ExprSetProperty(pExpr, EP_CanBeNull);
  77537. }
  77538. pSchema = pExpr->pTab->pSchema;
  77539. }
  77540. } /* if( pSrcList ) */
  77541. #ifndef SQLITE_OMIT_TRIGGER
  77542. /* If we have not already resolved the name, then maybe
  77543. ** it is a new.* or old.* trigger argument reference
  77544. */
  77545. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  77546. int op = pParse->eTriggerOp;
  77547. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  77548. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  77549. pExpr->iTable = 1;
  77550. pTab = pParse->pTriggerTab;
  77551. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  77552. pExpr->iTable = 0;
  77553. pTab = pParse->pTriggerTab;
  77554. }else{
  77555. pTab = 0;
  77556. }
  77557. if( pTab ){
  77558. int iCol;
  77559. pSchema = pTab->pSchema;
  77560. cntTab++;
  77561. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  77562. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  77563. if( iCol==pTab->iPKey ){
  77564. iCol = -1;
  77565. }
  77566. break;
  77567. }
  77568. }
  77569. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
  77570. /* IMP: R-51414-32910 */
  77571. /* IMP: R-44911-55124 */
  77572. iCol = -1;
  77573. }
  77574. if( iCol<pTab->nCol ){
  77575. cnt++;
  77576. if( iCol<0 ){
  77577. pExpr->affinity = SQLITE_AFF_INTEGER;
  77578. }else if( pExpr->iTable==0 ){
  77579. testcase( iCol==31 );
  77580. testcase( iCol==32 );
  77581. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  77582. }else{
  77583. testcase( iCol==31 );
  77584. testcase( iCol==32 );
  77585. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  77586. }
  77587. pExpr->iColumn = (i16)iCol;
  77588. pExpr->pTab = pTab;
  77589. isTrigger = 1;
  77590. }
  77591. }
  77592. }
  77593. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  77594. /*
  77595. ** Perhaps the name is a reference to the ROWID
  77596. */
  77597. if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
  77598. && VisibleRowid(pMatch->pTab) ){
  77599. cnt = 1;
  77600. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  77601. pExpr->affinity = SQLITE_AFF_INTEGER;
  77602. }
  77603. /*
  77604. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  77605. ** might refer to an result-set alias. This happens, for example, when
  77606. ** we are resolving names in the WHERE clause of the following command:
  77607. **
  77608. ** SELECT a+b AS x FROM table WHERE x<10;
  77609. **
  77610. ** In cases like this, replace pExpr with a copy of the expression that
  77611. ** forms the result set entry ("a+b" in the example) and return immediately.
  77612. ** Note that the expression in the result set should have already been
  77613. ** resolved by the time the WHERE clause is resolved.
  77614. **
  77615. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  77616. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  77617. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  77618. ** is supported for backwards compatibility only. TO DO: Issue a warning
  77619. ** on sqlite3_log() whenever the capability is used.
  77620. */
  77621. if( (pEList = pNC->pEList)!=0
  77622. && zTab==0
  77623. && cnt==0
  77624. ){
  77625. for(j=0; j<pEList->nExpr; j++){
  77626. char *zAs = pEList->a[j].zName;
  77627. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  77628. Expr *pOrig;
  77629. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  77630. assert( pExpr->x.pList==0 );
  77631. assert( pExpr->x.pSelect==0 );
  77632. pOrig = pEList->a[j].pExpr;
  77633. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  77634. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  77635. return WRC_Abort;
  77636. }
  77637. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  77638. cnt = 1;
  77639. pMatch = 0;
  77640. assert( zTab==0 && zDb==0 );
  77641. goto lookupname_end;
  77642. }
  77643. }
  77644. }
  77645. /* Advance to the next name context. The loop will exit when either
  77646. ** we have a match (cnt>0) or when we run out of name contexts.
  77647. */
  77648. if( cnt==0 ){
  77649. pNC = pNC->pNext;
  77650. nSubquery++;
  77651. }
  77652. }
  77653. /*
  77654. ** If X and Y are NULL (in other words if only the column name Z is
  77655. ** supplied) and the value of Z is enclosed in double-quotes, then
  77656. ** Z is a string literal if it doesn't match any column names. In that
  77657. ** case, we need to return right away and not make any changes to
  77658. ** pExpr.
  77659. **
  77660. ** Because no reference was made to outer contexts, the pNC->nRef
  77661. ** fields are not changed in any context.
  77662. */
  77663. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  77664. pExpr->op = TK_STRING;
  77665. pExpr->pTab = 0;
  77666. return WRC_Prune;
  77667. }
  77668. /*
  77669. ** cnt==0 means there was not match. cnt>1 means there were two or
  77670. ** more matches. Either way, we have an error.
  77671. */
  77672. if( cnt!=1 ){
  77673. const char *zErr;
  77674. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  77675. if( zDb ){
  77676. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  77677. }else if( zTab ){
  77678. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  77679. }else{
  77680. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  77681. }
  77682. pParse->checkSchema = 1;
  77683. pTopNC->nErr++;
  77684. }
  77685. /* If a column from a table in pSrcList is referenced, then record
  77686. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  77687. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  77688. ** column number is greater than the number of bits in the bitmask
  77689. ** then set the high-order bit of the bitmask.
  77690. */
  77691. if( pExpr->iColumn>=0 && pMatch!=0 ){
  77692. int n = pExpr->iColumn;
  77693. testcase( n==BMS-1 );
  77694. if( n>=BMS ){
  77695. n = BMS-1;
  77696. }
  77697. assert( pMatch->iCursor==pExpr->iTable );
  77698. pMatch->colUsed |= ((Bitmask)1)<<n;
  77699. }
  77700. /* Clean up and return
  77701. */
  77702. sqlite3ExprDelete(db, pExpr->pLeft);
  77703. pExpr->pLeft = 0;
  77704. sqlite3ExprDelete(db, pExpr->pRight);
  77705. pExpr->pRight = 0;
  77706. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  77707. lookupname_end:
  77708. if( cnt==1 ){
  77709. assert( pNC!=0 );
  77710. if( pExpr->op!=TK_AS ){
  77711. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  77712. }
  77713. /* Increment the nRef value on all name contexts from TopNC up to
  77714. ** the point where the name matched. */
  77715. for(;;){
  77716. assert( pTopNC!=0 );
  77717. pTopNC->nRef++;
  77718. if( pTopNC==pNC ) break;
  77719. pTopNC = pTopNC->pNext;
  77720. }
  77721. return WRC_Prune;
  77722. } else {
  77723. return WRC_Abort;
  77724. }
  77725. }
  77726. /*
  77727. ** Allocate and return a pointer to an expression to load the column iCol
  77728. ** from datasource iSrc in SrcList pSrc.
  77729. */
  77730. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  77731. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  77732. if( p ){
  77733. struct SrcList_item *pItem = &pSrc->a[iSrc];
  77734. p->pTab = pItem->pTab;
  77735. p->iTable = pItem->iCursor;
  77736. if( p->pTab->iPKey==iCol ){
  77737. p->iColumn = -1;
  77738. }else{
  77739. p->iColumn = (ynVar)iCol;
  77740. testcase( iCol==BMS );
  77741. testcase( iCol==BMS-1 );
  77742. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  77743. }
  77744. ExprSetProperty(p, EP_Resolved);
  77745. }
  77746. return p;
  77747. }
  77748. /*
  77749. ** Report an error that an expression is not valid for a partial index WHERE
  77750. ** clause.
  77751. */
  77752. static void notValidPartIdxWhere(
  77753. Parse *pParse, /* Leave error message here */
  77754. NameContext *pNC, /* The name context */
  77755. const char *zMsg /* Type of error */
  77756. ){
  77757. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  77758. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  77759. zMsg);
  77760. }
  77761. }
  77762. #ifndef SQLITE_OMIT_CHECK
  77763. /*
  77764. ** Report an error that an expression is not valid for a CHECK constraint.
  77765. */
  77766. static void notValidCheckConstraint(
  77767. Parse *pParse, /* Leave error message here */
  77768. NameContext *pNC, /* The name context */
  77769. const char *zMsg /* Type of error */
  77770. ){
  77771. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  77772. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  77773. }
  77774. }
  77775. #else
  77776. # define notValidCheckConstraint(P,N,M)
  77777. #endif
  77778. /*
  77779. ** Expression p should encode a floating point value between 1.0 and 0.0.
  77780. ** Return 1024 times this value. Or return -1 if p is not a floating point
  77781. ** value between 1.0 and 0.0.
  77782. */
  77783. static int exprProbability(Expr *p){
  77784. double r = -1.0;
  77785. if( p->op!=TK_FLOAT ) return -1;
  77786. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  77787. assert( r>=0.0 );
  77788. if( r>1.0 ) return -1;
  77789. return (int)(r*134217728.0);
  77790. }
  77791. /*
  77792. ** This routine is callback for sqlite3WalkExpr().
  77793. **
  77794. ** Resolve symbolic names into TK_COLUMN operators for the current
  77795. ** node in the expression tree. Return 0 to continue the search down
  77796. ** the tree or 2 to abort the tree walk.
  77797. **
  77798. ** This routine also does error checking and name resolution for
  77799. ** function names. The operator for aggregate functions is changed
  77800. ** to TK_AGG_FUNCTION.
  77801. */
  77802. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  77803. NameContext *pNC;
  77804. Parse *pParse;
  77805. pNC = pWalker->u.pNC;
  77806. assert( pNC!=0 );
  77807. pParse = pNC->pParse;
  77808. assert( pParse==pWalker->pParse );
  77809. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  77810. ExprSetProperty(pExpr, EP_Resolved);
  77811. #ifndef NDEBUG
  77812. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  77813. SrcList *pSrcList = pNC->pSrcList;
  77814. int i;
  77815. for(i=0; i<pNC->pSrcList->nSrc; i++){
  77816. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  77817. }
  77818. }
  77819. #endif
  77820. switch( pExpr->op ){
  77821. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  77822. /* The special operator TK_ROW means use the rowid for the first
  77823. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  77824. ** clause processing on UPDATE and DELETE statements.
  77825. */
  77826. case TK_ROW: {
  77827. SrcList *pSrcList = pNC->pSrcList;
  77828. struct SrcList_item *pItem;
  77829. assert( pSrcList && pSrcList->nSrc==1 );
  77830. pItem = pSrcList->a;
  77831. pExpr->op = TK_COLUMN;
  77832. pExpr->pTab = pItem->pTab;
  77833. pExpr->iTable = pItem->iCursor;
  77834. pExpr->iColumn = -1;
  77835. pExpr->affinity = SQLITE_AFF_INTEGER;
  77836. break;
  77837. }
  77838. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
  77839. && !defined(SQLITE_OMIT_SUBQUERY) */
  77840. /* A lone identifier is the name of a column.
  77841. */
  77842. case TK_ID: {
  77843. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  77844. }
  77845. /* A table name and column name: ID.ID
  77846. ** Or a database, table and column: ID.ID.ID
  77847. */
  77848. case TK_DOT: {
  77849. const char *zColumn;
  77850. const char *zTable;
  77851. const char *zDb;
  77852. Expr *pRight;
  77853. /* if( pSrcList==0 ) break; */
  77854. pRight = pExpr->pRight;
  77855. if( pRight->op==TK_ID ){
  77856. zDb = 0;
  77857. zTable = pExpr->pLeft->u.zToken;
  77858. zColumn = pRight->u.zToken;
  77859. }else{
  77860. assert( pRight->op==TK_DOT );
  77861. zDb = pExpr->pLeft->u.zToken;
  77862. zTable = pRight->pLeft->u.zToken;
  77863. zColumn = pRight->pRight->u.zToken;
  77864. }
  77865. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  77866. }
  77867. /* Resolve function names
  77868. */
  77869. case TK_FUNCTION: {
  77870. ExprList *pList = pExpr->x.pList; /* The argument list */
  77871. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  77872. int no_such_func = 0; /* True if no such function exists */
  77873. int wrong_num_args = 0; /* True if wrong number of arguments */
  77874. int is_agg = 0; /* True if is an aggregate function */
  77875. int auth; /* Authorization to use the function */
  77876. int nId; /* Number of characters in function name */
  77877. const char *zId; /* The function name. */
  77878. FuncDef *pDef; /* Information about the function */
  77879. u8 enc = ENC(pParse->db); /* The database encoding */
  77880. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77881. notValidPartIdxWhere(pParse, pNC, "functions");
  77882. zId = pExpr->u.zToken;
  77883. nId = sqlite3Strlen30(zId);
  77884. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  77885. if( pDef==0 ){
  77886. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  77887. if( pDef==0 ){
  77888. no_such_func = 1;
  77889. }else{
  77890. wrong_num_args = 1;
  77891. }
  77892. }else{
  77893. is_agg = pDef->xFunc==0;
  77894. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  77895. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  77896. if( n==2 ){
  77897. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  77898. if( pExpr->iTable<0 ){
  77899. sqlite3ErrorMsg(pParse,
  77900. "second argument to likelihood() must be a "
  77901. "constant between 0.0 and 1.0");
  77902. pNC->nErr++;
  77903. }
  77904. }else{
  77905. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
  77906. ** equivalent to likelihood(X, 0.0625).
  77907. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
  77908. ** short-hand for likelihood(X,0.0625).
  77909. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
  77910. ** for likelihood(X,0.9375).
  77911. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
  77912. ** to likelihood(X,0.9375). */
  77913. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  77914. pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
  77915. }
  77916. }
  77917. #ifndef SQLITE_OMIT_AUTHORIZATION
  77918. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  77919. if( auth!=SQLITE_OK ){
  77920. if( auth==SQLITE_DENY ){
  77921. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  77922. pDef->zName);
  77923. pNC->nErr++;
  77924. }
  77925. pExpr->op = TK_NULL;
  77926. return WRC_Prune;
  77927. }
  77928. #endif
  77929. if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ){
  77930. ExprSetProperty(pExpr,EP_ConstFunc);
  77931. }
  77932. }
  77933. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  77934. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  77935. pNC->nErr++;
  77936. is_agg = 0;
  77937. }else if( no_such_func && pParse->db->init.busy==0 ){
  77938. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  77939. pNC->nErr++;
  77940. }else if( wrong_num_args ){
  77941. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  77942. nId, zId);
  77943. pNC->nErr++;
  77944. }
  77945. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  77946. sqlite3WalkExprList(pWalker, pList);
  77947. if( is_agg ){
  77948. NameContext *pNC2 = pNC;
  77949. pExpr->op = TK_AGG_FUNCTION;
  77950. pExpr->op2 = 0;
  77951. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  77952. pExpr->op2++;
  77953. pNC2 = pNC2->pNext;
  77954. }
  77955. assert( pDef!=0 );
  77956. if( pNC2 ){
  77957. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  77958. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  77959. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  77960. }
  77961. pNC->ncFlags |= NC_AllowAgg;
  77962. }
  77963. /* FIX ME: Compute pExpr->affinity based on the expected return
  77964. ** type of the function
  77965. */
  77966. return WRC_Prune;
  77967. }
  77968. #ifndef SQLITE_OMIT_SUBQUERY
  77969. case TK_SELECT:
  77970. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  77971. #endif
  77972. case TK_IN: {
  77973. testcase( pExpr->op==TK_IN );
  77974. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77975. int nRef = pNC->nRef;
  77976. notValidCheckConstraint(pParse, pNC, "subqueries");
  77977. notValidPartIdxWhere(pParse, pNC, "subqueries");
  77978. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  77979. assert( pNC->nRef>=nRef );
  77980. if( nRef!=pNC->nRef ){
  77981. ExprSetProperty(pExpr, EP_VarSelect);
  77982. }
  77983. }
  77984. break;
  77985. }
  77986. case TK_VARIABLE: {
  77987. notValidCheckConstraint(pParse, pNC, "parameters");
  77988. notValidPartIdxWhere(pParse, pNC, "parameters");
  77989. break;
  77990. }
  77991. }
  77992. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  77993. }
  77994. /*
  77995. ** pEList is a list of expressions which are really the result set of the
  77996. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  77997. ** This routine checks to see if pE is a simple identifier which corresponds
  77998. ** to the AS-name of one of the terms of the expression list. If it is,
  77999. ** this routine return an integer between 1 and N where N is the number of
  78000. ** elements in pEList, corresponding to the matching entry. If there is
  78001. ** no match, or if pE is not a simple identifier, then this routine
  78002. ** return 0.
  78003. **
  78004. ** pEList has been resolved. pE has not.
  78005. */
  78006. static int resolveAsName(
  78007. Parse *pParse, /* Parsing context for error messages */
  78008. ExprList *pEList, /* List of expressions to scan */
  78009. Expr *pE /* Expression we are trying to match */
  78010. ){
  78011. int i; /* Loop counter */
  78012. UNUSED_PARAMETER(pParse);
  78013. if( pE->op==TK_ID ){
  78014. char *zCol = pE->u.zToken;
  78015. for(i=0; i<pEList->nExpr; i++){
  78016. char *zAs = pEList->a[i].zName;
  78017. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  78018. return i+1;
  78019. }
  78020. }
  78021. }
  78022. return 0;
  78023. }
  78024. /*
  78025. ** pE is a pointer to an expression which is a single term in the
  78026. ** ORDER BY of a compound SELECT. The expression has not been
  78027. ** name resolved.
  78028. **
  78029. ** At the point this routine is called, we already know that the
  78030. ** ORDER BY term is not an integer index into the result set. That
  78031. ** case is handled by the calling routine.
  78032. **
  78033. ** Attempt to match pE against result set columns in the left-most
  78034. ** SELECT statement. Return the index i of the matching column,
  78035. ** as an indication to the caller that it should sort by the i-th column.
  78036. ** The left-most column is 1. In other words, the value returned is the
  78037. ** same integer value that would be used in the SQL statement to indicate
  78038. ** the column.
  78039. **
  78040. ** If there is no match, return 0. Return -1 if an error occurs.
  78041. */
  78042. static int resolveOrderByTermToExprList(
  78043. Parse *pParse, /* Parsing context for error messages */
  78044. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  78045. Expr *pE /* The specific ORDER BY term */
  78046. ){
  78047. int i; /* Loop counter */
  78048. ExprList *pEList; /* The columns of the result set */
  78049. NameContext nc; /* Name context for resolving pE */
  78050. sqlite3 *db; /* Database connection */
  78051. int rc; /* Return code from subprocedures */
  78052. u8 savedSuppErr; /* Saved value of db->suppressErr */
  78053. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  78054. pEList = pSelect->pEList;
  78055. /* Resolve all names in the ORDER BY term expression
  78056. */
  78057. memset(&nc, 0, sizeof(nc));
  78058. nc.pParse = pParse;
  78059. nc.pSrcList = pSelect->pSrc;
  78060. nc.pEList = pEList;
  78061. nc.ncFlags = NC_AllowAgg;
  78062. nc.nErr = 0;
  78063. db = pParse->db;
  78064. savedSuppErr = db->suppressErr;
  78065. db->suppressErr = 1;
  78066. rc = sqlite3ResolveExprNames(&nc, pE);
  78067. db->suppressErr = savedSuppErr;
  78068. if( rc ) return 0;
  78069. /* Try to match the ORDER BY expression against an expression
  78070. ** in the result set. Return an 1-based index of the matching
  78071. ** result-set entry.
  78072. */
  78073. for(i=0; i<pEList->nExpr; i++){
  78074. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  78075. return i+1;
  78076. }
  78077. }
  78078. /* If no match, return 0. */
  78079. return 0;
  78080. }
  78081. /*
  78082. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  78083. */
  78084. static void resolveOutOfRangeError(
  78085. Parse *pParse, /* The error context into which to write the error */
  78086. const char *zType, /* "ORDER" or "GROUP" */
  78087. int i, /* The index (1-based) of the term out of range */
  78088. int mx /* Largest permissible value of i */
  78089. ){
  78090. sqlite3ErrorMsg(pParse,
  78091. "%r %s BY term out of range - should be "
  78092. "between 1 and %d", i, zType, mx);
  78093. }
  78094. /*
  78095. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  78096. ** each term of the ORDER BY clause is a constant integer between 1
  78097. ** and N where N is the number of columns in the compound SELECT.
  78098. **
  78099. ** ORDER BY terms that are already an integer between 1 and N are
  78100. ** unmodified. ORDER BY terms that are integers outside the range of
  78101. ** 1 through N generate an error. ORDER BY terms that are expressions
  78102. ** are matched against result set expressions of compound SELECT
  78103. ** beginning with the left-most SELECT and working toward the right.
  78104. ** At the first match, the ORDER BY expression is transformed into
  78105. ** the integer column number.
  78106. **
  78107. ** Return the number of errors seen.
  78108. */
  78109. static int resolveCompoundOrderBy(
  78110. Parse *pParse, /* Parsing context. Leave error messages here */
  78111. Select *pSelect /* The SELECT statement containing the ORDER BY */
  78112. ){
  78113. int i;
  78114. ExprList *pOrderBy;
  78115. ExprList *pEList;
  78116. sqlite3 *db;
  78117. int moreToDo = 1;
  78118. pOrderBy = pSelect->pOrderBy;
  78119. if( pOrderBy==0 ) return 0;
  78120. db = pParse->db;
  78121. #if SQLITE_MAX_COLUMN
  78122. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  78123. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  78124. return 1;
  78125. }
  78126. #endif
  78127. for(i=0; i<pOrderBy->nExpr; i++){
  78128. pOrderBy->a[i].done = 0;
  78129. }
  78130. pSelect->pNext = 0;
  78131. while( pSelect->pPrior ){
  78132. pSelect->pPrior->pNext = pSelect;
  78133. pSelect = pSelect->pPrior;
  78134. }
  78135. while( pSelect && moreToDo ){
  78136. struct ExprList_item *pItem;
  78137. moreToDo = 0;
  78138. pEList = pSelect->pEList;
  78139. assert( pEList!=0 );
  78140. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  78141. int iCol = -1;
  78142. Expr *pE, *pDup;
  78143. if( pItem->done ) continue;
  78144. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  78145. if( sqlite3ExprIsInteger(pE, &iCol) ){
  78146. if( iCol<=0 || iCol>pEList->nExpr ){
  78147. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  78148. return 1;
  78149. }
  78150. }else{
  78151. iCol = resolveAsName(pParse, pEList, pE);
  78152. if( iCol==0 ){
  78153. pDup = sqlite3ExprDup(db, pE, 0);
  78154. if( !db->mallocFailed ){
  78155. assert(pDup);
  78156. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  78157. }
  78158. sqlite3ExprDelete(db, pDup);
  78159. }
  78160. }
  78161. if( iCol>0 ){
  78162. /* Convert the ORDER BY term into an integer column number iCol,
  78163. ** taking care to preserve the COLLATE clause if it exists */
  78164. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  78165. if( pNew==0 ) return 1;
  78166. pNew->flags |= EP_IntValue;
  78167. pNew->u.iValue = iCol;
  78168. if( pItem->pExpr==pE ){
  78169. pItem->pExpr = pNew;
  78170. }else{
  78171. Expr *pParent = pItem->pExpr;
  78172. assert( pParent->op==TK_COLLATE );
  78173. while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
  78174. assert( pParent->pLeft==pE );
  78175. pParent->pLeft = pNew;
  78176. }
  78177. sqlite3ExprDelete(db, pE);
  78178. pItem->u.x.iOrderByCol = (u16)iCol;
  78179. pItem->done = 1;
  78180. }else{
  78181. moreToDo = 1;
  78182. }
  78183. }
  78184. pSelect = pSelect->pNext;
  78185. }
  78186. for(i=0; i<pOrderBy->nExpr; i++){
  78187. if( pOrderBy->a[i].done==0 ){
  78188. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  78189. "column in the result set", i+1);
  78190. return 1;
  78191. }
  78192. }
  78193. return 0;
  78194. }
  78195. /*
  78196. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  78197. ** the SELECT statement pSelect. If any term is reference to a
  78198. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  78199. ** field) then convert that term into a copy of the corresponding result set
  78200. ** column.
  78201. **
  78202. ** If any errors are detected, add an error message to pParse and
  78203. ** return non-zero. Return zero if no errors are seen.
  78204. */
  78205. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  78206. Parse *pParse, /* Parsing context. Leave error messages here */
  78207. Select *pSelect, /* The SELECT statement containing the clause */
  78208. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  78209. const char *zType /* "ORDER" or "GROUP" */
  78210. ){
  78211. int i;
  78212. sqlite3 *db = pParse->db;
  78213. ExprList *pEList;
  78214. struct ExprList_item *pItem;
  78215. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  78216. #if SQLITE_MAX_COLUMN
  78217. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  78218. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  78219. return 1;
  78220. }
  78221. #endif
  78222. pEList = pSelect->pEList;
  78223. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  78224. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  78225. if( pItem->u.x.iOrderByCol ){
  78226. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  78227. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  78228. return 1;
  78229. }
  78230. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
  78231. zType,0);
  78232. }
  78233. }
  78234. return 0;
  78235. }
  78236. /*
  78237. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  78238. ** The Name context of the SELECT statement is pNC. zType is either
  78239. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  78240. **
  78241. ** This routine resolves each term of the clause into an expression.
  78242. ** If the order-by term is an integer I between 1 and N (where N is the
  78243. ** number of columns in the result set of the SELECT) then the expression
  78244. ** in the resolution is a copy of the I-th result-set expression. If
  78245. ** the order-by term is an identifier that corresponds to the AS-name of
  78246. ** a result-set expression, then the term resolves to a copy of the
  78247. ** result-set expression. Otherwise, the expression is resolved in
  78248. ** the usual way - using sqlite3ResolveExprNames().
  78249. **
  78250. ** This routine returns the number of errors. If errors occur, then
  78251. ** an appropriate error message might be left in pParse. (OOM errors
  78252. ** excepted.)
  78253. */
  78254. static int resolveOrderGroupBy(
  78255. NameContext *pNC, /* The name context of the SELECT statement */
  78256. Select *pSelect, /* The SELECT statement holding pOrderBy */
  78257. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  78258. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  78259. ){
  78260. int i, j; /* Loop counters */
  78261. int iCol; /* Column number */
  78262. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  78263. Parse *pParse; /* Parsing context */
  78264. int nResult; /* Number of terms in the result set */
  78265. if( pOrderBy==0 ) return 0;
  78266. nResult = pSelect->pEList->nExpr;
  78267. pParse = pNC->pParse;
  78268. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  78269. Expr *pE = pItem->pExpr;
  78270. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  78271. if( zType[0]!='G' ){
  78272. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  78273. if( iCol>0 ){
  78274. /* If an AS-name match is found, mark this ORDER BY column as being
  78275. ** a copy of the iCol-th result-set column. The subsequent call to
  78276. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  78277. ** copy of the iCol-th result-set expression. */
  78278. pItem->u.x.iOrderByCol = (u16)iCol;
  78279. continue;
  78280. }
  78281. }
  78282. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  78283. /* The ORDER BY term is an integer constant. Again, set the column
  78284. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  78285. ** order-by term to a copy of the result-set expression */
  78286. if( iCol<1 || iCol>0xffff ){
  78287. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  78288. return 1;
  78289. }
  78290. pItem->u.x.iOrderByCol = (u16)iCol;
  78291. continue;
  78292. }
  78293. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  78294. pItem->u.x.iOrderByCol = 0;
  78295. if( sqlite3ResolveExprNames(pNC, pE) ){
  78296. return 1;
  78297. }
  78298. for(j=0; j<pSelect->pEList->nExpr; j++){
  78299. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  78300. pItem->u.x.iOrderByCol = j+1;
  78301. }
  78302. }
  78303. }
  78304. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  78305. }
  78306. /*
  78307. ** Resolve names in the SELECT statement p and all of its descendants.
  78308. */
  78309. static int resolveSelectStep(Walker *pWalker, Select *p){
  78310. NameContext *pOuterNC; /* Context that contains this SELECT */
  78311. NameContext sNC; /* Name context of this SELECT */
  78312. int isCompound; /* True if p is a compound select */
  78313. int nCompound; /* Number of compound terms processed so far */
  78314. Parse *pParse; /* Parsing context */
  78315. ExprList *pEList; /* Result set expression list */
  78316. int i; /* Loop counter */
  78317. ExprList *pGroupBy; /* The GROUP BY clause */
  78318. Select *pLeftmost; /* Left-most of SELECT of a compound */
  78319. sqlite3 *db; /* Database connection */
  78320. assert( p!=0 );
  78321. if( p->selFlags & SF_Resolved ){
  78322. return WRC_Prune;
  78323. }
  78324. pOuterNC = pWalker->u.pNC;
  78325. pParse = pWalker->pParse;
  78326. db = pParse->db;
  78327. /* Normally sqlite3SelectExpand() will be called first and will have
  78328. ** already expanded this SELECT. However, if this is a subquery within
  78329. ** an expression, sqlite3ResolveExprNames() will be called without a
  78330. ** prior call to sqlite3SelectExpand(). When that happens, let
  78331. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  78332. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  78333. ** this routine in the correct order.
  78334. */
  78335. if( (p->selFlags & SF_Expanded)==0 ){
  78336. sqlite3SelectPrep(pParse, p, pOuterNC);
  78337. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  78338. }
  78339. isCompound = p->pPrior!=0;
  78340. nCompound = 0;
  78341. pLeftmost = p;
  78342. while( p ){
  78343. assert( (p->selFlags & SF_Expanded)!=0 );
  78344. assert( (p->selFlags & SF_Resolved)==0 );
  78345. p->selFlags |= SF_Resolved;
  78346. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  78347. ** are not allowed to refer to any names, so pass an empty NameContext.
  78348. */
  78349. memset(&sNC, 0, sizeof(sNC));
  78350. sNC.pParse = pParse;
  78351. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  78352. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  78353. return WRC_Abort;
  78354. }
  78355. /* If the SF_Converted flags is set, then this Select object was
  78356. ** was created by the convertCompoundSelectToSubquery() function.
  78357. ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
  78358. ** as if it were part of the sub-query, not the parent. This block
  78359. ** moves the pOrderBy down to the sub-query. It will be moved back
  78360. ** after the names have been resolved. */
  78361. if( p->selFlags & SF_Converted ){
  78362. Select *pSub = p->pSrc->a[0].pSelect;
  78363. assert( p->pSrc->nSrc==1 && p->pOrderBy );
  78364. assert( pSub->pPrior && pSub->pOrderBy==0 );
  78365. pSub->pOrderBy = p->pOrderBy;
  78366. p->pOrderBy = 0;
  78367. }
  78368. /* Recursively resolve names in all subqueries
  78369. */
  78370. for(i=0; i<p->pSrc->nSrc; i++){
  78371. struct SrcList_item *pItem = &p->pSrc->a[i];
  78372. if( pItem->pSelect ){
  78373. NameContext *pNC; /* Used to iterate name contexts */
  78374. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  78375. const char *zSavedContext = pParse->zAuthContext;
  78376. /* Count the total number of references to pOuterNC and all of its
  78377. ** parent contexts. After resolving references to expressions in
  78378. ** pItem->pSelect, check if this value has changed. If so, then
  78379. ** SELECT statement pItem->pSelect must be correlated. Set the
  78380. ** pItem->isCorrelated flag if this is the case. */
  78381. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  78382. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  78383. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  78384. pParse->zAuthContext = zSavedContext;
  78385. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  78386. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  78387. assert( pItem->isCorrelated==0 && nRef<=0 );
  78388. pItem->isCorrelated = (nRef!=0);
  78389. }
  78390. }
  78391. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  78392. ** resolve the result-set expression list.
  78393. */
  78394. sNC.ncFlags = NC_AllowAgg;
  78395. sNC.pSrcList = p->pSrc;
  78396. sNC.pNext = pOuterNC;
  78397. /* Resolve names in the result set. */
  78398. pEList = p->pEList;
  78399. assert( pEList!=0 );
  78400. for(i=0; i<pEList->nExpr; i++){
  78401. Expr *pX = pEList->a[i].pExpr;
  78402. if( sqlite3ResolveExprNames(&sNC, pX) ){
  78403. return WRC_Abort;
  78404. }
  78405. }
  78406. /* If there are no aggregate functions in the result-set, and no GROUP BY
  78407. ** expression, do not allow aggregates in any of the other expressions.
  78408. */
  78409. assert( (p->selFlags & SF_Aggregate)==0 );
  78410. pGroupBy = p->pGroupBy;
  78411. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  78412. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  78413. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  78414. }else{
  78415. sNC.ncFlags &= ~NC_AllowAgg;
  78416. }
  78417. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  78418. */
  78419. if( p->pHaving && !pGroupBy ){
  78420. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  78421. return WRC_Abort;
  78422. }
  78423. /* Add the output column list to the name-context before parsing the
  78424. ** other expressions in the SELECT statement. This is so that
  78425. ** expressions in the WHERE clause (etc.) can refer to expressions by
  78426. ** aliases in the result set.
  78427. **
  78428. ** Minor point: If this is the case, then the expression will be
  78429. ** re-evaluated for each reference to it.
  78430. */
  78431. sNC.pEList = p->pEList;
  78432. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  78433. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  78434. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  78435. ** outer queries
  78436. */
  78437. sNC.pNext = 0;
  78438. sNC.ncFlags |= NC_AllowAgg;
  78439. /* If this is a converted compound query, move the ORDER BY clause from
  78440. ** the sub-query back to the parent query. At this point each term
  78441. ** within the ORDER BY clause has been transformed to an integer value.
  78442. ** These integers will be replaced by copies of the corresponding result
  78443. ** set expressions by the call to resolveOrderGroupBy() below. */
  78444. if( p->selFlags & SF_Converted ){
  78445. Select *pSub = p->pSrc->a[0].pSelect;
  78446. p->pOrderBy = pSub->pOrderBy;
  78447. pSub->pOrderBy = 0;
  78448. }
  78449. /* Process the ORDER BY clause for singleton SELECT statements.
  78450. ** The ORDER BY clause for compounds SELECT statements is handled
  78451. ** below, after all of the result-sets for all of the elements of
  78452. ** the compound have been resolved.
  78453. **
  78454. ** If there is an ORDER BY clause on a term of a compound-select other
  78455. ** than the right-most term, then that is a syntax error. But the error
  78456. ** is not detected until much later, and so we need to go ahead and
  78457. ** resolve those symbols on the incorrect ORDER BY for consistency.
  78458. */
  78459. if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
  78460. && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
  78461. ){
  78462. return WRC_Abort;
  78463. }
  78464. if( db->mallocFailed ){
  78465. return WRC_Abort;
  78466. }
  78467. /* Resolve the GROUP BY clause. At the same time, make sure
  78468. ** the GROUP BY clause does not contain aggregate functions.
  78469. */
  78470. if( pGroupBy ){
  78471. struct ExprList_item *pItem;
  78472. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  78473. return WRC_Abort;
  78474. }
  78475. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  78476. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  78477. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  78478. "the GROUP BY clause");
  78479. return WRC_Abort;
  78480. }
  78481. }
  78482. }
  78483. /* If this is part of a compound SELECT, check that it has the right
  78484. ** number of expressions in the select list. */
  78485. if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
  78486. sqlite3SelectWrongNumTermsError(pParse, p->pNext);
  78487. return WRC_Abort;
  78488. }
  78489. /* Advance to the next term of the compound
  78490. */
  78491. p = p->pPrior;
  78492. nCompound++;
  78493. }
  78494. /* Resolve the ORDER BY on a compound SELECT after all terms of
  78495. ** the compound have been resolved.
  78496. */
  78497. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  78498. return WRC_Abort;
  78499. }
  78500. return WRC_Prune;
  78501. }
  78502. /*
  78503. ** This routine walks an expression tree and resolves references to
  78504. ** table columns and result-set columns. At the same time, do error
  78505. ** checking on function usage and set a flag if any aggregate functions
  78506. ** are seen.
  78507. **
  78508. ** To resolve table columns references we look for nodes (or subtrees) of the
  78509. ** form X.Y.Z or Y.Z or just Z where
  78510. **
  78511. ** X: The name of a database. Ex: "main" or "temp" or
  78512. ** the symbolic name assigned to an ATTACH-ed database.
  78513. **
  78514. ** Y: The name of a table in a FROM clause. Or in a trigger
  78515. ** one of the special names "old" or "new".
  78516. **
  78517. ** Z: The name of a column in table Y.
  78518. **
  78519. ** The node at the root of the subtree is modified as follows:
  78520. **
  78521. ** Expr.op Changed to TK_COLUMN
  78522. ** Expr.pTab Points to the Table object for X.Y
  78523. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  78524. ** Expr.iTable The VDBE cursor number for X.Y
  78525. **
  78526. **
  78527. ** To resolve result-set references, look for expression nodes of the
  78528. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  78529. ** size of an AS clause in the result-set of a SELECT. The Z expression
  78530. ** is replaced by a copy of the left-hand side of the result-set expression.
  78531. ** Table-name and function resolution occurs on the substituted expression
  78532. ** tree. For example, in:
  78533. **
  78534. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  78535. **
  78536. ** The "x" term of the order by is replaced by "a+b" to render:
  78537. **
  78538. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  78539. **
  78540. ** Function calls are checked to make sure that the function is
  78541. ** defined and that the correct number of arguments are specified.
  78542. ** If the function is an aggregate function, then the NC_HasAgg flag is
  78543. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  78544. ** If an expression contains aggregate functions then the EP_Agg
  78545. ** property on the expression is set.
  78546. **
  78547. ** An error message is left in pParse if anything is amiss. The number
  78548. ** if errors is returned.
  78549. */
  78550. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  78551. NameContext *pNC, /* Namespace to resolve expressions in. */
  78552. Expr *pExpr /* The expression to be analyzed. */
  78553. ){
  78554. u16 savedHasAgg;
  78555. Walker w;
  78556. if( pExpr==0 ) return 0;
  78557. #if SQLITE_MAX_EXPR_DEPTH>0
  78558. {
  78559. Parse *pParse = pNC->pParse;
  78560. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  78561. return 1;
  78562. }
  78563. pParse->nHeight += pExpr->nHeight;
  78564. }
  78565. #endif
  78566. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  78567. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  78568. memset(&w, 0, sizeof(w));
  78569. w.xExprCallback = resolveExprStep;
  78570. w.xSelectCallback = resolveSelectStep;
  78571. w.pParse = pNC->pParse;
  78572. w.u.pNC = pNC;
  78573. sqlite3WalkExpr(&w, pExpr);
  78574. #if SQLITE_MAX_EXPR_DEPTH>0
  78575. pNC->pParse->nHeight -= pExpr->nHeight;
  78576. #endif
  78577. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  78578. ExprSetProperty(pExpr, EP_Error);
  78579. }
  78580. if( pNC->ncFlags & NC_HasAgg ){
  78581. ExprSetProperty(pExpr, EP_Agg);
  78582. }
  78583. pNC->ncFlags |= savedHasAgg;
  78584. return ExprHasProperty(pExpr, EP_Error);
  78585. }
  78586. /*
  78587. ** Resolve all names in all expressions of a SELECT and in all
  78588. ** decendents of the SELECT, including compounds off of p->pPrior,
  78589. ** subqueries in expressions, and subqueries used as FROM clause
  78590. ** terms.
  78591. **
  78592. ** See sqlite3ResolveExprNames() for a description of the kinds of
  78593. ** transformations that occur.
  78594. **
  78595. ** All SELECT statements should have been expanded using
  78596. ** sqlite3SelectExpand() prior to invoking this routine.
  78597. */
  78598. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  78599. Parse *pParse, /* The parser context */
  78600. Select *p, /* The SELECT statement being coded. */
  78601. NameContext *pOuterNC /* Name context for parent SELECT statement */
  78602. ){
  78603. Walker w;
  78604. assert( p!=0 );
  78605. memset(&w, 0, sizeof(w));
  78606. w.xExprCallback = resolveExprStep;
  78607. w.xSelectCallback = resolveSelectStep;
  78608. w.pParse = pParse;
  78609. w.u.pNC = pOuterNC;
  78610. sqlite3WalkSelect(&w, p);
  78611. }
  78612. /*
  78613. ** Resolve names in expressions that can only reference a single table:
  78614. **
  78615. ** * CHECK constraints
  78616. ** * WHERE clauses on partial indices
  78617. **
  78618. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  78619. ** is set to -1 and the Expr.iColumn value is set to the column number.
  78620. **
  78621. ** Any errors cause an error message to be set in pParse.
  78622. */
  78623. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  78624. Parse *pParse, /* Parsing context */
  78625. Table *pTab, /* The table being referenced */
  78626. int type, /* NC_IsCheck or NC_PartIdx */
  78627. Expr *pExpr, /* Expression to resolve. May be NULL. */
  78628. ExprList *pList /* Expression list to resolve. May be NUL. */
  78629. ){
  78630. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  78631. NameContext sNC; /* Name context for pParse->pNewTable */
  78632. int i; /* Loop counter */
  78633. assert( type==NC_IsCheck || type==NC_PartIdx );
  78634. memset(&sNC, 0, sizeof(sNC));
  78635. memset(&sSrc, 0, sizeof(sSrc));
  78636. sSrc.nSrc = 1;
  78637. sSrc.a[0].zName = pTab->zName;
  78638. sSrc.a[0].pTab = pTab;
  78639. sSrc.a[0].iCursor = -1;
  78640. sNC.pParse = pParse;
  78641. sNC.pSrcList = &sSrc;
  78642. sNC.ncFlags = type;
  78643. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  78644. if( pList ){
  78645. for(i=0; i<pList->nExpr; i++){
  78646. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  78647. return;
  78648. }
  78649. }
  78650. }
  78651. }
  78652. /************** End of resolve.c *********************************************/
  78653. /************** Begin file expr.c ********************************************/
  78654. /*
  78655. ** 2001 September 15
  78656. **
  78657. ** The author disclaims copyright to this source code. In place of
  78658. ** a legal notice, here is a blessing:
  78659. **
  78660. ** May you do good and not evil.
  78661. ** May you find forgiveness for yourself and forgive others.
  78662. ** May you share freely, never taking more than you give.
  78663. **
  78664. *************************************************************************
  78665. ** This file contains routines used for analyzing expressions and
  78666. ** for generating VDBE code that evaluates expressions in SQLite.
  78667. */
  78668. /* #include "sqliteInt.h" */
  78669. /*
  78670. ** Return the 'affinity' of the expression pExpr if any.
  78671. **
  78672. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  78673. ** or a sub-select with a column as the return value, then the
  78674. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  78675. ** indicating no affinity for the expression.
  78676. **
  78677. ** i.e. the WHERE clause expressions in the following statements all
  78678. ** have an affinity:
  78679. **
  78680. ** CREATE TABLE t1(a);
  78681. ** SELECT * FROM t1 WHERE a;
  78682. ** SELECT a AS b FROM t1 WHERE b;
  78683. ** SELECT * FROM t1 WHERE (select a from t1);
  78684. */
  78685. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  78686. int op;
  78687. pExpr = sqlite3ExprSkipCollate(pExpr);
  78688. if( pExpr->flags & EP_Generic ) return 0;
  78689. op = pExpr->op;
  78690. if( op==TK_SELECT ){
  78691. assert( pExpr->flags&EP_xIsSelect );
  78692. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  78693. }
  78694. #ifndef SQLITE_OMIT_CAST
  78695. if( op==TK_CAST ){
  78696. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78697. return sqlite3AffinityType(pExpr->u.zToken, 0);
  78698. }
  78699. #endif
  78700. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  78701. && pExpr->pTab!=0
  78702. ){
  78703. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  78704. ** a TK_COLUMN but was previously evaluated and cached in a register */
  78705. int j = pExpr->iColumn;
  78706. if( j<0 ) return SQLITE_AFF_INTEGER;
  78707. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  78708. return pExpr->pTab->aCol[j].affinity;
  78709. }
  78710. return pExpr->affinity;
  78711. }
  78712. /*
  78713. ** Set the collating sequence for expression pExpr to be the collating
  78714. ** sequence named by pToken. Return a pointer to a new Expr node that
  78715. ** implements the COLLATE operator.
  78716. **
  78717. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  78718. ** and the pExpr parameter is returned unchanged.
  78719. */
  78720. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  78721. Parse *pParse, /* Parsing context */
  78722. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  78723. const Token *pCollName, /* Name of collating sequence */
  78724. int dequote /* True to dequote pCollName */
  78725. ){
  78726. if( pCollName->n>0 ){
  78727. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
  78728. if( pNew ){
  78729. pNew->pLeft = pExpr;
  78730. pNew->flags |= EP_Collate|EP_Skip;
  78731. pExpr = pNew;
  78732. }
  78733. }
  78734. return pExpr;
  78735. }
  78736. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  78737. Token s;
  78738. assert( zC!=0 );
  78739. s.z = zC;
  78740. s.n = sqlite3Strlen30(s.z);
  78741. return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
  78742. }
  78743. /*
  78744. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  78745. ** or likelihood() function at the root of an expression.
  78746. */
  78747. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  78748. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  78749. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  78750. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  78751. assert( pExpr->x.pList->nExpr>0 );
  78752. assert( pExpr->op==TK_FUNCTION );
  78753. pExpr = pExpr->x.pList->a[0].pExpr;
  78754. }else{
  78755. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  78756. pExpr = pExpr->pLeft;
  78757. }
  78758. }
  78759. return pExpr;
  78760. }
  78761. /*
  78762. ** Return the collation sequence for the expression pExpr. If
  78763. ** there is no defined collating sequence, return NULL.
  78764. **
  78765. ** The collating sequence might be determined by a COLLATE operator
  78766. ** or by the presence of a column with a defined collating sequence.
  78767. ** COLLATE operators take first precedence. Left operands take
  78768. ** precedence over right operands.
  78769. */
  78770. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  78771. sqlite3 *db = pParse->db;
  78772. CollSeq *pColl = 0;
  78773. Expr *p = pExpr;
  78774. while( p ){
  78775. int op = p->op;
  78776. if( p->flags & EP_Generic ) break;
  78777. if( op==TK_CAST || op==TK_UPLUS ){
  78778. p = p->pLeft;
  78779. continue;
  78780. }
  78781. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  78782. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  78783. break;
  78784. }
  78785. if( (op==TK_AGG_COLUMN || op==TK_COLUMN
  78786. || op==TK_REGISTER || op==TK_TRIGGER)
  78787. && p->pTab!=0
  78788. ){
  78789. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  78790. ** a TK_COLUMN but was previously evaluated and cached in a register */
  78791. int j = p->iColumn;
  78792. if( j>=0 ){
  78793. const char *zColl = p->pTab->aCol[j].zColl;
  78794. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  78795. }
  78796. break;
  78797. }
  78798. if( p->flags & EP_Collate ){
  78799. if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
  78800. p = p->pLeft;
  78801. }else{
  78802. Expr *pNext = p->pRight;
  78803. /* The Expr.x union is never used at the same time as Expr.pRight */
  78804. assert( p->x.pList==0 || p->pRight==0 );
  78805. /* p->flags holds EP_Collate and p->pLeft->flags does not. And
  78806. ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
  78807. ** least one EP_Collate. Thus the following two ALWAYS. */
  78808. if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
  78809. int i;
  78810. for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
  78811. if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
  78812. pNext = p->x.pList->a[i].pExpr;
  78813. break;
  78814. }
  78815. }
  78816. }
  78817. p = pNext;
  78818. }
  78819. }else{
  78820. break;
  78821. }
  78822. }
  78823. if( sqlite3CheckCollSeq(pParse, pColl) ){
  78824. pColl = 0;
  78825. }
  78826. return pColl;
  78827. }
  78828. /*
  78829. ** pExpr is an operand of a comparison operator. aff2 is the
  78830. ** type affinity of the other operand. This routine returns the
  78831. ** type affinity that should be used for the comparison operator.
  78832. */
  78833. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  78834. char aff1 = sqlite3ExprAffinity(pExpr);
  78835. if( aff1 && aff2 ){
  78836. /* Both sides of the comparison are columns. If one has numeric
  78837. ** affinity, use that. Otherwise use no affinity.
  78838. */
  78839. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  78840. return SQLITE_AFF_NUMERIC;
  78841. }else{
  78842. return SQLITE_AFF_BLOB;
  78843. }
  78844. }else if( !aff1 && !aff2 ){
  78845. /* Neither side of the comparison is a column. Compare the
  78846. ** results directly.
  78847. */
  78848. return SQLITE_AFF_BLOB;
  78849. }else{
  78850. /* One side is a column, the other is not. Use the columns affinity. */
  78851. assert( aff1==0 || aff2==0 );
  78852. return (aff1 + aff2);
  78853. }
  78854. }
  78855. /*
  78856. ** pExpr is a comparison operator. Return the type affinity that should
  78857. ** be applied to both operands prior to doing the comparison.
  78858. */
  78859. static char comparisonAffinity(Expr *pExpr){
  78860. char aff;
  78861. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  78862. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  78863. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  78864. assert( pExpr->pLeft );
  78865. aff = sqlite3ExprAffinity(pExpr->pLeft);
  78866. if( pExpr->pRight ){
  78867. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  78868. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  78869. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  78870. }else if( !aff ){
  78871. aff = SQLITE_AFF_BLOB;
  78872. }
  78873. return aff;
  78874. }
  78875. /*
  78876. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  78877. ** idx_affinity is the affinity of an indexed column. Return true
  78878. ** if the index with affinity idx_affinity may be used to implement
  78879. ** the comparison in pExpr.
  78880. */
  78881. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  78882. char aff = comparisonAffinity(pExpr);
  78883. switch( aff ){
  78884. case SQLITE_AFF_BLOB:
  78885. return 1;
  78886. case SQLITE_AFF_TEXT:
  78887. return idx_affinity==SQLITE_AFF_TEXT;
  78888. default:
  78889. return sqlite3IsNumericAffinity(idx_affinity);
  78890. }
  78891. }
  78892. /*
  78893. ** Return the P5 value that should be used for a binary comparison
  78894. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  78895. */
  78896. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  78897. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  78898. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  78899. return aff;
  78900. }
  78901. /*
  78902. ** Return a pointer to the collation sequence that should be used by
  78903. ** a binary comparison operator comparing pLeft and pRight.
  78904. **
  78905. ** If the left hand expression has a collating sequence type, then it is
  78906. ** used. Otherwise the collation sequence for the right hand expression
  78907. ** is used, or the default (BINARY) if neither expression has a collating
  78908. ** type.
  78909. **
  78910. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  78911. ** it is not considered.
  78912. */
  78913. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  78914. Parse *pParse,
  78915. Expr *pLeft,
  78916. Expr *pRight
  78917. ){
  78918. CollSeq *pColl;
  78919. assert( pLeft );
  78920. if( pLeft->flags & EP_Collate ){
  78921. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  78922. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  78923. pColl = sqlite3ExprCollSeq(pParse, pRight);
  78924. }else{
  78925. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  78926. if( !pColl ){
  78927. pColl = sqlite3ExprCollSeq(pParse, pRight);
  78928. }
  78929. }
  78930. return pColl;
  78931. }
  78932. /*
  78933. ** Generate code for a comparison operator.
  78934. */
  78935. static int codeCompare(
  78936. Parse *pParse, /* The parsing (and code generating) context */
  78937. Expr *pLeft, /* The left operand */
  78938. Expr *pRight, /* The right operand */
  78939. int opcode, /* The comparison opcode */
  78940. int in1, int in2, /* Register holding operands */
  78941. int dest, /* Jump here if true. */
  78942. int jumpIfNull /* If true, jump if either operand is NULL */
  78943. ){
  78944. int p5;
  78945. int addr;
  78946. CollSeq *p4;
  78947. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  78948. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  78949. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  78950. (void*)p4, P4_COLLSEQ);
  78951. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  78952. return addr;
  78953. }
  78954. #if SQLITE_MAX_EXPR_DEPTH>0
  78955. /*
  78956. ** Check that argument nHeight is less than or equal to the maximum
  78957. ** expression depth allowed. If it is not, leave an error message in
  78958. ** pParse.
  78959. */
  78960. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  78961. int rc = SQLITE_OK;
  78962. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  78963. if( nHeight>mxHeight ){
  78964. sqlite3ErrorMsg(pParse,
  78965. "Expression tree is too large (maximum depth %d)", mxHeight
  78966. );
  78967. rc = SQLITE_ERROR;
  78968. }
  78969. return rc;
  78970. }
  78971. /* The following three functions, heightOfExpr(), heightOfExprList()
  78972. ** and heightOfSelect(), are used to determine the maximum height
  78973. ** of any expression tree referenced by the structure passed as the
  78974. ** first argument.
  78975. **
  78976. ** If this maximum height is greater than the current value pointed
  78977. ** to by pnHeight, the second parameter, then set *pnHeight to that
  78978. ** value.
  78979. */
  78980. static void heightOfExpr(Expr *p, int *pnHeight){
  78981. if( p ){
  78982. if( p->nHeight>*pnHeight ){
  78983. *pnHeight = p->nHeight;
  78984. }
  78985. }
  78986. }
  78987. static void heightOfExprList(ExprList *p, int *pnHeight){
  78988. if( p ){
  78989. int i;
  78990. for(i=0; i<p->nExpr; i++){
  78991. heightOfExpr(p->a[i].pExpr, pnHeight);
  78992. }
  78993. }
  78994. }
  78995. static void heightOfSelect(Select *p, int *pnHeight){
  78996. if( p ){
  78997. heightOfExpr(p->pWhere, pnHeight);
  78998. heightOfExpr(p->pHaving, pnHeight);
  78999. heightOfExpr(p->pLimit, pnHeight);
  79000. heightOfExpr(p->pOffset, pnHeight);
  79001. heightOfExprList(p->pEList, pnHeight);
  79002. heightOfExprList(p->pGroupBy, pnHeight);
  79003. heightOfExprList(p->pOrderBy, pnHeight);
  79004. heightOfSelect(p->pPrior, pnHeight);
  79005. }
  79006. }
  79007. /*
  79008. ** Set the Expr.nHeight variable in the structure passed as an
  79009. ** argument. An expression with no children, Expr.pList or
  79010. ** Expr.pSelect member has a height of 1. Any other expression
  79011. ** has a height equal to the maximum height of any other
  79012. ** referenced Expr plus one.
  79013. **
  79014. ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
  79015. ** if appropriate.
  79016. */
  79017. static void exprSetHeight(Expr *p){
  79018. int nHeight = 0;
  79019. heightOfExpr(p->pLeft, &nHeight);
  79020. heightOfExpr(p->pRight, &nHeight);
  79021. if( ExprHasProperty(p, EP_xIsSelect) ){
  79022. heightOfSelect(p->x.pSelect, &nHeight);
  79023. }else if( p->x.pList ){
  79024. heightOfExprList(p->x.pList, &nHeight);
  79025. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  79026. }
  79027. p->nHeight = nHeight + 1;
  79028. }
  79029. /*
  79030. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  79031. ** the height is greater than the maximum allowed expression depth,
  79032. ** leave an error in pParse.
  79033. **
  79034. ** Also propagate all EP_Propagate flags from the Expr.x.pList into
  79035. ** Expr.flags.
  79036. */
  79037. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  79038. if( pParse->nErr ) return;
  79039. exprSetHeight(p);
  79040. sqlite3ExprCheckHeight(pParse, p->nHeight);
  79041. }
  79042. /*
  79043. ** Return the maximum height of any expression tree referenced
  79044. ** by the select statement passed as an argument.
  79045. */
  79046. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  79047. int nHeight = 0;
  79048. heightOfSelect(p, &nHeight);
  79049. return nHeight;
  79050. }
  79051. #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
  79052. /*
  79053. ** Propagate all EP_Propagate flags from the Expr.x.pList into
  79054. ** Expr.flags.
  79055. */
  79056. SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
  79057. if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
  79058. p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
  79059. }
  79060. }
  79061. #define exprSetHeight(y)
  79062. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  79063. /*
  79064. ** This routine is the core allocator for Expr nodes.
  79065. **
  79066. ** Construct a new expression node and return a pointer to it. Memory
  79067. ** for this node and for the pToken argument is a single allocation
  79068. ** obtained from sqlite3DbMalloc(). The calling function
  79069. ** is responsible for making sure the node eventually gets freed.
  79070. **
  79071. ** If dequote is true, then the token (if it exists) is dequoted.
  79072. ** If dequote is false, no dequoting is performance. The deQuote
  79073. ** parameter is ignored if pToken is NULL or if the token does not
  79074. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  79075. ** then the EP_DblQuoted flag is set on the expression node.
  79076. **
  79077. ** Special case: If op==TK_INTEGER and pToken points to a string that
  79078. ** can be translated into a 32-bit integer, then the token is not
  79079. ** stored in u.zToken. Instead, the integer values is written
  79080. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  79081. ** is allocated to hold the integer text and the dequote flag is ignored.
  79082. */
  79083. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  79084. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  79085. int op, /* Expression opcode */
  79086. const Token *pToken, /* Token argument. Might be NULL */
  79087. int dequote /* True to dequote */
  79088. ){
  79089. Expr *pNew;
  79090. int nExtra = 0;
  79091. int iValue = 0;
  79092. if( pToken ){
  79093. if( op!=TK_INTEGER || pToken->z==0
  79094. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  79095. nExtra = pToken->n+1;
  79096. assert( iValue>=0 );
  79097. }
  79098. }
  79099. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  79100. if( pNew ){
  79101. pNew->op = (u8)op;
  79102. pNew->iAgg = -1;
  79103. if( pToken ){
  79104. if( nExtra==0 ){
  79105. pNew->flags |= EP_IntValue;
  79106. pNew->u.iValue = iValue;
  79107. }else{
  79108. int c;
  79109. pNew->u.zToken = (char*)&pNew[1];
  79110. assert( pToken->z!=0 || pToken->n==0 );
  79111. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  79112. pNew->u.zToken[pToken->n] = 0;
  79113. if( dequote && nExtra>=3
  79114. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  79115. sqlite3Dequote(pNew->u.zToken);
  79116. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  79117. }
  79118. }
  79119. }
  79120. #if SQLITE_MAX_EXPR_DEPTH>0
  79121. pNew->nHeight = 1;
  79122. #endif
  79123. }
  79124. return pNew;
  79125. }
  79126. /*
  79127. ** Allocate a new expression node from a zero-terminated token that has
  79128. ** already been dequoted.
  79129. */
  79130. SQLITE_PRIVATE Expr *sqlite3Expr(
  79131. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  79132. int op, /* Expression opcode */
  79133. const char *zToken /* Token argument. Might be NULL */
  79134. ){
  79135. Token x;
  79136. x.z = zToken;
  79137. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  79138. return sqlite3ExprAlloc(db, op, &x, 0);
  79139. }
  79140. /*
  79141. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  79142. **
  79143. ** If pRoot==NULL that means that a memory allocation error has occurred.
  79144. ** In that case, delete the subtrees pLeft and pRight.
  79145. */
  79146. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  79147. sqlite3 *db,
  79148. Expr *pRoot,
  79149. Expr *pLeft,
  79150. Expr *pRight
  79151. ){
  79152. if( pRoot==0 ){
  79153. assert( db->mallocFailed );
  79154. sqlite3ExprDelete(db, pLeft);
  79155. sqlite3ExprDelete(db, pRight);
  79156. }else{
  79157. if( pRight ){
  79158. pRoot->pRight = pRight;
  79159. pRoot->flags |= EP_Propagate & pRight->flags;
  79160. }
  79161. if( pLeft ){
  79162. pRoot->pLeft = pLeft;
  79163. pRoot->flags |= EP_Propagate & pLeft->flags;
  79164. }
  79165. exprSetHeight(pRoot);
  79166. }
  79167. }
  79168. /*
  79169. ** Allocate an Expr node which joins as many as two subtrees.
  79170. **
  79171. ** One or both of the subtrees can be NULL. Return a pointer to the new
  79172. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  79173. ** free the subtrees and return NULL.
  79174. */
  79175. SQLITE_PRIVATE Expr *sqlite3PExpr(
  79176. Parse *pParse, /* Parsing context */
  79177. int op, /* Expression opcode */
  79178. Expr *pLeft, /* Left operand */
  79179. Expr *pRight, /* Right operand */
  79180. const Token *pToken /* Argument token */
  79181. ){
  79182. Expr *p;
  79183. if( op==TK_AND && pLeft && pRight && pParse->nErr==0 ){
  79184. /* Take advantage of short-circuit false optimization for AND */
  79185. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  79186. }else{
  79187. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  79188. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  79189. }
  79190. if( p ) {
  79191. sqlite3ExprCheckHeight(pParse, p->nHeight);
  79192. }
  79193. return p;
  79194. }
  79195. /*
  79196. ** If the expression is always either TRUE or FALSE (respectively),
  79197. ** then return 1. If one cannot determine the truth value of the
  79198. ** expression at compile-time return 0.
  79199. **
  79200. ** This is an optimization. If is OK to return 0 here even if
  79201. ** the expression really is always false or false (a false negative).
  79202. ** But it is a bug to return 1 if the expression might have different
  79203. ** boolean values in different circumstances (a false positive.)
  79204. **
  79205. ** Note that if the expression is part of conditional for a
  79206. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  79207. ** is it true or false, so always return 0.
  79208. */
  79209. static int exprAlwaysTrue(Expr *p){
  79210. int v = 0;
  79211. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  79212. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  79213. return v!=0;
  79214. }
  79215. static int exprAlwaysFalse(Expr *p){
  79216. int v = 0;
  79217. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  79218. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  79219. return v==0;
  79220. }
  79221. /*
  79222. ** Join two expressions using an AND operator. If either expression is
  79223. ** NULL, then just return the other expression.
  79224. **
  79225. ** If one side or the other of the AND is known to be false, then instead
  79226. ** of returning an AND expression, just return a constant expression with
  79227. ** a value of false.
  79228. */
  79229. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  79230. if( pLeft==0 ){
  79231. return pRight;
  79232. }else if( pRight==0 ){
  79233. return pLeft;
  79234. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  79235. sqlite3ExprDelete(db, pLeft);
  79236. sqlite3ExprDelete(db, pRight);
  79237. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  79238. }else{
  79239. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  79240. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  79241. return pNew;
  79242. }
  79243. }
  79244. /*
  79245. ** Construct a new expression node for a function with multiple
  79246. ** arguments.
  79247. */
  79248. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  79249. Expr *pNew;
  79250. sqlite3 *db = pParse->db;
  79251. assert( pToken );
  79252. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  79253. if( pNew==0 ){
  79254. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  79255. return 0;
  79256. }
  79257. pNew->x.pList = pList;
  79258. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  79259. sqlite3ExprSetHeightAndFlags(pParse, pNew);
  79260. return pNew;
  79261. }
  79262. /*
  79263. ** Assign a variable number to an expression that encodes a wildcard
  79264. ** in the original SQL statement.
  79265. **
  79266. ** Wildcards consisting of a single "?" are assigned the next sequential
  79267. ** variable number.
  79268. **
  79269. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  79270. ** sure "nnn" is not too be to avoid a denial of service attack when
  79271. ** the SQL statement comes from an external source.
  79272. **
  79273. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  79274. ** as the previous instance of the same wildcard. Or if this is the first
  79275. ** instance of the wildcard, the next sequential variable number is
  79276. ** assigned.
  79277. */
  79278. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  79279. sqlite3 *db = pParse->db;
  79280. const char *z;
  79281. if( pExpr==0 ) return;
  79282. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  79283. z = pExpr->u.zToken;
  79284. assert( z!=0 );
  79285. assert( z[0]!=0 );
  79286. if( z[1]==0 ){
  79287. /* Wildcard of the form "?". Assign the next variable number */
  79288. assert( z[0]=='?' );
  79289. pExpr->iColumn = (ynVar)(++pParse->nVar);
  79290. }else{
  79291. ynVar x = 0;
  79292. u32 n = sqlite3Strlen30(z);
  79293. if( z[0]=='?' ){
  79294. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  79295. ** use it as the variable number */
  79296. i64 i;
  79297. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  79298. pExpr->iColumn = x = (ynVar)i;
  79299. testcase( i==0 );
  79300. testcase( i==1 );
  79301. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  79302. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  79303. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  79304. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  79305. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  79306. x = 0;
  79307. }
  79308. if( i>pParse->nVar ){
  79309. pParse->nVar = (int)i;
  79310. }
  79311. }else{
  79312. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  79313. ** number as the prior appearance of the same name, or if the name
  79314. ** has never appeared before, reuse the same variable number
  79315. */
  79316. ynVar i;
  79317. for(i=0; i<pParse->nzVar; i++){
  79318. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  79319. pExpr->iColumn = x = (ynVar)i+1;
  79320. break;
  79321. }
  79322. }
  79323. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  79324. }
  79325. if( x>0 ){
  79326. if( x>pParse->nzVar ){
  79327. char **a;
  79328. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  79329. if( a==0 ) return; /* Error reported through db->mallocFailed */
  79330. pParse->azVar = a;
  79331. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  79332. pParse->nzVar = x;
  79333. }
  79334. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  79335. sqlite3DbFree(db, pParse->azVar[x-1]);
  79336. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  79337. }
  79338. }
  79339. }
  79340. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  79341. sqlite3ErrorMsg(pParse, "too many SQL variables");
  79342. }
  79343. }
  79344. /*
  79345. ** Recursively delete an expression tree.
  79346. */
  79347. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  79348. if( p==0 ) return;
  79349. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  79350. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  79351. if( !ExprHasProperty(p, EP_TokenOnly) ){
  79352. /* The Expr.x union is never used at the same time as Expr.pRight */
  79353. assert( p->x.pList==0 || p->pRight==0 );
  79354. sqlite3ExprDelete(db, p->pLeft);
  79355. sqlite3ExprDelete(db, p->pRight);
  79356. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  79357. if( ExprHasProperty(p, EP_xIsSelect) ){
  79358. sqlite3SelectDelete(db, p->x.pSelect);
  79359. }else{
  79360. sqlite3ExprListDelete(db, p->x.pList);
  79361. }
  79362. }
  79363. if( !ExprHasProperty(p, EP_Static) ){
  79364. sqlite3DbFree(db, p);
  79365. }
  79366. }
  79367. /*
  79368. ** Return the number of bytes allocated for the expression structure
  79369. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  79370. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  79371. */
  79372. static int exprStructSize(Expr *p){
  79373. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  79374. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  79375. return EXPR_FULLSIZE;
  79376. }
  79377. /*
  79378. ** The dupedExpr*Size() routines each return the number of bytes required
  79379. ** to store a copy of an expression or expression tree. They differ in
  79380. ** how much of the tree is measured.
  79381. **
  79382. ** dupedExprStructSize() Size of only the Expr structure
  79383. ** dupedExprNodeSize() Size of Expr + space for token
  79384. ** dupedExprSize() Expr + token + subtree components
  79385. **
  79386. ***************************************************************************
  79387. **
  79388. ** The dupedExprStructSize() function returns two values OR-ed together:
  79389. ** (1) the space required for a copy of the Expr structure only and
  79390. ** (2) the EP_xxx flags that indicate what the structure size should be.
  79391. ** The return values is always one of:
  79392. **
  79393. ** EXPR_FULLSIZE
  79394. ** EXPR_REDUCEDSIZE | EP_Reduced
  79395. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  79396. **
  79397. ** The size of the structure can be found by masking the return value
  79398. ** of this routine with 0xfff. The flags can be found by masking the
  79399. ** return value with EP_Reduced|EP_TokenOnly.
  79400. **
  79401. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  79402. ** (unreduced) Expr objects as they or originally constructed by the parser.
  79403. ** During expression analysis, extra information is computed and moved into
  79404. ** later parts of teh Expr object and that extra information might get chopped
  79405. ** off if the expression is reduced. Note also that it does not work to
  79406. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  79407. ** to reduce a pristine expression tree from the parser. The implementation
  79408. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  79409. ** to enforce this constraint.
  79410. */
  79411. static int dupedExprStructSize(Expr *p, int flags){
  79412. int nSize;
  79413. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  79414. assert( EXPR_FULLSIZE<=0xfff );
  79415. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  79416. if( 0==(flags&EXPRDUP_REDUCE) ){
  79417. nSize = EXPR_FULLSIZE;
  79418. }else{
  79419. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  79420. assert( !ExprHasProperty(p, EP_FromJoin) );
  79421. assert( !ExprHasProperty(p, EP_MemToken) );
  79422. assert( !ExprHasProperty(p, EP_NoReduce) );
  79423. if( p->pLeft || p->x.pList ){
  79424. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  79425. }else{
  79426. assert( p->pRight==0 );
  79427. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  79428. }
  79429. }
  79430. return nSize;
  79431. }
  79432. /*
  79433. ** This function returns the space in bytes required to store the copy
  79434. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  79435. ** string is defined.)
  79436. */
  79437. static int dupedExprNodeSize(Expr *p, int flags){
  79438. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  79439. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  79440. nByte += sqlite3Strlen30(p->u.zToken)+1;
  79441. }
  79442. return ROUND8(nByte);
  79443. }
  79444. /*
  79445. ** Return the number of bytes required to create a duplicate of the
  79446. ** expression passed as the first argument. The second argument is a
  79447. ** mask containing EXPRDUP_XXX flags.
  79448. **
  79449. ** The value returned includes space to create a copy of the Expr struct
  79450. ** itself and the buffer referred to by Expr.u.zToken, if any.
  79451. **
  79452. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  79453. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  79454. ** and Expr.pRight variables (but not for any structures pointed to or
  79455. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  79456. */
  79457. static int dupedExprSize(Expr *p, int flags){
  79458. int nByte = 0;
  79459. if( p ){
  79460. nByte = dupedExprNodeSize(p, flags);
  79461. if( flags&EXPRDUP_REDUCE ){
  79462. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  79463. }
  79464. }
  79465. return nByte;
  79466. }
  79467. /*
  79468. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  79469. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  79470. ** to store the copy of expression p, the copies of p->u.zToken
  79471. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  79472. ** if any. Before returning, *pzBuffer is set to the first byte past the
  79473. ** portion of the buffer copied into by this function.
  79474. */
  79475. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  79476. Expr *pNew = 0; /* Value to return */
  79477. if( p ){
  79478. const int isReduced = (flags&EXPRDUP_REDUCE);
  79479. u8 *zAlloc;
  79480. u32 staticFlag = 0;
  79481. assert( pzBuffer==0 || isReduced );
  79482. /* Figure out where to write the new Expr structure. */
  79483. if( pzBuffer ){
  79484. zAlloc = *pzBuffer;
  79485. staticFlag = EP_Static;
  79486. }else{
  79487. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  79488. }
  79489. pNew = (Expr *)zAlloc;
  79490. if( pNew ){
  79491. /* Set nNewSize to the size allocated for the structure pointed to
  79492. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  79493. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  79494. ** by the copy of the p->u.zToken string (if any).
  79495. */
  79496. const unsigned nStructSize = dupedExprStructSize(p, flags);
  79497. const int nNewSize = nStructSize & 0xfff;
  79498. int nToken;
  79499. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  79500. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  79501. }else{
  79502. nToken = 0;
  79503. }
  79504. if( isReduced ){
  79505. assert( ExprHasProperty(p, EP_Reduced)==0 );
  79506. memcpy(zAlloc, p, nNewSize);
  79507. }else{
  79508. int nSize = exprStructSize(p);
  79509. memcpy(zAlloc, p, nSize);
  79510. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  79511. }
  79512. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  79513. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  79514. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  79515. pNew->flags |= staticFlag;
  79516. /* Copy the p->u.zToken string, if any. */
  79517. if( nToken ){
  79518. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  79519. memcpy(zToken, p->u.zToken, nToken);
  79520. }
  79521. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  79522. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  79523. if( ExprHasProperty(p, EP_xIsSelect) ){
  79524. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  79525. }else{
  79526. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  79527. }
  79528. }
  79529. /* Fill in pNew->pLeft and pNew->pRight. */
  79530. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  79531. zAlloc += dupedExprNodeSize(p, flags);
  79532. if( ExprHasProperty(pNew, EP_Reduced) ){
  79533. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  79534. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  79535. }
  79536. if( pzBuffer ){
  79537. *pzBuffer = zAlloc;
  79538. }
  79539. }else{
  79540. if( !ExprHasProperty(p, EP_TokenOnly) ){
  79541. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  79542. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  79543. }
  79544. }
  79545. }
  79546. }
  79547. return pNew;
  79548. }
  79549. /*
  79550. ** Create and return a deep copy of the object passed as the second
  79551. ** argument. If an OOM condition is encountered, NULL is returned
  79552. ** and the db->mallocFailed flag set.
  79553. */
  79554. #ifndef SQLITE_OMIT_CTE
  79555. static With *withDup(sqlite3 *db, With *p){
  79556. With *pRet = 0;
  79557. if( p ){
  79558. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  79559. pRet = sqlite3DbMallocZero(db, nByte);
  79560. if( pRet ){
  79561. int i;
  79562. pRet->nCte = p->nCte;
  79563. for(i=0; i<p->nCte; i++){
  79564. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  79565. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  79566. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  79567. }
  79568. }
  79569. }
  79570. return pRet;
  79571. }
  79572. #else
  79573. # define withDup(x,y) 0
  79574. #endif
  79575. /*
  79576. ** The following group of routines make deep copies of expressions,
  79577. ** expression lists, ID lists, and select statements. The copies can
  79578. ** be deleted (by being passed to their respective ...Delete() routines)
  79579. ** without effecting the originals.
  79580. **
  79581. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  79582. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  79583. ** by subsequent calls to sqlite*ListAppend() routines.
  79584. **
  79585. ** Any tables that the SrcList might point to are not duplicated.
  79586. **
  79587. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  79588. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  79589. ** truncated version of the usual Expr structure that will be stored as
  79590. ** part of the in-memory representation of the database schema.
  79591. */
  79592. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  79593. return exprDup(db, p, flags, 0);
  79594. }
  79595. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  79596. ExprList *pNew;
  79597. struct ExprList_item *pItem, *pOldItem;
  79598. int i;
  79599. if( p==0 ) return 0;
  79600. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  79601. if( pNew==0 ) return 0;
  79602. pNew->nExpr = i = p->nExpr;
  79603. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  79604. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  79605. if( pItem==0 ){
  79606. sqlite3DbFree(db, pNew);
  79607. return 0;
  79608. }
  79609. pOldItem = p->a;
  79610. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  79611. Expr *pOldExpr = pOldItem->pExpr;
  79612. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  79613. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  79614. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  79615. pItem->sortOrder = pOldItem->sortOrder;
  79616. pItem->done = 0;
  79617. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  79618. pItem->u = pOldItem->u;
  79619. }
  79620. return pNew;
  79621. }
  79622. /*
  79623. ** If cursors, triggers, views and subqueries are all omitted from
  79624. ** the build, then none of the following routines, except for
  79625. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  79626. ** called with a NULL argument.
  79627. */
  79628. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  79629. || !defined(SQLITE_OMIT_SUBQUERY)
  79630. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  79631. SrcList *pNew;
  79632. int i;
  79633. int nByte;
  79634. if( p==0 ) return 0;
  79635. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  79636. pNew = sqlite3DbMallocRaw(db, nByte );
  79637. if( pNew==0 ) return 0;
  79638. pNew->nSrc = pNew->nAlloc = p->nSrc;
  79639. for(i=0; i<p->nSrc; i++){
  79640. struct SrcList_item *pNewItem = &pNew->a[i];
  79641. struct SrcList_item *pOldItem = &p->a[i];
  79642. Table *pTab;
  79643. pNewItem->pSchema = pOldItem->pSchema;
  79644. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  79645. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  79646. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  79647. pNewItem->jointype = pOldItem->jointype;
  79648. pNewItem->iCursor = pOldItem->iCursor;
  79649. pNewItem->addrFillSub = pOldItem->addrFillSub;
  79650. pNewItem->regReturn = pOldItem->regReturn;
  79651. pNewItem->isCorrelated = pOldItem->isCorrelated;
  79652. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  79653. pNewItem->isRecursive = pOldItem->isRecursive;
  79654. pNewItem->zIndexedBy = sqlite3DbStrDup(db, pOldItem->zIndexedBy);
  79655. pNewItem->notIndexed = pOldItem->notIndexed;
  79656. pNewItem->pIndex = pOldItem->pIndex;
  79657. pTab = pNewItem->pTab = pOldItem->pTab;
  79658. if( pTab ){
  79659. pTab->nRef++;
  79660. }
  79661. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  79662. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  79663. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  79664. pNewItem->colUsed = pOldItem->colUsed;
  79665. }
  79666. return pNew;
  79667. }
  79668. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  79669. IdList *pNew;
  79670. int i;
  79671. if( p==0 ) return 0;
  79672. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  79673. if( pNew==0 ) return 0;
  79674. pNew->nId = p->nId;
  79675. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  79676. if( pNew->a==0 ){
  79677. sqlite3DbFree(db, pNew);
  79678. return 0;
  79679. }
  79680. /* Note that because the size of the allocation for p->a[] is not
  79681. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  79682. ** on the duplicate created by this function. */
  79683. for(i=0; i<p->nId; i++){
  79684. struct IdList_item *pNewItem = &pNew->a[i];
  79685. struct IdList_item *pOldItem = &p->a[i];
  79686. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  79687. pNewItem->idx = pOldItem->idx;
  79688. }
  79689. return pNew;
  79690. }
  79691. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  79692. Select *pNew, *pPrior;
  79693. if( p==0 ) return 0;
  79694. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  79695. if( pNew==0 ) return 0;
  79696. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  79697. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  79698. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  79699. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  79700. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  79701. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  79702. pNew->op = p->op;
  79703. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  79704. if( pPrior ) pPrior->pNext = pNew;
  79705. pNew->pNext = 0;
  79706. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  79707. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  79708. pNew->iLimit = 0;
  79709. pNew->iOffset = 0;
  79710. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  79711. pNew->addrOpenEphm[0] = -1;
  79712. pNew->addrOpenEphm[1] = -1;
  79713. pNew->nSelectRow = p->nSelectRow;
  79714. pNew->pWith = withDup(db, p->pWith);
  79715. sqlite3SelectSetName(pNew, p->zSelName);
  79716. return pNew;
  79717. }
  79718. #else
  79719. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  79720. assert( p==0 );
  79721. return 0;
  79722. }
  79723. #endif
  79724. /*
  79725. ** Add a new element to the end of an expression list. If pList is
  79726. ** initially NULL, then create a new expression list.
  79727. **
  79728. ** If a memory allocation error occurs, the entire list is freed and
  79729. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  79730. ** that the new entry was successfully appended.
  79731. */
  79732. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  79733. Parse *pParse, /* Parsing context */
  79734. ExprList *pList, /* List to which to append. Might be NULL */
  79735. Expr *pExpr /* Expression to be appended. Might be NULL */
  79736. ){
  79737. sqlite3 *db = pParse->db;
  79738. if( pList==0 ){
  79739. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  79740. if( pList==0 ){
  79741. goto no_mem;
  79742. }
  79743. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  79744. if( pList->a==0 ) goto no_mem;
  79745. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  79746. struct ExprList_item *a;
  79747. assert( pList->nExpr>0 );
  79748. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  79749. if( a==0 ){
  79750. goto no_mem;
  79751. }
  79752. pList->a = a;
  79753. }
  79754. assert( pList->a!=0 );
  79755. if( 1 ){
  79756. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  79757. memset(pItem, 0, sizeof(*pItem));
  79758. pItem->pExpr = pExpr;
  79759. }
  79760. return pList;
  79761. no_mem:
  79762. /* Avoid leaking memory if malloc has failed. */
  79763. sqlite3ExprDelete(db, pExpr);
  79764. sqlite3ExprListDelete(db, pList);
  79765. return 0;
  79766. }
  79767. /*
  79768. ** Set the ExprList.a[].zName element of the most recently added item
  79769. ** on the expression list.
  79770. **
  79771. ** pList might be NULL following an OOM error. But pName should never be
  79772. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  79773. ** is set.
  79774. */
  79775. SQLITE_PRIVATE void sqlite3ExprListSetName(
  79776. Parse *pParse, /* Parsing context */
  79777. ExprList *pList, /* List to which to add the span. */
  79778. Token *pName, /* Name to be added */
  79779. int dequote /* True to cause the name to be dequoted */
  79780. ){
  79781. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  79782. if( pList ){
  79783. struct ExprList_item *pItem;
  79784. assert( pList->nExpr>0 );
  79785. pItem = &pList->a[pList->nExpr-1];
  79786. assert( pItem->zName==0 );
  79787. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  79788. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  79789. }
  79790. }
  79791. /*
  79792. ** Set the ExprList.a[].zSpan element of the most recently added item
  79793. ** on the expression list.
  79794. **
  79795. ** pList might be NULL following an OOM error. But pSpan should never be
  79796. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  79797. ** is set.
  79798. */
  79799. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  79800. Parse *pParse, /* Parsing context */
  79801. ExprList *pList, /* List to which to add the span. */
  79802. ExprSpan *pSpan /* The span to be added */
  79803. ){
  79804. sqlite3 *db = pParse->db;
  79805. assert( pList!=0 || db->mallocFailed!=0 );
  79806. if( pList ){
  79807. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  79808. assert( pList->nExpr>0 );
  79809. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  79810. sqlite3DbFree(db, pItem->zSpan);
  79811. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  79812. (int)(pSpan->zEnd - pSpan->zStart));
  79813. }
  79814. }
  79815. /*
  79816. ** If the expression list pEList contains more than iLimit elements,
  79817. ** leave an error message in pParse.
  79818. */
  79819. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  79820. Parse *pParse,
  79821. ExprList *pEList,
  79822. const char *zObject
  79823. ){
  79824. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  79825. testcase( pEList && pEList->nExpr==mx );
  79826. testcase( pEList && pEList->nExpr==mx+1 );
  79827. if( pEList && pEList->nExpr>mx ){
  79828. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  79829. }
  79830. }
  79831. /*
  79832. ** Delete an entire expression list.
  79833. */
  79834. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  79835. int i;
  79836. struct ExprList_item *pItem;
  79837. if( pList==0 ) return;
  79838. assert( pList->a!=0 || pList->nExpr==0 );
  79839. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  79840. sqlite3ExprDelete(db, pItem->pExpr);
  79841. sqlite3DbFree(db, pItem->zName);
  79842. sqlite3DbFree(db, pItem->zSpan);
  79843. }
  79844. sqlite3DbFree(db, pList->a);
  79845. sqlite3DbFree(db, pList);
  79846. }
  79847. /*
  79848. ** Return the bitwise-OR of all Expr.flags fields in the given
  79849. ** ExprList.
  79850. */
  79851. SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
  79852. int i;
  79853. u32 m = 0;
  79854. if( pList ){
  79855. for(i=0; i<pList->nExpr; i++){
  79856. Expr *pExpr = pList->a[i].pExpr;
  79857. if( ALWAYS(pExpr) ) m |= pExpr->flags;
  79858. }
  79859. }
  79860. return m;
  79861. }
  79862. /*
  79863. ** These routines are Walker callbacks used to check expressions to
  79864. ** see if they are "constant" for some definition of constant. The
  79865. ** Walker.eCode value determines the type of "constant" we are looking
  79866. ** for.
  79867. **
  79868. ** These callback routines are used to implement the following:
  79869. **
  79870. ** sqlite3ExprIsConstant() pWalker->eCode==1
  79871. ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
  79872. ** sqlite3ExprIsTableConstant() pWalker->eCode==3
  79873. ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
  79874. **
  79875. ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
  79876. ** is found to not be a constant.
  79877. **
  79878. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  79879. ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
  79880. ** an existing schema and 4 when processing a new statement. A bound
  79881. ** parameter raises an error for new statements, but is silently converted
  79882. ** to NULL for existing schemas. This allows sqlite_master tables that
  79883. ** contain a bound parameter because they were generated by older versions
  79884. ** of SQLite to be parsed by newer versions of SQLite without raising a
  79885. ** malformed schema error.
  79886. */
  79887. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  79888. /* If pWalker->eCode is 2 then any term of the expression that comes from
  79889. ** the ON or USING clauses of a left join disqualifies the expression
  79890. ** from being considered constant. */
  79891. if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  79892. pWalker->eCode = 0;
  79893. return WRC_Abort;
  79894. }
  79895. switch( pExpr->op ){
  79896. /* Consider functions to be constant if all their arguments are constant
  79897. ** and either pWalker->eCode==4 or 5 or the function has the
  79898. ** SQLITE_FUNC_CONST flag. */
  79899. case TK_FUNCTION:
  79900. if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
  79901. return WRC_Continue;
  79902. }else{
  79903. pWalker->eCode = 0;
  79904. return WRC_Abort;
  79905. }
  79906. case TK_ID:
  79907. case TK_COLUMN:
  79908. case TK_AGG_FUNCTION:
  79909. case TK_AGG_COLUMN:
  79910. testcase( pExpr->op==TK_ID );
  79911. testcase( pExpr->op==TK_COLUMN );
  79912. testcase( pExpr->op==TK_AGG_FUNCTION );
  79913. testcase( pExpr->op==TK_AGG_COLUMN );
  79914. if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
  79915. return WRC_Continue;
  79916. }else{
  79917. pWalker->eCode = 0;
  79918. return WRC_Abort;
  79919. }
  79920. case TK_VARIABLE:
  79921. if( pWalker->eCode==5 ){
  79922. /* Silently convert bound parameters that appear inside of CREATE
  79923. ** statements into a NULL when parsing the CREATE statement text out
  79924. ** of the sqlite_master table */
  79925. pExpr->op = TK_NULL;
  79926. }else if( pWalker->eCode==4 ){
  79927. /* A bound parameter in a CREATE statement that originates from
  79928. ** sqlite3_prepare() causes an error */
  79929. pWalker->eCode = 0;
  79930. return WRC_Abort;
  79931. }
  79932. /* Fall through */
  79933. default:
  79934. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  79935. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  79936. return WRC_Continue;
  79937. }
  79938. }
  79939. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  79940. UNUSED_PARAMETER(NotUsed);
  79941. pWalker->eCode = 0;
  79942. return WRC_Abort;
  79943. }
  79944. static int exprIsConst(Expr *p, int initFlag, int iCur){
  79945. Walker w;
  79946. memset(&w, 0, sizeof(w));
  79947. w.eCode = initFlag;
  79948. w.xExprCallback = exprNodeIsConstant;
  79949. w.xSelectCallback = selectNodeIsConstant;
  79950. w.u.iCur = iCur;
  79951. sqlite3WalkExpr(&w, p);
  79952. return w.eCode;
  79953. }
  79954. /*
  79955. ** Walk an expression tree. Return non-zero if the expression is constant
  79956. ** and 0 if it involves variables or function calls.
  79957. **
  79958. ** For the purposes of this function, a double-quoted string (ex: "abc")
  79959. ** is considered a variable but a single-quoted string (ex: 'abc') is
  79960. ** a constant.
  79961. */
  79962. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  79963. return exprIsConst(p, 1, 0);
  79964. }
  79965. /*
  79966. ** Walk an expression tree. Return non-zero if the expression is constant
  79967. ** that does no originate from the ON or USING clauses of a join.
  79968. ** Return 0 if it involves variables or function calls or terms from
  79969. ** an ON or USING clause.
  79970. */
  79971. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  79972. return exprIsConst(p, 2, 0);
  79973. }
  79974. /*
  79975. ** Walk an expression tree. Return non-zero if the expression is constant
  79976. ** for any single row of the table with cursor iCur. In other words, the
  79977. ** expression must not refer to any non-deterministic function nor any
  79978. ** table other than iCur.
  79979. */
  79980. SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
  79981. return exprIsConst(p, 3, iCur);
  79982. }
  79983. /*
  79984. ** Walk an expression tree. Return non-zero if the expression is constant
  79985. ** or a function call with constant arguments. Return and 0 if there
  79986. ** are any variables.
  79987. **
  79988. ** For the purposes of this function, a double-quoted string (ex: "abc")
  79989. ** is considered a variable but a single-quoted string (ex: 'abc') is
  79990. ** a constant.
  79991. */
  79992. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  79993. assert( isInit==0 || isInit==1 );
  79994. return exprIsConst(p, 4+isInit, 0);
  79995. }
  79996. /*
  79997. ** If the expression p codes a constant integer that is small enough
  79998. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  79999. ** in *pValue. If the expression is not an integer or if it is too big
  80000. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  80001. */
  80002. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  80003. int rc = 0;
  80004. /* If an expression is an integer literal that fits in a signed 32-bit
  80005. ** integer, then the EP_IntValue flag will have already been set */
  80006. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  80007. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  80008. if( p->flags & EP_IntValue ){
  80009. *pValue = p->u.iValue;
  80010. return 1;
  80011. }
  80012. switch( p->op ){
  80013. case TK_UPLUS: {
  80014. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  80015. break;
  80016. }
  80017. case TK_UMINUS: {
  80018. int v;
  80019. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  80020. assert( v!=(-2147483647-1) );
  80021. *pValue = -v;
  80022. rc = 1;
  80023. }
  80024. break;
  80025. }
  80026. default: break;
  80027. }
  80028. return rc;
  80029. }
  80030. /*
  80031. ** Return FALSE if there is no chance that the expression can be NULL.
  80032. **
  80033. ** If the expression might be NULL or if the expression is too complex
  80034. ** to tell return TRUE.
  80035. **
  80036. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  80037. ** when we know that a value cannot be NULL. Hence, a false positive
  80038. ** (returning TRUE when in fact the expression can never be NULL) might
  80039. ** be a small performance hit but is otherwise harmless. On the other
  80040. ** hand, a false negative (returning FALSE when the result could be NULL)
  80041. ** will likely result in an incorrect answer. So when in doubt, return
  80042. ** TRUE.
  80043. */
  80044. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  80045. u8 op;
  80046. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  80047. op = p->op;
  80048. if( op==TK_REGISTER ) op = p->op2;
  80049. switch( op ){
  80050. case TK_INTEGER:
  80051. case TK_STRING:
  80052. case TK_FLOAT:
  80053. case TK_BLOB:
  80054. return 0;
  80055. case TK_COLUMN:
  80056. assert( p->pTab!=0 );
  80057. return ExprHasProperty(p, EP_CanBeNull) ||
  80058. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  80059. default:
  80060. return 1;
  80061. }
  80062. }
  80063. /*
  80064. ** Return TRUE if the given expression is a constant which would be
  80065. ** unchanged by OP_Affinity with the affinity given in the second
  80066. ** argument.
  80067. **
  80068. ** This routine is used to determine if the OP_Affinity operation
  80069. ** can be omitted. When in doubt return FALSE. A false negative
  80070. ** is harmless. A false positive, however, can result in the wrong
  80071. ** answer.
  80072. */
  80073. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  80074. u8 op;
  80075. if( aff==SQLITE_AFF_BLOB ) return 1;
  80076. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  80077. op = p->op;
  80078. if( op==TK_REGISTER ) op = p->op2;
  80079. switch( op ){
  80080. case TK_INTEGER: {
  80081. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  80082. }
  80083. case TK_FLOAT: {
  80084. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  80085. }
  80086. case TK_STRING: {
  80087. return aff==SQLITE_AFF_TEXT;
  80088. }
  80089. case TK_BLOB: {
  80090. return 1;
  80091. }
  80092. case TK_COLUMN: {
  80093. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  80094. return p->iColumn<0
  80095. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  80096. }
  80097. default: {
  80098. return 0;
  80099. }
  80100. }
  80101. }
  80102. /*
  80103. ** Return TRUE if the given string is a row-id column name.
  80104. */
  80105. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  80106. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  80107. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  80108. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  80109. return 0;
  80110. }
  80111. /*
  80112. ** Return true if we are able to the IN operator optimization on a
  80113. ** query of the form
  80114. **
  80115. ** x IN (SELECT ...)
  80116. **
  80117. ** Where the SELECT... clause is as specified by the parameter to this
  80118. ** routine.
  80119. **
  80120. ** The Select object passed in has already been preprocessed and no
  80121. ** errors have been found.
  80122. */
  80123. #ifndef SQLITE_OMIT_SUBQUERY
  80124. static int isCandidateForInOpt(Select *p){
  80125. SrcList *pSrc;
  80126. ExprList *pEList;
  80127. Table *pTab;
  80128. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  80129. if( p->pPrior ) return 0; /* Not a compound SELECT */
  80130. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  80131. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  80132. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  80133. return 0; /* No DISTINCT keyword and no aggregate functions */
  80134. }
  80135. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  80136. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  80137. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  80138. if( p->pWhere ) return 0; /* Has no WHERE clause */
  80139. pSrc = p->pSrc;
  80140. assert( pSrc!=0 );
  80141. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  80142. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  80143. pTab = pSrc->a[0].pTab;
  80144. if( NEVER(pTab==0) ) return 0;
  80145. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  80146. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  80147. pEList = p->pEList;
  80148. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  80149. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  80150. return 1;
  80151. }
  80152. #endif /* SQLITE_OMIT_SUBQUERY */
  80153. /*
  80154. ** Code an OP_Once instruction and allocate space for its flag. Return the
  80155. ** address of the new instruction.
  80156. */
  80157. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  80158. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  80159. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  80160. }
  80161. /*
  80162. ** Generate code that checks the left-most column of index table iCur to see if
  80163. ** it contains any NULL entries. Cause the register at regHasNull to be set
  80164. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  80165. ** to be set to NULL if iCur contains one or more NULL values.
  80166. */
  80167. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  80168. int j1;
  80169. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  80170. j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  80171. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  80172. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  80173. VdbeComment((v, "first_entry_in(%d)", iCur));
  80174. sqlite3VdbeJumpHere(v, j1);
  80175. }
  80176. #ifndef SQLITE_OMIT_SUBQUERY
  80177. /*
  80178. ** The argument is an IN operator with a list (not a subquery) on the
  80179. ** right-hand side. Return TRUE if that list is constant.
  80180. */
  80181. static int sqlite3InRhsIsConstant(Expr *pIn){
  80182. Expr *pLHS;
  80183. int res;
  80184. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  80185. pLHS = pIn->pLeft;
  80186. pIn->pLeft = 0;
  80187. res = sqlite3ExprIsConstant(pIn);
  80188. pIn->pLeft = pLHS;
  80189. return res;
  80190. }
  80191. #endif
  80192. /*
  80193. ** This function is used by the implementation of the IN (...) operator.
  80194. ** The pX parameter is the expression on the RHS of the IN operator, which
  80195. ** might be either a list of expressions or a subquery.
  80196. **
  80197. ** The job of this routine is to find or create a b-tree object that can
  80198. ** be used either to test for membership in the RHS set or to iterate through
  80199. ** all members of the RHS set, skipping duplicates.
  80200. **
  80201. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  80202. ** and pX->iTable is set to the index of that cursor.
  80203. **
  80204. ** The returned value of this function indicates the b-tree type, as follows:
  80205. **
  80206. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  80207. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  80208. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  80209. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  80210. ** populated epheremal table.
  80211. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  80212. ** implemented as a sequence of comparisons.
  80213. **
  80214. ** An existing b-tree might be used if the RHS expression pX is a simple
  80215. ** subquery such as:
  80216. **
  80217. ** SELECT <column> FROM <table>
  80218. **
  80219. ** If the RHS of the IN operator is a list or a more complex subquery, then
  80220. ** an ephemeral table might need to be generated from the RHS and then
  80221. ** pX->iTable made to point to the ephemeral table instead of an
  80222. ** existing table.
  80223. **
  80224. ** The inFlags parameter must contain exactly one of the bits
  80225. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  80226. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  80227. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  80228. ** IN index will be used to loop over all values of the RHS of the
  80229. ** IN operator.
  80230. **
  80231. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  80232. ** through the set members) then the b-tree must not contain duplicates.
  80233. ** An epheremal table must be used unless the selected <column> is guaranteed
  80234. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  80235. ** has a UNIQUE constraint or UNIQUE index.
  80236. **
  80237. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  80238. ** for fast set membership tests) then an epheremal table must
  80239. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  80240. ** be found with <column> as its left-most column.
  80241. **
  80242. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  80243. ** if the RHS of the IN operator is a list (not a subquery) then this
  80244. ** routine might decide that creating an ephemeral b-tree for membership
  80245. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  80246. ** calling routine should implement the IN operator using a sequence
  80247. ** of Eq or Ne comparison operations.
  80248. **
  80249. ** When the b-tree is being used for membership tests, the calling function
  80250. ** might need to know whether or not the RHS side of the IN operator
  80251. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  80252. ** if there is any chance that the (...) might contain a NULL value at
  80253. ** runtime, then a register is allocated and the register number written
  80254. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  80255. ** NULL value, then *prRhsHasNull is left unchanged.
  80256. **
  80257. ** If a register is allocated and its location stored in *prRhsHasNull, then
  80258. ** the value in that register will be NULL if the b-tree contains one or more
  80259. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  80260. ** NULL values.
  80261. */
  80262. #ifndef SQLITE_OMIT_SUBQUERY
  80263. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
  80264. Select *p; /* SELECT to the right of IN operator */
  80265. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  80266. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  80267. int mustBeUnique; /* True if RHS must be unique */
  80268. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  80269. assert( pX->op==TK_IN );
  80270. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  80271. /* Check to see if an existing table or index can be used to
  80272. ** satisfy the query. This is preferable to generating a new
  80273. ** ephemeral table.
  80274. */
  80275. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  80276. if( pParse->nErr==0 && isCandidateForInOpt(p) ){
  80277. sqlite3 *db = pParse->db; /* Database connection */
  80278. Table *pTab; /* Table <table>. */
  80279. Expr *pExpr; /* Expression <column> */
  80280. i16 iCol; /* Index of column <column> */
  80281. i16 iDb; /* Database idx for pTab */
  80282. assert( p ); /* Because of isCandidateForInOpt(p) */
  80283. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  80284. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  80285. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  80286. pTab = p->pSrc->a[0].pTab;
  80287. pExpr = p->pEList->a[0].pExpr;
  80288. iCol = (i16)pExpr->iColumn;
  80289. /* Code an OP_Transaction and OP_TableLock for <table>. */
  80290. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  80291. sqlite3CodeVerifySchema(pParse, iDb);
  80292. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  80293. /* This function is only called from two places. In both cases the vdbe
  80294. ** has already been allocated. So assume sqlite3GetVdbe() is always
  80295. ** successful here.
  80296. */
  80297. assert(v);
  80298. if( iCol<0 ){
  80299. int iAddr = sqlite3CodeOnce(pParse);
  80300. VdbeCoverage(v);
  80301. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  80302. eType = IN_INDEX_ROWID;
  80303. sqlite3VdbeJumpHere(v, iAddr);
  80304. }else{
  80305. Index *pIdx; /* Iterator variable */
  80306. /* The collation sequence used by the comparison. If an index is to
  80307. ** be used in place of a temp-table, it must be ordered according
  80308. ** to this collation sequence. */
  80309. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  80310. /* Check that the affinity that will be used to perform the
  80311. ** comparison is the same as the affinity of the column. If
  80312. ** it is not, it is not possible to use any index.
  80313. */
  80314. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  80315. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  80316. if( (pIdx->aiColumn[0]==iCol)
  80317. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  80318. && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
  80319. ){
  80320. int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  80321. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  80322. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  80323. VdbeComment((v, "%s", pIdx->zName));
  80324. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  80325. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  80326. if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
  80327. *prRhsHasNull = ++pParse->nMem;
  80328. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  80329. }
  80330. sqlite3VdbeJumpHere(v, iAddr);
  80331. }
  80332. }
  80333. }
  80334. }
  80335. /* If no preexisting index is available for the IN clause
  80336. ** and IN_INDEX_NOOP is an allowed reply
  80337. ** and the RHS of the IN operator is a list, not a subquery
  80338. ** and the RHS is not contant or has two or fewer terms,
  80339. ** then it is not worth creating an ephemeral table to evaluate
  80340. ** the IN operator so return IN_INDEX_NOOP.
  80341. */
  80342. if( eType==0
  80343. && (inFlags & IN_INDEX_NOOP_OK)
  80344. && !ExprHasProperty(pX, EP_xIsSelect)
  80345. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  80346. ){
  80347. eType = IN_INDEX_NOOP;
  80348. }
  80349. if( eType==0 ){
  80350. /* Could not find an existing table or index to use as the RHS b-tree.
  80351. ** We will have to generate an ephemeral table to do the job.
  80352. */
  80353. u32 savedNQueryLoop = pParse->nQueryLoop;
  80354. int rMayHaveNull = 0;
  80355. eType = IN_INDEX_EPH;
  80356. if( inFlags & IN_INDEX_LOOP ){
  80357. pParse->nQueryLoop = 0;
  80358. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  80359. eType = IN_INDEX_ROWID;
  80360. }
  80361. }else if( prRhsHasNull ){
  80362. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  80363. }
  80364. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  80365. pParse->nQueryLoop = savedNQueryLoop;
  80366. }else{
  80367. pX->iTable = iTab;
  80368. }
  80369. return eType;
  80370. }
  80371. #endif
  80372. /*
  80373. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  80374. ** or IN operators. Examples:
  80375. **
  80376. ** (SELECT a FROM b) -- subquery
  80377. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  80378. ** x IN (4,5,11) -- IN operator with list on right-hand side
  80379. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  80380. **
  80381. ** The pExpr parameter describes the expression that contains the IN
  80382. ** operator or subquery.
  80383. **
  80384. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  80385. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  80386. ** to some integer key column of a table B-Tree. In this case, use an
  80387. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  80388. ** (slower) variable length keys B-Tree.
  80389. **
  80390. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  80391. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  80392. ** All this routine does is initialize the register given by rMayHaveNull
  80393. ** to NULL. Calling routines will take care of changing this register
  80394. ** value to non-NULL if the RHS is NULL-free.
  80395. **
  80396. ** For a SELECT or EXISTS operator, return the register that holds the
  80397. ** result. For IN operators or if an error occurs, the return value is 0.
  80398. */
  80399. #ifndef SQLITE_OMIT_SUBQUERY
  80400. SQLITE_PRIVATE int sqlite3CodeSubselect(
  80401. Parse *pParse, /* Parsing context */
  80402. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  80403. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  80404. int isRowid /* If true, LHS of IN operator is a rowid */
  80405. ){
  80406. int jmpIfDynamic = -1; /* One-time test address */
  80407. int rReg = 0; /* Register storing resulting */
  80408. Vdbe *v = sqlite3GetVdbe(pParse);
  80409. if( NEVER(v==0) ) return 0;
  80410. sqlite3ExprCachePush(pParse);
  80411. /* This code must be run in its entirety every time it is encountered
  80412. ** if any of the following is true:
  80413. **
  80414. ** * The right-hand side is a correlated subquery
  80415. ** * The right-hand side is an expression list containing variables
  80416. ** * We are inside a trigger
  80417. **
  80418. ** If all of the above are false, then we can run this code just once
  80419. ** save the results, and reuse the same result on subsequent invocations.
  80420. */
  80421. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  80422. jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  80423. }
  80424. #ifndef SQLITE_OMIT_EXPLAIN
  80425. if( pParse->explain==2 ){
  80426. char *zMsg = sqlite3MPrintf(
  80427. pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
  80428. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  80429. );
  80430. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  80431. }
  80432. #endif
  80433. switch( pExpr->op ){
  80434. case TK_IN: {
  80435. char affinity; /* Affinity of the LHS of the IN */
  80436. int addr; /* Address of OP_OpenEphemeral instruction */
  80437. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  80438. KeyInfo *pKeyInfo = 0; /* Key information */
  80439. affinity = sqlite3ExprAffinity(pLeft);
  80440. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  80441. ** expression it is handled the same way. An ephemeral table is
  80442. ** filled with single-field index keys representing the results
  80443. ** from the SELECT or the <exprlist>.
  80444. **
  80445. ** If the 'x' expression is a column value, or the SELECT...
  80446. ** statement returns a column value, then the affinity of that
  80447. ** column is used to build the index keys. If both 'x' and the
  80448. ** SELECT... statement are columns, then numeric affinity is used
  80449. ** if either column has NUMERIC or INTEGER affinity. If neither
  80450. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  80451. ** is used.
  80452. */
  80453. pExpr->iTable = pParse->nTab++;
  80454. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  80455. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
  80456. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  80457. /* Case 1: expr IN (SELECT ...)
  80458. **
  80459. ** Generate code to write the results of the select into the temporary
  80460. ** table allocated and opened above.
  80461. */
  80462. Select *pSelect = pExpr->x.pSelect;
  80463. SelectDest dest;
  80464. ExprList *pEList;
  80465. assert( !isRowid );
  80466. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  80467. dest.affSdst = (u8)affinity;
  80468. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  80469. pSelect->iLimit = 0;
  80470. testcase( pSelect->selFlags & SF_Distinct );
  80471. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  80472. if( sqlite3Select(pParse, pSelect, &dest) ){
  80473. sqlite3KeyInfoUnref(pKeyInfo);
  80474. return 0;
  80475. }
  80476. pEList = pSelect->pEList;
  80477. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  80478. assert( pEList!=0 );
  80479. assert( pEList->nExpr>0 );
  80480. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  80481. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  80482. pEList->a[0].pExpr);
  80483. }else if( ALWAYS(pExpr->x.pList!=0) ){
  80484. /* Case 2: expr IN (exprlist)
  80485. **
  80486. ** For each expression, build an index key from the evaluation and
  80487. ** store it in the temporary table. If <expr> is a column, then use
  80488. ** that columns affinity when building index keys. If <expr> is not
  80489. ** a column, use numeric affinity.
  80490. */
  80491. int i;
  80492. ExprList *pList = pExpr->x.pList;
  80493. struct ExprList_item *pItem;
  80494. int r1, r2, r3;
  80495. if( !affinity ){
  80496. affinity = SQLITE_AFF_BLOB;
  80497. }
  80498. if( pKeyInfo ){
  80499. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  80500. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  80501. }
  80502. /* Loop through each expression in <exprlist>. */
  80503. r1 = sqlite3GetTempReg(pParse);
  80504. r2 = sqlite3GetTempReg(pParse);
  80505. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  80506. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  80507. Expr *pE2 = pItem->pExpr;
  80508. int iValToIns;
  80509. /* If the expression is not constant then we will need to
  80510. ** disable the test that was generated above that makes sure
  80511. ** this code only executes once. Because for a non-constant
  80512. ** expression we need to rerun this code each time.
  80513. */
  80514. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  80515. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  80516. jmpIfDynamic = -1;
  80517. }
  80518. /* Evaluate the expression and insert it into the temp table */
  80519. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  80520. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  80521. }else{
  80522. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  80523. if( isRowid ){
  80524. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  80525. sqlite3VdbeCurrentAddr(v)+2);
  80526. VdbeCoverage(v);
  80527. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  80528. }else{
  80529. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  80530. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  80531. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  80532. }
  80533. }
  80534. }
  80535. sqlite3ReleaseTempReg(pParse, r1);
  80536. sqlite3ReleaseTempReg(pParse, r2);
  80537. }
  80538. if( pKeyInfo ){
  80539. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  80540. }
  80541. break;
  80542. }
  80543. case TK_EXISTS:
  80544. case TK_SELECT:
  80545. default: {
  80546. /* If this has to be a scalar SELECT. Generate code to put the
  80547. ** value of this select in a memory cell and record the number
  80548. ** of the memory cell in iColumn. If this is an EXISTS, write
  80549. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  80550. ** and record that memory cell in iColumn.
  80551. */
  80552. Select *pSel; /* SELECT statement to encode */
  80553. SelectDest dest; /* How to deal with SELECt result */
  80554. testcase( pExpr->op==TK_EXISTS );
  80555. testcase( pExpr->op==TK_SELECT );
  80556. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  80557. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  80558. pSel = pExpr->x.pSelect;
  80559. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  80560. if( pExpr->op==TK_SELECT ){
  80561. dest.eDest = SRT_Mem;
  80562. dest.iSdst = dest.iSDParm;
  80563. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  80564. VdbeComment((v, "Init subquery result"));
  80565. }else{
  80566. dest.eDest = SRT_Exists;
  80567. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  80568. VdbeComment((v, "Init EXISTS result"));
  80569. }
  80570. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  80571. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  80572. &sqlite3IntTokens[1]);
  80573. pSel->iLimit = 0;
  80574. pSel->selFlags &= ~SF_MultiValue;
  80575. if( sqlite3Select(pParse, pSel, &dest) ){
  80576. return 0;
  80577. }
  80578. rReg = dest.iSDParm;
  80579. ExprSetVVAProperty(pExpr, EP_NoReduce);
  80580. break;
  80581. }
  80582. }
  80583. if( rHasNullFlag ){
  80584. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  80585. }
  80586. if( jmpIfDynamic>=0 ){
  80587. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  80588. }
  80589. sqlite3ExprCachePop(pParse);
  80590. return rReg;
  80591. }
  80592. #endif /* SQLITE_OMIT_SUBQUERY */
  80593. #ifndef SQLITE_OMIT_SUBQUERY
  80594. /*
  80595. ** Generate code for an IN expression.
  80596. **
  80597. ** x IN (SELECT ...)
  80598. ** x IN (value, value, ...)
  80599. **
  80600. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  80601. ** is an array of zero or more values. The expression is true if the LHS is
  80602. ** contained within the RHS. The value of the expression is unknown (NULL)
  80603. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  80604. ** RHS contains one or more NULL values.
  80605. **
  80606. ** This routine generates code that jumps to destIfFalse if the LHS is not
  80607. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  80608. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  80609. ** within the RHS then fall through.
  80610. */
  80611. static void sqlite3ExprCodeIN(
  80612. Parse *pParse, /* Parsing and code generating context */
  80613. Expr *pExpr, /* The IN expression */
  80614. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  80615. int destIfNull /* Jump here if the results are unknown due to NULLs */
  80616. ){
  80617. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  80618. char affinity; /* Comparison affinity to use */
  80619. int eType; /* Type of the RHS */
  80620. int r1; /* Temporary use register */
  80621. Vdbe *v; /* Statement under construction */
  80622. /* Compute the RHS. After this step, the table with cursor
  80623. ** pExpr->iTable will contains the values that make up the RHS.
  80624. */
  80625. v = pParse->pVdbe;
  80626. assert( v!=0 ); /* OOM detected prior to this routine */
  80627. VdbeNoopComment((v, "begin IN expr"));
  80628. eType = sqlite3FindInIndex(pParse, pExpr,
  80629. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  80630. destIfFalse==destIfNull ? 0 : &rRhsHasNull);
  80631. /* Figure out the affinity to use to create a key from the results
  80632. ** of the expression. affinityStr stores a static string suitable for
  80633. ** P4 of OP_MakeRecord.
  80634. */
  80635. affinity = comparisonAffinity(pExpr);
  80636. /* Code the LHS, the <expr> from "<expr> IN (...)".
  80637. */
  80638. sqlite3ExprCachePush(pParse);
  80639. r1 = sqlite3GetTempReg(pParse);
  80640. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  80641. /* If sqlite3FindInIndex() did not find or create an index that is
  80642. ** suitable for evaluating the IN operator, then evaluate using a
  80643. ** sequence of comparisons.
  80644. */
  80645. if( eType==IN_INDEX_NOOP ){
  80646. ExprList *pList = pExpr->x.pList;
  80647. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  80648. int labelOk = sqlite3VdbeMakeLabel(v);
  80649. int r2, regToFree;
  80650. int regCkNull = 0;
  80651. int ii;
  80652. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  80653. if( destIfNull!=destIfFalse ){
  80654. regCkNull = sqlite3GetTempReg(pParse);
  80655. sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
  80656. }
  80657. for(ii=0; ii<pList->nExpr; ii++){
  80658. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  80659. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  80660. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  80661. }
  80662. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  80663. sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
  80664. (void*)pColl, P4_COLLSEQ);
  80665. VdbeCoverageIf(v, ii<pList->nExpr-1);
  80666. VdbeCoverageIf(v, ii==pList->nExpr-1);
  80667. sqlite3VdbeChangeP5(v, affinity);
  80668. }else{
  80669. assert( destIfNull==destIfFalse );
  80670. sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
  80671. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  80672. sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
  80673. }
  80674. sqlite3ReleaseTempReg(pParse, regToFree);
  80675. }
  80676. if( regCkNull ){
  80677. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  80678. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  80679. }
  80680. sqlite3VdbeResolveLabel(v, labelOk);
  80681. sqlite3ReleaseTempReg(pParse, regCkNull);
  80682. }else{
  80683. /* If the LHS is NULL, then the result is either false or NULL depending
  80684. ** on whether the RHS is empty or not, respectively.
  80685. */
  80686. if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
  80687. if( destIfNull==destIfFalse ){
  80688. /* Shortcut for the common case where the false and NULL outcomes are
  80689. ** the same. */
  80690. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  80691. }else{
  80692. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  80693. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  80694. VdbeCoverage(v);
  80695. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  80696. sqlite3VdbeJumpHere(v, addr1);
  80697. }
  80698. }
  80699. if( eType==IN_INDEX_ROWID ){
  80700. /* In this case, the RHS is the ROWID of table b-tree
  80701. */
  80702. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  80703. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  80704. VdbeCoverage(v);
  80705. }else{
  80706. /* In this case, the RHS is an index b-tree.
  80707. */
  80708. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  80709. /* If the set membership test fails, then the result of the
  80710. ** "x IN (...)" expression must be either 0 or NULL. If the set
  80711. ** contains no NULL values, then the result is 0. If the set
  80712. ** contains one or more NULL values, then the result of the
  80713. ** expression is also NULL.
  80714. */
  80715. assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
  80716. if( rRhsHasNull==0 ){
  80717. /* This branch runs if it is known at compile time that the RHS
  80718. ** cannot contain NULL values. This happens as the result
  80719. ** of a "NOT NULL" constraint in the database schema.
  80720. **
  80721. ** Also run this branch if NULL is equivalent to FALSE
  80722. ** for this particular IN operator.
  80723. */
  80724. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  80725. VdbeCoverage(v);
  80726. }else{
  80727. /* In this branch, the RHS of the IN might contain a NULL and
  80728. ** the presence of a NULL on the RHS makes a difference in the
  80729. ** outcome.
  80730. */
  80731. int j1;
  80732. /* First check to see if the LHS is contained in the RHS. If so,
  80733. ** then the answer is TRUE the presence of NULLs in the RHS does
  80734. ** not matter. If the LHS is not contained in the RHS, then the
  80735. ** answer is NULL if the RHS contains NULLs and the answer is
  80736. ** FALSE if the RHS is NULL-free.
  80737. */
  80738. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  80739. VdbeCoverage(v);
  80740. sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
  80741. VdbeCoverage(v);
  80742. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  80743. sqlite3VdbeJumpHere(v, j1);
  80744. }
  80745. }
  80746. }
  80747. sqlite3ReleaseTempReg(pParse, r1);
  80748. sqlite3ExprCachePop(pParse);
  80749. VdbeComment((v, "end IN expr"));
  80750. }
  80751. #endif /* SQLITE_OMIT_SUBQUERY */
  80752. #ifndef SQLITE_OMIT_FLOATING_POINT
  80753. /*
  80754. ** Generate an instruction that will put the floating point
  80755. ** value described by z[0..n-1] into register iMem.
  80756. **
  80757. ** The z[] string will probably not be zero-terminated. But the
  80758. ** z[n] character is guaranteed to be something that does not look
  80759. ** like the continuation of the number.
  80760. */
  80761. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  80762. if( ALWAYS(z!=0) ){
  80763. double value;
  80764. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  80765. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  80766. if( negateFlag ) value = -value;
  80767. sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
  80768. }
  80769. }
  80770. #endif
  80771. /*
  80772. ** Generate an instruction that will put the integer describe by
  80773. ** text z[0..n-1] into register iMem.
  80774. **
  80775. ** Expr.u.zToken is always UTF8 and zero-terminated.
  80776. */
  80777. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  80778. Vdbe *v = pParse->pVdbe;
  80779. if( pExpr->flags & EP_IntValue ){
  80780. int i = pExpr->u.iValue;
  80781. assert( i>=0 );
  80782. if( negFlag ) i = -i;
  80783. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  80784. }else{
  80785. int c;
  80786. i64 value;
  80787. const char *z = pExpr->u.zToken;
  80788. assert( z!=0 );
  80789. c = sqlite3DecOrHexToI64(z, &value);
  80790. if( c==0 || (c==2 && negFlag) ){
  80791. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  80792. sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
  80793. }else{
  80794. #ifdef SQLITE_OMIT_FLOATING_POINT
  80795. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  80796. #else
  80797. #ifndef SQLITE_OMIT_HEX_INTEGER
  80798. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  80799. sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
  80800. }else
  80801. #endif
  80802. {
  80803. codeReal(v, z, negFlag, iMem);
  80804. }
  80805. #endif
  80806. }
  80807. }
  80808. }
  80809. /*
  80810. ** Clear a cache entry.
  80811. */
  80812. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  80813. if( p->tempReg ){
  80814. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  80815. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  80816. }
  80817. p->tempReg = 0;
  80818. }
  80819. }
  80820. /*
  80821. ** Record in the column cache that a particular column from a
  80822. ** particular table is stored in a particular register.
  80823. */
  80824. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  80825. int i;
  80826. int minLru;
  80827. int idxLru;
  80828. struct yColCache *p;
  80829. /* Unless an error has occurred, register numbers are always positive. */
  80830. assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
  80831. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  80832. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  80833. ** for testing only - to verify that SQLite always gets the same answer
  80834. ** with and without the column cache.
  80835. */
  80836. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  80837. /* First replace any existing entry.
  80838. **
  80839. ** Actually, the way the column cache is currently used, we are guaranteed
  80840. ** that the object will never already be in cache. Verify this guarantee.
  80841. */
  80842. #ifndef NDEBUG
  80843. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  80844. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  80845. }
  80846. #endif
  80847. /* Find an empty slot and replace it */
  80848. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  80849. if( p->iReg==0 ){
  80850. p->iLevel = pParse->iCacheLevel;
  80851. p->iTable = iTab;
  80852. p->iColumn = iCol;
  80853. p->iReg = iReg;
  80854. p->tempReg = 0;
  80855. p->lru = pParse->iCacheCnt++;
  80856. return;
  80857. }
  80858. }
  80859. /* Replace the last recently used */
  80860. minLru = 0x7fffffff;
  80861. idxLru = -1;
  80862. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  80863. if( p->lru<minLru ){
  80864. idxLru = i;
  80865. minLru = p->lru;
  80866. }
  80867. }
  80868. if( ALWAYS(idxLru>=0) ){
  80869. p = &pParse->aColCache[idxLru];
  80870. p->iLevel = pParse->iCacheLevel;
  80871. p->iTable = iTab;
  80872. p->iColumn = iCol;
  80873. p->iReg = iReg;
  80874. p->tempReg = 0;
  80875. p->lru = pParse->iCacheCnt++;
  80876. return;
  80877. }
  80878. }
  80879. /*
  80880. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  80881. ** Purge the range of registers from the column cache.
  80882. */
  80883. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  80884. int i;
  80885. int iLast = iReg + nReg - 1;
  80886. struct yColCache *p;
  80887. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  80888. int r = p->iReg;
  80889. if( r>=iReg && r<=iLast ){
  80890. cacheEntryClear(pParse, p);
  80891. p->iReg = 0;
  80892. }
  80893. }
  80894. }
  80895. /*
  80896. ** Remember the current column cache context. Any new entries added
  80897. ** added to the column cache after this call are removed when the
  80898. ** corresponding pop occurs.
  80899. */
  80900. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  80901. pParse->iCacheLevel++;
  80902. #ifdef SQLITE_DEBUG
  80903. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  80904. printf("PUSH to %d\n", pParse->iCacheLevel);
  80905. }
  80906. #endif
  80907. }
  80908. /*
  80909. ** Remove from the column cache any entries that were added since the
  80910. ** the previous sqlite3ExprCachePush operation. In other words, restore
  80911. ** the cache to the state it was in prior the most recent Push.
  80912. */
  80913. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  80914. int i;
  80915. struct yColCache *p;
  80916. assert( pParse->iCacheLevel>=1 );
  80917. pParse->iCacheLevel--;
  80918. #ifdef SQLITE_DEBUG
  80919. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  80920. printf("POP to %d\n", pParse->iCacheLevel);
  80921. }
  80922. #endif
  80923. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  80924. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  80925. cacheEntryClear(pParse, p);
  80926. p->iReg = 0;
  80927. }
  80928. }
  80929. }
  80930. /*
  80931. ** When a cached column is reused, make sure that its register is
  80932. ** no longer available as a temp register. ticket #3879: that same
  80933. ** register might be in the cache in multiple places, so be sure to
  80934. ** get them all.
  80935. */
  80936. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  80937. int i;
  80938. struct yColCache *p;
  80939. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  80940. if( p->iReg==iReg ){
  80941. p->tempReg = 0;
  80942. }
  80943. }
  80944. }
  80945. /*
  80946. ** Generate code to extract the value of the iCol-th column of a table.
  80947. */
  80948. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  80949. Vdbe *v, /* The VDBE under construction */
  80950. Table *pTab, /* The table containing the value */
  80951. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  80952. int iCol, /* Index of the column to extract */
  80953. int regOut /* Extract the value into this register */
  80954. ){
  80955. if( iCol<0 || iCol==pTab->iPKey ){
  80956. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  80957. }else{
  80958. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  80959. int x = iCol;
  80960. if( !HasRowid(pTab) ){
  80961. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  80962. }
  80963. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  80964. }
  80965. if( iCol>=0 ){
  80966. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  80967. }
  80968. }
  80969. /*
  80970. ** Generate code that will extract the iColumn-th column from
  80971. ** table pTab and store the column value in a register. An effort
  80972. ** is made to store the column value in register iReg, but this is
  80973. ** not guaranteed. The location of the column value is returned.
  80974. **
  80975. ** There must be an open cursor to pTab in iTable when this routine
  80976. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  80977. */
  80978. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  80979. Parse *pParse, /* Parsing and code generating context */
  80980. Table *pTab, /* Description of the table we are reading from */
  80981. int iColumn, /* Index of the table column */
  80982. int iTable, /* The cursor pointing to the table */
  80983. int iReg, /* Store results here */
  80984. u8 p5 /* P5 value for OP_Column */
  80985. ){
  80986. Vdbe *v = pParse->pVdbe;
  80987. int i;
  80988. struct yColCache *p;
  80989. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  80990. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  80991. p->lru = pParse->iCacheCnt++;
  80992. sqlite3ExprCachePinRegister(pParse, p->iReg);
  80993. return p->iReg;
  80994. }
  80995. }
  80996. assert( v!=0 );
  80997. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  80998. if( p5 ){
  80999. sqlite3VdbeChangeP5(v, p5);
  81000. }else{
  81001. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  81002. }
  81003. return iReg;
  81004. }
  81005. /*
  81006. ** Clear all column cache entries.
  81007. */
  81008. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  81009. int i;
  81010. struct yColCache *p;
  81011. #if SQLITE_DEBUG
  81012. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  81013. printf("CLEAR\n");
  81014. }
  81015. #endif
  81016. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81017. if( p->iReg ){
  81018. cacheEntryClear(pParse, p);
  81019. p->iReg = 0;
  81020. }
  81021. }
  81022. }
  81023. /*
  81024. ** Record the fact that an affinity change has occurred on iCount
  81025. ** registers starting with iStart.
  81026. */
  81027. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  81028. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  81029. }
  81030. /*
  81031. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  81032. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  81033. */
  81034. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  81035. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  81036. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  81037. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  81038. }
  81039. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  81040. /*
  81041. ** Return true if any register in the range iFrom..iTo (inclusive)
  81042. ** is used as part of the column cache.
  81043. **
  81044. ** This routine is used within assert() and testcase() macros only
  81045. ** and does not appear in a normal build.
  81046. */
  81047. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  81048. int i;
  81049. struct yColCache *p;
  81050. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  81051. int r = p->iReg;
  81052. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  81053. }
  81054. return 0;
  81055. }
  81056. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  81057. /*
  81058. ** Convert an expression node to a TK_REGISTER
  81059. */
  81060. static void exprToRegister(Expr *p, int iReg){
  81061. p->op2 = p->op;
  81062. p->op = TK_REGISTER;
  81063. p->iTable = iReg;
  81064. ExprClearProperty(p, EP_Skip);
  81065. }
  81066. /*
  81067. ** Generate code into the current Vdbe to evaluate the given
  81068. ** expression. Attempt to store the results in register "target".
  81069. ** Return the register where results are stored.
  81070. **
  81071. ** With this routine, there is no guarantee that results will
  81072. ** be stored in target. The result might be stored in some other
  81073. ** register if it is convenient to do so. The calling function
  81074. ** must check the return code and move the results to the desired
  81075. ** register.
  81076. */
  81077. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  81078. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  81079. int op; /* The opcode being coded */
  81080. int inReg = target; /* Results stored in register inReg */
  81081. int regFree1 = 0; /* If non-zero free this temporary register */
  81082. int regFree2 = 0; /* If non-zero free this temporary register */
  81083. int r1, r2, r3, r4; /* Various register numbers */
  81084. sqlite3 *db = pParse->db; /* The database connection */
  81085. Expr tempX; /* Temporary expression node */
  81086. assert( target>0 && target<=pParse->nMem );
  81087. if( v==0 ){
  81088. assert( pParse->db->mallocFailed );
  81089. return 0;
  81090. }
  81091. if( pExpr==0 ){
  81092. op = TK_NULL;
  81093. }else{
  81094. op = pExpr->op;
  81095. }
  81096. switch( op ){
  81097. case TK_AGG_COLUMN: {
  81098. AggInfo *pAggInfo = pExpr->pAggInfo;
  81099. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  81100. if( !pAggInfo->directMode ){
  81101. assert( pCol->iMem>0 );
  81102. inReg = pCol->iMem;
  81103. break;
  81104. }else if( pAggInfo->useSortingIdx ){
  81105. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  81106. pCol->iSorterColumn, target);
  81107. break;
  81108. }
  81109. /* Otherwise, fall thru into the TK_COLUMN case */
  81110. }
  81111. case TK_COLUMN: {
  81112. int iTab = pExpr->iTable;
  81113. if( iTab<0 ){
  81114. if( pParse->ckBase>0 ){
  81115. /* Generating CHECK constraints or inserting into partial index */
  81116. inReg = pExpr->iColumn + pParse->ckBase;
  81117. break;
  81118. }else{
  81119. /* Deleting from a partial index */
  81120. iTab = pParse->iPartIdxTab;
  81121. }
  81122. }
  81123. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  81124. pExpr->iColumn, iTab, target,
  81125. pExpr->op2);
  81126. break;
  81127. }
  81128. case TK_INTEGER: {
  81129. codeInteger(pParse, pExpr, 0, target);
  81130. break;
  81131. }
  81132. #ifndef SQLITE_OMIT_FLOATING_POINT
  81133. case TK_FLOAT: {
  81134. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81135. codeReal(v, pExpr->u.zToken, 0, target);
  81136. break;
  81137. }
  81138. #endif
  81139. case TK_STRING: {
  81140. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81141. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  81142. break;
  81143. }
  81144. case TK_NULL: {
  81145. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  81146. break;
  81147. }
  81148. #ifndef SQLITE_OMIT_BLOB_LITERAL
  81149. case TK_BLOB: {
  81150. int n;
  81151. const char *z;
  81152. char *zBlob;
  81153. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81154. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  81155. assert( pExpr->u.zToken[1]=='\'' );
  81156. z = &pExpr->u.zToken[2];
  81157. n = sqlite3Strlen30(z) - 1;
  81158. assert( z[n]=='\'' );
  81159. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  81160. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  81161. break;
  81162. }
  81163. #endif
  81164. case TK_VARIABLE: {
  81165. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81166. assert( pExpr->u.zToken!=0 );
  81167. assert( pExpr->u.zToken[0]!=0 );
  81168. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  81169. if( pExpr->u.zToken[1]!=0 ){
  81170. assert( pExpr->u.zToken[0]=='?'
  81171. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  81172. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  81173. }
  81174. break;
  81175. }
  81176. case TK_REGISTER: {
  81177. inReg = pExpr->iTable;
  81178. break;
  81179. }
  81180. case TK_AS: {
  81181. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  81182. break;
  81183. }
  81184. #ifndef SQLITE_OMIT_CAST
  81185. case TK_CAST: {
  81186. /* Expressions of the form: CAST(pLeft AS token) */
  81187. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  81188. if( inReg!=target ){
  81189. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  81190. inReg = target;
  81191. }
  81192. sqlite3VdbeAddOp2(v, OP_Cast, target,
  81193. sqlite3AffinityType(pExpr->u.zToken, 0));
  81194. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  81195. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  81196. break;
  81197. }
  81198. #endif /* SQLITE_OMIT_CAST */
  81199. case TK_LT:
  81200. case TK_LE:
  81201. case TK_GT:
  81202. case TK_GE:
  81203. case TK_NE:
  81204. case TK_EQ: {
  81205. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81206. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  81207. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  81208. r1, r2, inReg, SQLITE_STOREP2);
  81209. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  81210. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  81211. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  81212. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  81213. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  81214. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  81215. testcase( regFree1==0 );
  81216. testcase( regFree2==0 );
  81217. break;
  81218. }
  81219. case TK_IS:
  81220. case TK_ISNOT: {
  81221. testcase( op==TK_IS );
  81222. testcase( op==TK_ISNOT );
  81223. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81224. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  81225. op = (op==TK_IS) ? TK_EQ : TK_NE;
  81226. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  81227. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  81228. VdbeCoverageIf(v, op==TK_EQ);
  81229. VdbeCoverageIf(v, op==TK_NE);
  81230. testcase( regFree1==0 );
  81231. testcase( regFree2==0 );
  81232. break;
  81233. }
  81234. case TK_AND:
  81235. case TK_OR:
  81236. case TK_PLUS:
  81237. case TK_STAR:
  81238. case TK_MINUS:
  81239. case TK_REM:
  81240. case TK_BITAND:
  81241. case TK_BITOR:
  81242. case TK_SLASH:
  81243. case TK_LSHIFT:
  81244. case TK_RSHIFT:
  81245. case TK_CONCAT: {
  81246. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  81247. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  81248. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  81249. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  81250. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  81251. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  81252. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  81253. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  81254. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  81255. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  81256. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  81257. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81258. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  81259. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  81260. testcase( regFree1==0 );
  81261. testcase( regFree2==0 );
  81262. break;
  81263. }
  81264. case TK_UMINUS: {
  81265. Expr *pLeft = pExpr->pLeft;
  81266. assert( pLeft );
  81267. if( pLeft->op==TK_INTEGER ){
  81268. codeInteger(pParse, pLeft, 1, target);
  81269. #ifndef SQLITE_OMIT_FLOATING_POINT
  81270. }else if( pLeft->op==TK_FLOAT ){
  81271. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81272. codeReal(v, pLeft->u.zToken, 1, target);
  81273. #endif
  81274. }else{
  81275. tempX.op = TK_INTEGER;
  81276. tempX.flags = EP_IntValue|EP_TokenOnly;
  81277. tempX.u.iValue = 0;
  81278. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  81279. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  81280. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  81281. testcase( regFree2==0 );
  81282. }
  81283. inReg = target;
  81284. break;
  81285. }
  81286. case TK_BITNOT:
  81287. case TK_NOT: {
  81288. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  81289. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  81290. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81291. testcase( regFree1==0 );
  81292. inReg = target;
  81293. sqlite3VdbeAddOp2(v, op, r1, inReg);
  81294. break;
  81295. }
  81296. case TK_ISNULL:
  81297. case TK_NOTNULL: {
  81298. int addr;
  81299. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  81300. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  81301. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  81302. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81303. testcase( regFree1==0 );
  81304. addr = sqlite3VdbeAddOp1(v, op, r1);
  81305. VdbeCoverageIf(v, op==TK_ISNULL);
  81306. VdbeCoverageIf(v, op==TK_NOTNULL);
  81307. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  81308. sqlite3VdbeJumpHere(v, addr);
  81309. break;
  81310. }
  81311. case TK_AGG_FUNCTION: {
  81312. AggInfo *pInfo = pExpr->pAggInfo;
  81313. if( pInfo==0 ){
  81314. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81315. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  81316. }else{
  81317. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  81318. }
  81319. break;
  81320. }
  81321. case TK_FUNCTION: {
  81322. ExprList *pFarg; /* List of function arguments */
  81323. int nFarg; /* Number of function arguments */
  81324. FuncDef *pDef; /* The function definition object */
  81325. int nId; /* Length of the function name in bytes */
  81326. const char *zId; /* The function name */
  81327. u32 constMask = 0; /* Mask of function arguments that are constant */
  81328. int i; /* Loop counter */
  81329. u8 enc = ENC(db); /* The text encoding used by this database */
  81330. CollSeq *pColl = 0; /* A collating sequence */
  81331. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  81332. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  81333. pFarg = 0;
  81334. }else{
  81335. pFarg = pExpr->x.pList;
  81336. }
  81337. nFarg = pFarg ? pFarg->nExpr : 0;
  81338. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81339. zId = pExpr->u.zToken;
  81340. nId = sqlite3Strlen30(zId);
  81341. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  81342. if( pDef==0 || pDef->xFunc==0 ){
  81343. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  81344. break;
  81345. }
  81346. /* Attempt a direct implementation of the built-in COALESCE() and
  81347. ** IFNULL() functions. This avoids unnecessary evaluation of
  81348. ** arguments past the first non-NULL argument.
  81349. */
  81350. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  81351. int endCoalesce = sqlite3VdbeMakeLabel(v);
  81352. assert( nFarg>=2 );
  81353. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  81354. for(i=1; i<nFarg; i++){
  81355. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  81356. VdbeCoverage(v);
  81357. sqlite3ExprCacheRemove(pParse, target, 1);
  81358. sqlite3ExprCachePush(pParse);
  81359. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  81360. sqlite3ExprCachePop(pParse);
  81361. }
  81362. sqlite3VdbeResolveLabel(v, endCoalesce);
  81363. break;
  81364. }
  81365. /* The UNLIKELY() function is a no-op. The result is the value
  81366. ** of the first argument.
  81367. */
  81368. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  81369. assert( nFarg>=1 );
  81370. inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
  81371. break;
  81372. }
  81373. for(i=0; i<nFarg; i++){
  81374. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  81375. testcase( i==31 );
  81376. constMask |= MASKBIT32(i);
  81377. }
  81378. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  81379. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  81380. }
  81381. }
  81382. if( pFarg ){
  81383. if( constMask ){
  81384. r1 = pParse->nMem+1;
  81385. pParse->nMem += nFarg;
  81386. }else{
  81387. r1 = sqlite3GetTempRange(pParse, nFarg);
  81388. }
  81389. /* For length() and typeof() functions with a column argument,
  81390. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  81391. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  81392. ** loading.
  81393. */
  81394. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  81395. u8 exprOp;
  81396. assert( nFarg==1 );
  81397. assert( pFarg->a[0].pExpr!=0 );
  81398. exprOp = pFarg->a[0].pExpr->op;
  81399. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  81400. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  81401. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  81402. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  81403. pFarg->a[0].pExpr->op2 =
  81404. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  81405. }
  81406. }
  81407. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  81408. sqlite3ExprCodeExprList(pParse, pFarg, r1,
  81409. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  81410. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  81411. }else{
  81412. r1 = 0;
  81413. }
  81414. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81415. /* Possibly overload the function if the first argument is
  81416. ** a virtual table column.
  81417. **
  81418. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  81419. ** second argument, not the first, as the argument to test to
  81420. ** see if it is a column in a virtual table. This is done because
  81421. ** the left operand of infix functions (the operand we want to
  81422. ** control overloading) ends up as the second argument to the
  81423. ** function. The expression "A glob B" is equivalent to
  81424. ** "glob(B,A). We want to use the A in "A glob B" to test
  81425. ** for function overloading. But we use the B term in "glob(B,A)".
  81426. */
  81427. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  81428. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  81429. }else if( nFarg>0 ){
  81430. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  81431. }
  81432. #endif
  81433. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  81434. if( !pColl ) pColl = db->pDfltColl;
  81435. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  81436. }
  81437. sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
  81438. (char*)pDef, P4_FUNCDEF);
  81439. sqlite3VdbeChangeP5(v, (u8)nFarg);
  81440. if( nFarg && constMask==0 ){
  81441. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  81442. }
  81443. break;
  81444. }
  81445. #ifndef SQLITE_OMIT_SUBQUERY
  81446. case TK_EXISTS:
  81447. case TK_SELECT: {
  81448. testcase( op==TK_EXISTS );
  81449. testcase( op==TK_SELECT );
  81450. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  81451. break;
  81452. }
  81453. case TK_IN: {
  81454. int destIfFalse = sqlite3VdbeMakeLabel(v);
  81455. int destIfNull = sqlite3VdbeMakeLabel(v);
  81456. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  81457. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  81458. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  81459. sqlite3VdbeResolveLabel(v, destIfFalse);
  81460. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  81461. sqlite3VdbeResolveLabel(v, destIfNull);
  81462. break;
  81463. }
  81464. #endif /* SQLITE_OMIT_SUBQUERY */
  81465. /*
  81466. ** x BETWEEN y AND z
  81467. **
  81468. ** This is equivalent to
  81469. **
  81470. ** x>=y AND x<=z
  81471. **
  81472. ** X is stored in pExpr->pLeft.
  81473. ** Y is stored in pExpr->pList->a[0].pExpr.
  81474. ** Z is stored in pExpr->pList->a[1].pExpr.
  81475. */
  81476. case TK_BETWEEN: {
  81477. Expr *pLeft = pExpr->pLeft;
  81478. struct ExprList_item *pLItem = pExpr->x.pList->a;
  81479. Expr *pRight = pLItem->pExpr;
  81480. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  81481. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  81482. testcase( regFree1==0 );
  81483. testcase( regFree2==0 );
  81484. r3 = sqlite3GetTempReg(pParse);
  81485. r4 = sqlite3GetTempReg(pParse);
  81486. codeCompare(pParse, pLeft, pRight, OP_Ge,
  81487. r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
  81488. pLItem++;
  81489. pRight = pLItem->pExpr;
  81490. sqlite3ReleaseTempReg(pParse, regFree2);
  81491. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  81492. testcase( regFree2==0 );
  81493. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  81494. VdbeCoverage(v);
  81495. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  81496. sqlite3ReleaseTempReg(pParse, r3);
  81497. sqlite3ReleaseTempReg(pParse, r4);
  81498. break;
  81499. }
  81500. case TK_COLLATE:
  81501. case TK_UPLUS: {
  81502. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  81503. break;
  81504. }
  81505. case TK_TRIGGER: {
  81506. /* If the opcode is TK_TRIGGER, then the expression is a reference
  81507. ** to a column in the new.* or old.* pseudo-tables available to
  81508. ** trigger programs. In this case Expr.iTable is set to 1 for the
  81509. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  81510. ** is set to the column of the pseudo-table to read, or to -1 to
  81511. ** read the rowid field.
  81512. **
  81513. ** The expression is implemented using an OP_Param opcode. The p1
  81514. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  81515. ** to reference another column of the old.* pseudo-table, where
  81516. ** i is the index of the column. For a new.rowid reference, p1 is
  81517. ** set to (n+1), where n is the number of columns in each pseudo-table.
  81518. ** For a reference to any other column in the new.* pseudo-table, p1
  81519. ** is set to (n+2+i), where n and i are as defined previously. For
  81520. ** example, if the table on which triggers are being fired is
  81521. ** declared as:
  81522. **
  81523. ** CREATE TABLE t1(a, b);
  81524. **
  81525. ** Then p1 is interpreted as follows:
  81526. **
  81527. ** p1==0 -> old.rowid p1==3 -> new.rowid
  81528. ** p1==1 -> old.a p1==4 -> new.a
  81529. ** p1==2 -> old.b p1==5 -> new.b
  81530. */
  81531. Table *pTab = pExpr->pTab;
  81532. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  81533. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  81534. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  81535. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  81536. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  81537. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  81538. VdbeComment((v, "%s.%s -> $%d",
  81539. (pExpr->iTable ? "new" : "old"),
  81540. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  81541. target
  81542. ));
  81543. #ifndef SQLITE_OMIT_FLOATING_POINT
  81544. /* If the column has REAL affinity, it may currently be stored as an
  81545. ** integer. Use OP_RealAffinity to make sure it is really real.
  81546. **
  81547. ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
  81548. ** floating point when extracting it from the record. */
  81549. if( pExpr->iColumn>=0
  81550. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  81551. ){
  81552. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  81553. }
  81554. #endif
  81555. break;
  81556. }
  81557. /*
  81558. ** Form A:
  81559. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  81560. **
  81561. ** Form B:
  81562. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  81563. **
  81564. ** Form A is can be transformed into the equivalent form B as follows:
  81565. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  81566. ** WHEN x=eN THEN rN ELSE y END
  81567. **
  81568. ** X (if it exists) is in pExpr->pLeft.
  81569. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  81570. ** odd. The Y is also optional. If the number of elements in x.pList
  81571. ** is even, then Y is omitted and the "otherwise" result is NULL.
  81572. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  81573. **
  81574. ** The result of the expression is the Ri for the first matching Ei,
  81575. ** or if there is no matching Ei, the ELSE term Y, or if there is
  81576. ** no ELSE term, NULL.
  81577. */
  81578. default: assert( op==TK_CASE ); {
  81579. int endLabel; /* GOTO label for end of CASE stmt */
  81580. int nextCase; /* GOTO label for next WHEN clause */
  81581. int nExpr; /* 2x number of WHEN terms */
  81582. int i; /* Loop counter */
  81583. ExprList *pEList; /* List of WHEN terms */
  81584. struct ExprList_item *aListelem; /* Array of WHEN terms */
  81585. Expr opCompare; /* The X==Ei expression */
  81586. Expr *pX; /* The X expression */
  81587. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  81588. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  81589. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  81590. assert(pExpr->x.pList->nExpr > 0);
  81591. pEList = pExpr->x.pList;
  81592. aListelem = pEList->a;
  81593. nExpr = pEList->nExpr;
  81594. endLabel = sqlite3VdbeMakeLabel(v);
  81595. if( (pX = pExpr->pLeft)!=0 ){
  81596. tempX = *pX;
  81597. testcase( pX->op==TK_COLUMN );
  81598. exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  81599. testcase( regFree1==0 );
  81600. opCompare.op = TK_EQ;
  81601. opCompare.pLeft = &tempX;
  81602. pTest = &opCompare;
  81603. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  81604. ** The value in regFree1 might get SCopy-ed into the file result.
  81605. ** So make sure that the regFree1 register is not reused for other
  81606. ** purposes and possibly overwritten. */
  81607. regFree1 = 0;
  81608. }
  81609. for(i=0; i<nExpr-1; i=i+2){
  81610. sqlite3ExprCachePush(pParse);
  81611. if( pX ){
  81612. assert( pTest!=0 );
  81613. opCompare.pRight = aListelem[i].pExpr;
  81614. }else{
  81615. pTest = aListelem[i].pExpr;
  81616. }
  81617. nextCase = sqlite3VdbeMakeLabel(v);
  81618. testcase( pTest->op==TK_COLUMN );
  81619. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  81620. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  81621. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  81622. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  81623. sqlite3ExprCachePop(pParse);
  81624. sqlite3VdbeResolveLabel(v, nextCase);
  81625. }
  81626. if( (nExpr&1)!=0 ){
  81627. sqlite3ExprCachePush(pParse);
  81628. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  81629. sqlite3ExprCachePop(pParse);
  81630. }else{
  81631. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  81632. }
  81633. assert( db->mallocFailed || pParse->nErr>0
  81634. || pParse->iCacheLevel==iCacheLevel );
  81635. sqlite3VdbeResolveLabel(v, endLabel);
  81636. break;
  81637. }
  81638. #ifndef SQLITE_OMIT_TRIGGER
  81639. case TK_RAISE: {
  81640. assert( pExpr->affinity==OE_Rollback
  81641. || pExpr->affinity==OE_Abort
  81642. || pExpr->affinity==OE_Fail
  81643. || pExpr->affinity==OE_Ignore
  81644. );
  81645. if( !pParse->pTriggerTab ){
  81646. sqlite3ErrorMsg(pParse,
  81647. "RAISE() may only be used within a trigger-program");
  81648. return 0;
  81649. }
  81650. if( pExpr->affinity==OE_Abort ){
  81651. sqlite3MayAbort(pParse);
  81652. }
  81653. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  81654. if( pExpr->affinity==OE_Ignore ){
  81655. sqlite3VdbeAddOp4(
  81656. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  81657. VdbeCoverage(v);
  81658. }else{
  81659. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  81660. pExpr->affinity, pExpr->u.zToken, 0, 0);
  81661. }
  81662. break;
  81663. }
  81664. #endif
  81665. }
  81666. sqlite3ReleaseTempReg(pParse, regFree1);
  81667. sqlite3ReleaseTempReg(pParse, regFree2);
  81668. return inReg;
  81669. }
  81670. /*
  81671. ** Factor out the code of the given expression to initialization time.
  81672. */
  81673. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
  81674. Parse *pParse, /* Parsing context */
  81675. Expr *pExpr, /* The expression to code when the VDBE initializes */
  81676. int regDest, /* Store the value in this register */
  81677. u8 reusable /* True if this expression is reusable */
  81678. ){
  81679. ExprList *p;
  81680. assert( ConstFactorOk(pParse) );
  81681. p = pParse->pConstExpr;
  81682. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  81683. p = sqlite3ExprListAppend(pParse, p, pExpr);
  81684. if( p ){
  81685. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  81686. pItem->u.iConstExprReg = regDest;
  81687. pItem->reusable = reusable;
  81688. }
  81689. pParse->pConstExpr = p;
  81690. }
  81691. /*
  81692. ** Generate code to evaluate an expression and store the results
  81693. ** into a register. Return the register number where the results
  81694. ** are stored.
  81695. **
  81696. ** If the register is a temporary register that can be deallocated,
  81697. ** then write its number into *pReg. If the result register is not
  81698. ** a temporary, then set *pReg to zero.
  81699. **
  81700. ** If pExpr is a constant, then this routine might generate this
  81701. ** code to fill the register in the initialization section of the
  81702. ** VDBE program, in order to factor it out of the evaluation loop.
  81703. */
  81704. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  81705. int r2;
  81706. pExpr = sqlite3ExprSkipCollate(pExpr);
  81707. if( ConstFactorOk(pParse)
  81708. && pExpr->op!=TK_REGISTER
  81709. && sqlite3ExprIsConstantNotJoin(pExpr)
  81710. ){
  81711. ExprList *p = pParse->pConstExpr;
  81712. int i;
  81713. *pReg = 0;
  81714. if( p ){
  81715. struct ExprList_item *pItem;
  81716. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  81717. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  81718. return pItem->u.iConstExprReg;
  81719. }
  81720. }
  81721. }
  81722. r2 = ++pParse->nMem;
  81723. sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
  81724. }else{
  81725. int r1 = sqlite3GetTempReg(pParse);
  81726. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  81727. if( r2==r1 ){
  81728. *pReg = r1;
  81729. }else{
  81730. sqlite3ReleaseTempReg(pParse, r1);
  81731. *pReg = 0;
  81732. }
  81733. }
  81734. return r2;
  81735. }
  81736. /*
  81737. ** Generate code that will evaluate expression pExpr and store the
  81738. ** results in register target. The results are guaranteed to appear
  81739. ** in register target.
  81740. */
  81741. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  81742. int inReg;
  81743. assert( target>0 && target<=pParse->nMem );
  81744. if( pExpr && pExpr->op==TK_REGISTER ){
  81745. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  81746. }else{
  81747. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  81748. assert( pParse->pVdbe || pParse->db->mallocFailed );
  81749. if( inReg!=target && pParse->pVdbe ){
  81750. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  81751. }
  81752. }
  81753. }
  81754. /*
  81755. ** Generate code that will evaluate expression pExpr and store the
  81756. ** results in register target. The results are guaranteed to appear
  81757. ** in register target. If the expression is constant, then this routine
  81758. ** might choose to code the expression at initialization time.
  81759. */
  81760. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  81761. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  81762. sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
  81763. }else{
  81764. sqlite3ExprCode(pParse, pExpr, target);
  81765. }
  81766. }
  81767. /*
  81768. ** Generate code that evaluates the given expression and puts the result
  81769. ** in register target.
  81770. **
  81771. ** Also make a copy of the expression results into another "cache" register
  81772. ** and modify the expression so that the next time it is evaluated,
  81773. ** the result is a copy of the cache register.
  81774. **
  81775. ** This routine is used for expressions that are used multiple
  81776. ** times. They are evaluated once and the results of the expression
  81777. ** are reused.
  81778. */
  81779. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  81780. Vdbe *v = pParse->pVdbe;
  81781. int iMem;
  81782. assert( target>0 );
  81783. assert( pExpr->op!=TK_REGISTER );
  81784. sqlite3ExprCode(pParse, pExpr, target);
  81785. iMem = ++pParse->nMem;
  81786. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  81787. exprToRegister(pExpr, iMem);
  81788. }
  81789. /*
  81790. ** Generate code that pushes the value of every element of the given
  81791. ** expression list into a sequence of registers beginning at target.
  81792. **
  81793. ** Return the number of elements evaluated.
  81794. **
  81795. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  81796. ** filled using OP_SCopy. OP_Copy must be used instead.
  81797. **
  81798. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  81799. ** factored out into initialization code.
  81800. */
  81801. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  81802. Parse *pParse, /* Parsing context */
  81803. ExprList *pList, /* The expression list to be coded */
  81804. int target, /* Where to write results */
  81805. u8 flags /* SQLITE_ECEL_* flags */
  81806. ){
  81807. struct ExprList_item *pItem;
  81808. int i, n;
  81809. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  81810. assert( pList!=0 );
  81811. assert( target>0 );
  81812. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  81813. n = pList->nExpr;
  81814. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  81815. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  81816. Expr *pExpr = pItem->pExpr;
  81817. if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  81818. sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
  81819. }else{
  81820. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  81821. if( inReg!=target+i ){
  81822. VdbeOp *pOp;
  81823. Vdbe *v = pParse->pVdbe;
  81824. if( copyOp==OP_Copy
  81825. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  81826. && pOp->p1+pOp->p3+1==inReg
  81827. && pOp->p2+pOp->p3+1==target+i
  81828. ){
  81829. pOp->p3++;
  81830. }else{
  81831. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  81832. }
  81833. }
  81834. }
  81835. }
  81836. return n;
  81837. }
  81838. /*
  81839. ** Generate code for a BETWEEN operator.
  81840. **
  81841. ** x BETWEEN y AND z
  81842. **
  81843. ** The above is equivalent to
  81844. **
  81845. ** x>=y AND x<=z
  81846. **
  81847. ** Code it as such, taking care to do the common subexpression
  81848. ** elimination of x.
  81849. */
  81850. static void exprCodeBetween(
  81851. Parse *pParse, /* Parsing and code generating context */
  81852. Expr *pExpr, /* The BETWEEN expression */
  81853. int dest, /* Jump here if the jump is taken */
  81854. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  81855. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  81856. ){
  81857. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  81858. Expr compLeft; /* The x>=y term */
  81859. Expr compRight; /* The x<=z term */
  81860. Expr exprX; /* The x subexpression */
  81861. int regFree1 = 0; /* Temporary use register */
  81862. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  81863. exprX = *pExpr->pLeft;
  81864. exprAnd.op = TK_AND;
  81865. exprAnd.pLeft = &compLeft;
  81866. exprAnd.pRight = &compRight;
  81867. compLeft.op = TK_GE;
  81868. compLeft.pLeft = &exprX;
  81869. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  81870. compRight.op = TK_LE;
  81871. compRight.pLeft = &exprX;
  81872. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  81873. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  81874. if( jumpIfTrue ){
  81875. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  81876. }else{
  81877. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  81878. }
  81879. sqlite3ReleaseTempReg(pParse, regFree1);
  81880. /* Ensure adequate test coverage */
  81881. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  81882. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  81883. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  81884. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  81885. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  81886. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  81887. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  81888. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  81889. }
  81890. /*
  81891. ** Generate code for a boolean expression such that a jump is made
  81892. ** to the label "dest" if the expression is true but execution
  81893. ** continues straight thru if the expression is false.
  81894. **
  81895. ** If the expression evaluates to NULL (neither true nor false), then
  81896. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  81897. **
  81898. ** This code depends on the fact that certain token values (ex: TK_EQ)
  81899. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  81900. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  81901. ** the make process cause these values to align. Assert()s in the code
  81902. ** below verify that the numbers are aligned correctly.
  81903. */
  81904. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  81905. Vdbe *v = pParse->pVdbe;
  81906. int op = 0;
  81907. int regFree1 = 0;
  81908. int regFree2 = 0;
  81909. int r1, r2;
  81910. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  81911. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  81912. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  81913. op = pExpr->op;
  81914. switch( op ){
  81915. case TK_AND: {
  81916. int d2 = sqlite3VdbeMakeLabel(v);
  81917. testcase( jumpIfNull==0 );
  81918. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  81919. sqlite3ExprCachePush(pParse);
  81920. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  81921. sqlite3VdbeResolveLabel(v, d2);
  81922. sqlite3ExprCachePop(pParse);
  81923. break;
  81924. }
  81925. case TK_OR: {
  81926. testcase( jumpIfNull==0 );
  81927. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  81928. sqlite3ExprCachePush(pParse);
  81929. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  81930. sqlite3ExprCachePop(pParse);
  81931. break;
  81932. }
  81933. case TK_NOT: {
  81934. testcase( jumpIfNull==0 );
  81935. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  81936. break;
  81937. }
  81938. case TK_LT:
  81939. case TK_LE:
  81940. case TK_GT:
  81941. case TK_GE:
  81942. case TK_NE:
  81943. case TK_EQ: {
  81944. testcase( jumpIfNull==0 );
  81945. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81946. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  81947. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  81948. r1, r2, dest, jumpIfNull);
  81949. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  81950. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  81951. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  81952. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  81953. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  81954. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  81955. testcase( regFree1==0 );
  81956. testcase( regFree2==0 );
  81957. break;
  81958. }
  81959. case TK_IS:
  81960. case TK_ISNOT: {
  81961. testcase( op==TK_IS );
  81962. testcase( op==TK_ISNOT );
  81963. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81964. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  81965. op = (op==TK_IS) ? TK_EQ : TK_NE;
  81966. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  81967. r1, r2, dest, SQLITE_NULLEQ);
  81968. VdbeCoverageIf(v, op==TK_EQ);
  81969. VdbeCoverageIf(v, op==TK_NE);
  81970. testcase( regFree1==0 );
  81971. testcase( regFree2==0 );
  81972. break;
  81973. }
  81974. case TK_ISNULL:
  81975. case TK_NOTNULL: {
  81976. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  81977. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  81978. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  81979. sqlite3VdbeAddOp2(v, op, r1, dest);
  81980. VdbeCoverageIf(v, op==TK_ISNULL);
  81981. VdbeCoverageIf(v, op==TK_NOTNULL);
  81982. testcase( regFree1==0 );
  81983. break;
  81984. }
  81985. case TK_BETWEEN: {
  81986. testcase( jumpIfNull==0 );
  81987. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  81988. break;
  81989. }
  81990. #ifndef SQLITE_OMIT_SUBQUERY
  81991. case TK_IN: {
  81992. int destIfFalse = sqlite3VdbeMakeLabel(v);
  81993. int destIfNull = jumpIfNull ? dest : destIfFalse;
  81994. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  81995. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  81996. sqlite3VdbeResolveLabel(v, destIfFalse);
  81997. break;
  81998. }
  81999. #endif
  82000. default: {
  82001. if( exprAlwaysTrue(pExpr) ){
  82002. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  82003. }else if( exprAlwaysFalse(pExpr) ){
  82004. /* No-op */
  82005. }else{
  82006. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  82007. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  82008. VdbeCoverage(v);
  82009. testcase( regFree1==0 );
  82010. testcase( jumpIfNull==0 );
  82011. }
  82012. break;
  82013. }
  82014. }
  82015. sqlite3ReleaseTempReg(pParse, regFree1);
  82016. sqlite3ReleaseTempReg(pParse, regFree2);
  82017. }
  82018. /*
  82019. ** Generate code for a boolean expression such that a jump is made
  82020. ** to the label "dest" if the expression is false but execution
  82021. ** continues straight thru if the expression is true.
  82022. **
  82023. ** If the expression evaluates to NULL (neither true nor false) then
  82024. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  82025. ** is 0.
  82026. */
  82027. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  82028. Vdbe *v = pParse->pVdbe;
  82029. int op = 0;
  82030. int regFree1 = 0;
  82031. int regFree2 = 0;
  82032. int r1, r2;
  82033. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  82034. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  82035. if( pExpr==0 ) return;
  82036. /* The value of pExpr->op and op are related as follows:
  82037. **
  82038. ** pExpr->op op
  82039. ** --------- ----------
  82040. ** TK_ISNULL OP_NotNull
  82041. ** TK_NOTNULL OP_IsNull
  82042. ** TK_NE OP_Eq
  82043. ** TK_EQ OP_Ne
  82044. ** TK_GT OP_Le
  82045. ** TK_LE OP_Gt
  82046. ** TK_GE OP_Lt
  82047. ** TK_LT OP_Ge
  82048. **
  82049. ** For other values of pExpr->op, op is undefined and unused.
  82050. ** The value of TK_ and OP_ constants are arranged such that we
  82051. ** can compute the mapping above using the following expression.
  82052. ** Assert()s verify that the computation is correct.
  82053. */
  82054. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  82055. /* Verify correct alignment of TK_ and OP_ constants
  82056. */
  82057. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  82058. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  82059. assert( pExpr->op!=TK_NE || op==OP_Eq );
  82060. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  82061. assert( pExpr->op!=TK_LT || op==OP_Ge );
  82062. assert( pExpr->op!=TK_LE || op==OP_Gt );
  82063. assert( pExpr->op!=TK_GT || op==OP_Le );
  82064. assert( pExpr->op!=TK_GE || op==OP_Lt );
  82065. switch( pExpr->op ){
  82066. case TK_AND: {
  82067. testcase( jumpIfNull==0 );
  82068. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  82069. sqlite3ExprCachePush(pParse);
  82070. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  82071. sqlite3ExprCachePop(pParse);
  82072. break;
  82073. }
  82074. case TK_OR: {
  82075. int d2 = sqlite3VdbeMakeLabel(v);
  82076. testcase( jumpIfNull==0 );
  82077. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  82078. sqlite3ExprCachePush(pParse);
  82079. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  82080. sqlite3VdbeResolveLabel(v, d2);
  82081. sqlite3ExprCachePop(pParse);
  82082. break;
  82083. }
  82084. case TK_NOT: {
  82085. testcase( jumpIfNull==0 );
  82086. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  82087. break;
  82088. }
  82089. case TK_LT:
  82090. case TK_LE:
  82091. case TK_GT:
  82092. case TK_GE:
  82093. case TK_NE:
  82094. case TK_EQ: {
  82095. testcase( jumpIfNull==0 );
  82096. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82097. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82098. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82099. r1, r2, dest, jumpIfNull);
  82100. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  82101. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  82102. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  82103. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  82104. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  82105. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  82106. testcase( regFree1==0 );
  82107. testcase( regFree2==0 );
  82108. break;
  82109. }
  82110. case TK_IS:
  82111. case TK_ISNOT: {
  82112. testcase( pExpr->op==TK_IS );
  82113. testcase( pExpr->op==TK_ISNOT );
  82114. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82115. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  82116. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  82117. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  82118. r1, r2, dest, SQLITE_NULLEQ);
  82119. VdbeCoverageIf(v, op==TK_EQ);
  82120. VdbeCoverageIf(v, op==TK_NE);
  82121. testcase( regFree1==0 );
  82122. testcase( regFree2==0 );
  82123. break;
  82124. }
  82125. case TK_ISNULL:
  82126. case TK_NOTNULL: {
  82127. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  82128. sqlite3VdbeAddOp2(v, op, r1, dest);
  82129. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  82130. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  82131. testcase( regFree1==0 );
  82132. break;
  82133. }
  82134. case TK_BETWEEN: {
  82135. testcase( jumpIfNull==0 );
  82136. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  82137. break;
  82138. }
  82139. #ifndef SQLITE_OMIT_SUBQUERY
  82140. case TK_IN: {
  82141. if( jumpIfNull ){
  82142. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  82143. }else{
  82144. int destIfNull = sqlite3VdbeMakeLabel(v);
  82145. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  82146. sqlite3VdbeResolveLabel(v, destIfNull);
  82147. }
  82148. break;
  82149. }
  82150. #endif
  82151. default: {
  82152. if( exprAlwaysFalse(pExpr) ){
  82153. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  82154. }else if( exprAlwaysTrue(pExpr) ){
  82155. /* no-op */
  82156. }else{
  82157. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  82158. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  82159. VdbeCoverage(v);
  82160. testcase( regFree1==0 );
  82161. testcase( jumpIfNull==0 );
  82162. }
  82163. break;
  82164. }
  82165. }
  82166. sqlite3ReleaseTempReg(pParse, regFree1);
  82167. sqlite3ReleaseTempReg(pParse, regFree2);
  82168. }
  82169. /*
  82170. ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
  82171. ** code generation, and that copy is deleted after code generation. This
  82172. ** ensures that the original pExpr is unchanged.
  82173. */
  82174. SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
  82175. sqlite3 *db = pParse->db;
  82176. Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
  82177. if( db->mallocFailed==0 ){
  82178. sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
  82179. }
  82180. sqlite3ExprDelete(db, pCopy);
  82181. }
  82182. /*
  82183. ** Do a deep comparison of two expression trees. Return 0 if the two
  82184. ** expressions are completely identical. Return 1 if they differ only
  82185. ** by a COLLATE operator at the top level. Return 2 if there are differences
  82186. ** other than the top-level COLLATE operator.
  82187. **
  82188. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  82189. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  82190. **
  82191. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  82192. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  82193. **
  82194. ** Sometimes this routine will return 2 even if the two expressions
  82195. ** really are equivalent. If we cannot prove that the expressions are
  82196. ** identical, we return 2 just to be safe. So if this routine
  82197. ** returns 2, then you do not really know for certain if the two
  82198. ** expressions are the same. But if you get a 0 or 1 return, then you
  82199. ** can be sure the expressions are the same. In the places where
  82200. ** this routine is used, it does not hurt to get an extra 2 - that
  82201. ** just might result in some slightly slower code. But returning
  82202. ** an incorrect 0 or 1 could lead to a malfunction.
  82203. */
  82204. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  82205. u32 combinedFlags;
  82206. if( pA==0 || pB==0 ){
  82207. return pB==pA ? 0 : 2;
  82208. }
  82209. combinedFlags = pA->flags | pB->flags;
  82210. if( combinedFlags & EP_IntValue ){
  82211. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  82212. return 0;
  82213. }
  82214. return 2;
  82215. }
  82216. if( pA->op!=pB->op ){
  82217. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  82218. return 1;
  82219. }
  82220. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  82221. return 1;
  82222. }
  82223. return 2;
  82224. }
  82225. if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
  82226. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  82227. return pA->op==TK_COLLATE ? 1 : 2;
  82228. }
  82229. }
  82230. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  82231. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  82232. if( combinedFlags & EP_xIsSelect ) return 2;
  82233. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  82234. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  82235. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  82236. if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
  82237. if( pA->iColumn!=pB->iColumn ) return 2;
  82238. if( pA->iTable!=pB->iTable
  82239. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  82240. }
  82241. }
  82242. return 0;
  82243. }
  82244. /*
  82245. ** Compare two ExprList objects. Return 0 if they are identical and
  82246. ** non-zero if they differ in any way.
  82247. **
  82248. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  82249. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  82250. **
  82251. ** This routine might return non-zero for equivalent ExprLists. The
  82252. ** only consequence will be disabled optimizations. But this routine
  82253. ** must never return 0 if the two ExprList objects are different, or
  82254. ** a malfunction will result.
  82255. **
  82256. ** Two NULL pointers are considered to be the same. But a NULL pointer
  82257. ** always differs from a non-NULL pointer.
  82258. */
  82259. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  82260. int i;
  82261. if( pA==0 && pB==0 ) return 0;
  82262. if( pA==0 || pB==0 ) return 1;
  82263. if( pA->nExpr!=pB->nExpr ) return 1;
  82264. for(i=0; i<pA->nExpr; i++){
  82265. Expr *pExprA = pA->a[i].pExpr;
  82266. Expr *pExprB = pB->a[i].pExpr;
  82267. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  82268. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  82269. }
  82270. return 0;
  82271. }
  82272. /*
  82273. ** Return true if we can prove the pE2 will always be true if pE1 is
  82274. ** true. Return false if we cannot complete the proof or if pE2 might
  82275. ** be false. Examples:
  82276. **
  82277. ** pE1: x==5 pE2: x==5 Result: true
  82278. ** pE1: x>0 pE2: x==5 Result: false
  82279. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  82280. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  82281. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  82282. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  82283. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  82284. **
  82285. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  82286. ** Expr.iTable<0 then assume a table number given by iTab.
  82287. **
  82288. ** When in doubt, return false. Returning true might give a performance
  82289. ** improvement. Returning false might cause a performance reduction, but
  82290. ** it will always give the correct answer and is hence always safe.
  82291. */
  82292. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  82293. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  82294. return 1;
  82295. }
  82296. if( pE2->op==TK_OR
  82297. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  82298. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  82299. ){
  82300. return 1;
  82301. }
  82302. if( pE2->op==TK_NOTNULL
  82303. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  82304. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  82305. ){
  82306. return 1;
  82307. }
  82308. return 0;
  82309. }
  82310. /*
  82311. ** An instance of the following structure is used by the tree walker
  82312. ** to count references to table columns in the arguments of an
  82313. ** aggregate function, in order to implement the
  82314. ** sqlite3FunctionThisSrc() routine.
  82315. */
  82316. struct SrcCount {
  82317. SrcList *pSrc; /* One particular FROM clause in a nested query */
  82318. int nThis; /* Number of references to columns in pSrcList */
  82319. int nOther; /* Number of references to columns in other FROM clauses */
  82320. };
  82321. /*
  82322. ** Count the number of references to columns.
  82323. */
  82324. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  82325. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  82326. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  82327. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  82328. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  82329. ** NEVER() will need to be removed. */
  82330. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  82331. int i;
  82332. struct SrcCount *p = pWalker->u.pSrcCount;
  82333. SrcList *pSrc = p->pSrc;
  82334. int nSrc = pSrc ? pSrc->nSrc : 0;
  82335. for(i=0; i<nSrc; i++){
  82336. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  82337. }
  82338. if( i<nSrc ){
  82339. p->nThis++;
  82340. }else{
  82341. p->nOther++;
  82342. }
  82343. }
  82344. return WRC_Continue;
  82345. }
  82346. /*
  82347. ** Determine if any of the arguments to the pExpr Function reference
  82348. ** pSrcList. Return true if they do. Also return true if the function
  82349. ** has no arguments or has only constant arguments. Return false if pExpr
  82350. ** references columns but not columns of tables found in pSrcList.
  82351. */
  82352. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  82353. Walker w;
  82354. struct SrcCount cnt;
  82355. assert( pExpr->op==TK_AGG_FUNCTION );
  82356. memset(&w, 0, sizeof(w));
  82357. w.xExprCallback = exprSrcCount;
  82358. w.u.pSrcCount = &cnt;
  82359. cnt.pSrc = pSrcList;
  82360. cnt.nThis = 0;
  82361. cnt.nOther = 0;
  82362. sqlite3WalkExprList(&w, pExpr->x.pList);
  82363. return cnt.nThis>0 || cnt.nOther==0;
  82364. }
  82365. /*
  82366. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  82367. ** the new element. Return a negative number if malloc fails.
  82368. */
  82369. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  82370. int i;
  82371. pInfo->aCol = sqlite3ArrayAllocate(
  82372. db,
  82373. pInfo->aCol,
  82374. sizeof(pInfo->aCol[0]),
  82375. &pInfo->nColumn,
  82376. &i
  82377. );
  82378. return i;
  82379. }
  82380. /*
  82381. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  82382. ** the new element. Return a negative number if malloc fails.
  82383. */
  82384. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  82385. int i;
  82386. pInfo->aFunc = sqlite3ArrayAllocate(
  82387. db,
  82388. pInfo->aFunc,
  82389. sizeof(pInfo->aFunc[0]),
  82390. &pInfo->nFunc,
  82391. &i
  82392. );
  82393. return i;
  82394. }
  82395. /*
  82396. ** This is the xExprCallback for a tree walker. It is used to
  82397. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  82398. ** for additional information.
  82399. */
  82400. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  82401. int i;
  82402. NameContext *pNC = pWalker->u.pNC;
  82403. Parse *pParse = pNC->pParse;
  82404. SrcList *pSrcList = pNC->pSrcList;
  82405. AggInfo *pAggInfo = pNC->pAggInfo;
  82406. switch( pExpr->op ){
  82407. case TK_AGG_COLUMN:
  82408. case TK_COLUMN: {
  82409. testcase( pExpr->op==TK_AGG_COLUMN );
  82410. testcase( pExpr->op==TK_COLUMN );
  82411. /* Check to see if the column is in one of the tables in the FROM
  82412. ** clause of the aggregate query */
  82413. if( ALWAYS(pSrcList!=0) ){
  82414. struct SrcList_item *pItem = pSrcList->a;
  82415. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  82416. struct AggInfo_col *pCol;
  82417. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  82418. if( pExpr->iTable==pItem->iCursor ){
  82419. /* If we reach this point, it means that pExpr refers to a table
  82420. ** that is in the FROM clause of the aggregate query.
  82421. **
  82422. ** Make an entry for the column in pAggInfo->aCol[] if there
  82423. ** is not an entry there already.
  82424. */
  82425. int k;
  82426. pCol = pAggInfo->aCol;
  82427. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  82428. if( pCol->iTable==pExpr->iTable &&
  82429. pCol->iColumn==pExpr->iColumn ){
  82430. break;
  82431. }
  82432. }
  82433. if( (k>=pAggInfo->nColumn)
  82434. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  82435. ){
  82436. pCol = &pAggInfo->aCol[k];
  82437. pCol->pTab = pExpr->pTab;
  82438. pCol->iTable = pExpr->iTable;
  82439. pCol->iColumn = pExpr->iColumn;
  82440. pCol->iMem = ++pParse->nMem;
  82441. pCol->iSorterColumn = -1;
  82442. pCol->pExpr = pExpr;
  82443. if( pAggInfo->pGroupBy ){
  82444. int j, n;
  82445. ExprList *pGB = pAggInfo->pGroupBy;
  82446. struct ExprList_item *pTerm = pGB->a;
  82447. n = pGB->nExpr;
  82448. for(j=0; j<n; j++, pTerm++){
  82449. Expr *pE = pTerm->pExpr;
  82450. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  82451. pE->iColumn==pExpr->iColumn ){
  82452. pCol->iSorterColumn = j;
  82453. break;
  82454. }
  82455. }
  82456. }
  82457. if( pCol->iSorterColumn<0 ){
  82458. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  82459. }
  82460. }
  82461. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  82462. ** because it was there before or because we just created it).
  82463. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  82464. ** pAggInfo->aCol[] entry.
  82465. */
  82466. ExprSetVVAProperty(pExpr, EP_NoReduce);
  82467. pExpr->pAggInfo = pAggInfo;
  82468. pExpr->op = TK_AGG_COLUMN;
  82469. pExpr->iAgg = (i16)k;
  82470. break;
  82471. } /* endif pExpr->iTable==pItem->iCursor */
  82472. } /* end loop over pSrcList */
  82473. }
  82474. return WRC_Prune;
  82475. }
  82476. case TK_AGG_FUNCTION: {
  82477. if( (pNC->ncFlags & NC_InAggFunc)==0
  82478. && pWalker->walkerDepth==pExpr->op2
  82479. ){
  82480. /* Check to see if pExpr is a duplicate of another aggregate
  82481. ** function that is already in the pAggInfo structure
  82482. */
  82483. struct AggInfo_func *pItem = pAggInfo->aFunc;
  82484. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  82485. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  82486. break;
  82487. }
  82488. }
  82489. if( i>=pAggInfo->nFunc ){
  82490. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  82491. */
  82492. u8 enc = ENC(pParse->db);
  82493. i = addAggInfoFunc(pParse->db, pAggInfo);
  82494. if( i>=0 ){
  82495. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  82496. pItem = &pAggInfo->aFunc[i];
  82497. pItem->pExpr = pExpr;
  82498. pItem->iMem = ++pParse->nMem;
  82499. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  82500. pItem->pFunc = sqlite3FindFunction(pParse->db,
  82501. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  82502. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  82503. if( pExpr->flags & EP_Distinct ){
  82504. pItem->iDistinct = pParse->nTab++;
  82505. }else{
  82506. pItem->iDistinct = -1;
  82507. }
  82508. }
  82509. }
  82510. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  82511. */
  82512. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  82513. ExprSetVVAProperty(pExpr, EP_NoReduce);
  82514. pExpr->iAgg = (i16)i;
  82515. pExpr->pAggInfo = pAggInfo;
  82516. return WRC_Prune;
  82517. }else{
  82518. return WRC_Continue;
  82519. }
  82520. }
  82521. }
  82522. return WRC_Continue;
  82523. }
  82524. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  82525. UNUSED_PARAMETER(pWalker);
  82526. UNUSED_PARAMETER(pSelect);
  82527. return WRC_Continue;
  82528. }
  82529. /*
  82530. ** Analyze the pExpr expression looking for aggregate functions and
  82531. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  82532. ** points to. Additional entries are made on the AggInfo object as
  82533. ** necessary.
  82534. **
  82535. ** This routine should only be called after the expression has been
  82536. ** analyzed by sqlite3ResolveExprNames().
  82537. */
  82538. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  82539. Walker w;
  82540. memset(&w, 0, sizeof(w));
  82541. w.xExprCallback = analyzeAggregate;
  82542. w.xSelectCallback = analyzeAggregatesInSelect;
  82543. w.u.pNC = pNC;
  82544. assert( pNC->pSrcList!=0 );
  82545. sqlite3WalkExpr(&w, pExpr);
  82546. }
  82547. /*
  82548. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  82549. ** expression list. Return the number of errors.
  82550. **
  82551. ** If an error is found, the analysis is cut short.
  82552. */
  82553. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  82554. struct ExprList_item *pItem;
  82555. int i;
  82556. if( pList ){
  82557. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  82558. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  82559. }
  82560. }
  82561. }
  82562. /*
  82563. ** Allocate a single new register for use to hold some intermediate result.
  82564. */
  82565. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  82566. if( pParse->nTempReg==0 ){
  82567. return ++pParse->nMem;
  82568. }
  82569. return pParse->aTempReg[--pParse->nTempReg];
  82570. }
  82571. /*
  82572. ** Deallocate a register, making available for reuse for some other
  82573. ** purpose.
  82574. **
  82575. ** If a register is currently being used by the column cache, then
  82576. ** the deallocation is deferred until the column cache line that uses
  82577. ** the register becomes stale.
  82578. */
  82579. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  82580. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  82581. int i;
  82582. struct yColCache *p;
  82583. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  82584. if( p->iReg==iReg ){
  82585. p->tempReg = 1;
  82586. return;
  82587. }
  82588. }
  82589. pParse->aTempReg[pParse->nTempReg++] = iReg;
  82590. }
  82591. }
  82592. /*
  82593. ** Allocate or deallocate a block of nReg consecutive registers
  82594. */
  82595. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  82596. int i, n;
  82597. i = pParse->iRangeReg;
  82598. n = pParse->nRangeReg;
  82599. if( nReg<=n ){
  82600. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  82601. pParse->iRangeReg += nReg;
  82602. pParse->nRangeReg -= nReg;
  82603. }else{
  82604. i = pParse->nMem+1;
  82605. pParse->nMem += nReg;
  82606. }
  82607. return i;
  82608. }
  82609. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  82610. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  82611. if( nReg>pParse->nRangeReg ){
  82612. pParse->nRangeReg = nReg;
  82613. pParse->iRangeReg = iReg;
  82614. }
  82615. }
  82616. /*
  82617. ** Mark all temporary registers as being unavailable for reuse.
  82618. */
  82619. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  82620. pParse->nTempReg = 0;
  82621. pParse->nRangeReg = 0;
  82622. }
  82623. /************** End of expr.c ************************************************/
  82624. /************** Begin file alter.c *******************************************/
  82625. /*
  82626. ** 2005 February 15
  82627. **
  82628. ** The author disclaims copyright to this source code. In place of
  82629. ** a legal notice, here is a blessing:
  82630. **
  82631. ** May you do good and not evil.
  82632. ** May you find forgiveness for yourself and forgive others.
  82633. ** May you share freely, never taking more than you give.
  82634. **
  82635. *************************************************************************
  82636. ** This file contains C code routines that used to generate VDBE code
  82637. ** that implements the ALTER TABLE command.
  82638. */
  82639. /* #include "sqliteInt.h" */
  82640. /*
  82641. ** The code in this file only exists if we are not omitting the
  82642. ** ALTER TABLE logic from the build.
  82643. */
  82644. #ifndef SQLITE_OMIT_ALTERTABLE
  82645. /*
  82646. ** This function is used by SQL generated to implement the
  82647. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  82648. ** CREATE INDEX command. The second is a table name. The table name in
  82649. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  82650. ** argument and the result returned. Examples:
  82651. **
  82652. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  82653. ** -> 'CREATE TABLE def(a, b, c)'
  82654. **
  82655. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  82656. ** -> 'CREATE INDEX i ON def(a, b, c)'
  82657. */
  82658. static void renameTableFunc(
  82659. sqlite3_context *context,
  82660. int NotUsed,
  82661. sqlite3_value **argv
  82662. ){
  82663. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  82664. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  82665. int token;
  82666. Token tname;
  82667. unsigned char const *zCsr = zSql;
  82668. int len = 0;
  82669. char *zRet;
  82670. sqlite3 *db = sqlite3_context_db_handle(context);
  82671. UNUSED_PARAMETER(NotUsed);
  82672. /* The principle used to locate the table name in the CREATE TABLE
  82673. ** statement is that the table name is the first non-space token that
  82674. ** is immediately followed by a TK_LP or TK_USING token.
  82675. */
  82676. if( zSql ){
  82677. do {
  82678. if( !*zCsr ){
  82679. /* Ran out of input before finding an opening bracket. Return NULL. */
  82680. return;
  82681. }
  82682. /* Store the token that zCsr points to in tname. */
  82683. tname.z = (char*)zCsr;
  82684. tname.n = len;
  82685. /* Advance zCsr to the next token. Store that token type in 'token',
  82686. ** and its length in 'len' (to be used next iteration of this loop).
  82687. */
  82688. do {
  82689. zCsr += len;
  82690. len = sqlite3GetToken(zCsr, &token);
  82691. } while( token==TK_SPACE );
  82692. assert( len>0 );
  82693. } while( token!=TK_LP && token!=TK_USING );
  82694. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  82695. zSql, zTableName, tname.z+tname.n);
  82696. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  82697. }
  82698. }
  82699. /*
  82700. ** This C function implements an SQL user function that is used by SQL code
  82701. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  82702. ** of any foreign key constraints that use the table being renamed as the
  82703. ** parent table. It is passed three arguments:
  82704. **
  82705. ** 1) The complete text of the CREATE TABLE statement being modified,
  82706. ** 2) The old name of the table being renamed, and
  82707. ** 3) The new name of the table being renamed.
  82708. **
  82709. ** It returns the new CREATE TABLE statement. For example:
  82710. **
  82711. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  82712. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  82713. */
  82714. #ifndef SQLITE_OMIT_FOREIGN_KEY
  82715. static void renameParentFunc(
  82716. sqlite3_context *context,
  82717. int NotUsed,
  82718. sqlite3_value **argv
  82719. ){
  82720. sqlite3 *db = sqlite3_context_db_handle(context);
  82721. char *zOutput = 0;
  82722. char *zResult;
  82723. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  82724. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  82725. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  82726. unsigned const char *z; /* Pointer to token */
  82727. int n; /* Length of token z */
  82728. int token; /* Type of token */
  82729. UNUSED_PARAMETER(NotUsed);
  82730. if( zInput==0 || zOld==0 ) return;
  82731. for(z=zInput; *z; z=z+n){
  82732. n = sqlite3GetToken(z, &token);
  82733. if( token==TK_REFERENCES ){
  82734. char *zParent;
  82735. do {
  82736. z += n;
  82737. n = sqlite3GetToken(z, &token);
  82738. }while( token==TK_SPACE );
  82739. if( token==TK_ILLEGAL ) break;
  82740. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  82741. if( zParent==0 ) break;
  82742. sqlite3Dequote(zParent);
  82743. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  82744. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  82745. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  82746. );
  82747. sqlite3DbFree(db, zOutput);
  82748. zOutput = zOut;
  82749. zInput = &z[n];
  82750. }
  82751. sqlite3DbFree(db, zParent);
  82752. }
  82753. }
  82754. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  82755. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  82756. sqlite3DbFree(db, zOutput);
  82757. }
  82758. #endif
  82759. #ifndef SQLITE_OMIT_TRIGGER
  82760. /* This function is used by SQL generated to implement the
  82761. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  82762. ** statement. The second is a table name. The table name in the CREATE
  82763. ** TRIGGER statement is replaced with the third argument and the result
  82764. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  82765. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  82766. */
  82767. static void renameTriggerFunc(
  82768. sqlite3_context *context,
  82769. int NotUsed,
  82770. sqlite3_value **argv
  82771. ){
  82772. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  82773. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  82774. int token;
  82775. Token tname;
  82776. int dist = 3;
  82777. unsigned char const *zCsr = zSql;
  82778. int len = 0;
  82779. char *zRet;
  82780. sqlite3 *db = sqlite3_context_db_handle(context);
  82781. UNUSED_PARAMETER(NotUsed);
  82782. /* The principle used to locate the table name in the CREATE TRIGGER
  82783. ** statement is that the table name is the first token that is immediately
  82784. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  82785. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  82786. */
  82787. if( zSql ){
  82788. do {
  82789. if( !*zCsr ){
  82790. /* Ran out of input before finding the table name. Return NULL. */
  82791. return;
  82792. }
  82793. /* Store the token that zCsr points to in tname. */
  82794. tname.z = (char*)zCsr;
  82795. tname.n = len;
  82796. /* Advance zCsr to the next token. Store that token type in 'token',
  82797. ** and its length in 'len' (to be used next iteration of this loop).
  82798. */
  82799. do {
  82800. zCsr += len;
  82801. len = sqlite3GetToken(zCsr, &token);
  82802. }while( token==TK_SPACE );
  82803. assert( len>0 );
  82804. /* Variable 'dist' stores the number of tokens read since the most
  82805. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  82806. ** token is read and 'dist' equals 2, the condition stated above
  82807. ** to be met.
  82808. **
  82809. ** Note that ON cannot be a database, table or column name, so
  82810. ** there is no need to worry about syntax like
  82811. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  82812. */
  82813. dist++;
  82814. if( token==TK_DOT || token==TK_ON ){
  82815. dist = 0;
  82816. }
  82817. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  82818. /* Variable tname now contains the token that is the old table-name
  82819. ** in the CREATE TRIGGER statement.
  82820. */
  82821. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  82822. zSql, zTableName, tname.z+tname.n);
  82823. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  82824. }
  82825. }
  82826. #endif /* !SQLITE_OMIT_TRIGGER */
  82827. /*
  82828. ** Register built-in functions used to help implement ALTER TABLE
  82829. */
  82830. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  82831. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  82832. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  82833. #ifndef SQLITE_OMIT_TRIGGER
  82834. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  82835. #endif
  82836. #ifndef SQLITE_OMIT_FOREIGN_KEY
  82837. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  82838. #endif
  82839. };
  82840. int i;
  82841. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  82842. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  82843. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  82844. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  82845. }
  82846. }
  82847. /*
  82848. ** This function is used to create the text of expressions of the form:
  82849. **
  82850. ** name=<constant1> OR name=<constant2> OR ...
  82851. **
  82852. ** If argument zWhere is NULL, then a pointer string containing the text
  82853. ** "name=<constant>" is returned, where <constant> is the quoted version
  82854. ** of the string passed as argument zConstant. The returned buffer is
  82855. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  82856. ** caller to ensure that it is eventually freed.
  82857. **
  82858. ** If argument zWhere is not NULL, then the string returned is
  82859. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  82860. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  82861. **
  82862. */
  82863. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  82864. char *zNew;
  82865. if( !zWhere ){
  82866. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  82867. }else{
  82868. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  82869. sqlite3DbFree(db, zWhere);
  82870. }
  82871. return zNew;
  82872. }
  82873. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  82874. /*
  82875. ** Generate the text of a WHERE expression which can be used to select all
  82876. ** tables that have foreign key constraints that refer to table pTab (i.e.
  82877. ** constraints for which pTab is the parent table) from the sqlite_master
  82878. ** table.
  82879. */
  82880. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  82881. FKey *p;
  82882. char *zWhere = 0;
  82883. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  82884. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  82885. }
  82886. return zWhere;
  82887. }
  82888. #endif
  82889. /*
  82890. ** Generate the text of a WHERE expression which can be used to select all
  82891. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  82892. ** table pTab has no temporary triggers, or is itself stored in the
  82893. ** temporary database, NULL is returned.
  82894. */
  82895. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  82896. Trigger *pTrig;
  82897. char *zWhere = 0;
  82898. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  82899. /* If the table is not located in the temp-db (in which case NULL is
  82900. ** returned, loop through the tables list of triggers. For each trigger
  82901. ** that is not part of the temp-db schema, add a clause to the WHERE
  82902. ** expression being built up in zWhere.
  82903. */
  82904. if( pTab->pSchema!=pTempSchema ){
  82905. sqlite3 *db = pParse->db;
  82906. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  82907. if( pTrig->pSchema==pTempSchema ){
  82908. zWhere = whereOrName(db, zWhere, pTrig->zName);
  82909. }
  82910. }
  82911. }
  82912. if( zWhere ){
  82913. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  82914. sqlite3DbFree(pParse->db, zWhere);
  82915. zWhere = zNew;
  82916. }
  82917. return zWhere;
  82918. }
  82919. /*
  82920. ** Generate code to drop and reload the internal representation of table
  82921. ** pTab from the database, including triggers and temporary triggers.
  82922. ** Argument zName is the name of the table in the database schema at
  82923. ** the time the generated code is executed. This can be different from
  82924. ** pTab->zName if this function is being called to code part of an
  82925. ** "ALTER TABLE RENAME TO" statement.
  82926. */
  82927. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  82928. Vdbe *v;
  82929. char *zWhere;
  82930. int iDb; /* Index of database containing pTab */
  82931. #ifndef SQLITE_OMIT_TRIGGER
  82932. Trigger *pTrig;
  82933. #endif
  82934. v = sqlite3GetVdbe(pParse);
  82935. if( NEVER(v==0) ) return;
  82936. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  82937. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  82938. assert( iDb>=0 );
  82939. #ifndef SQLITE_OMIT_TRIGGER
  82940. /* Drop any table triggers from the internal schema. */
  82941. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  82942. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  82943. assert( iTrigDb==iDb || iTrigDb==1 );
  82944. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  82945. }
  82946. #endif
  82947. /* Drop the table and index from the internal schema. */
  82948. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  82949. /* Reload the table, index and permanent trigger schemas. */
  82950. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  82951. if( !zWhere ) return;
  82952. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  82953. #ifndef SQLITE_OMIT_TRIGGER
  82954. /* Now, if the table is not stored in the temp database, reload any temp
  82955. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  82956. */
  82957. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  82958. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  82959. }
  82960. #endif
  82961. }
  82962. /*
  82963. ** Parameter zName is the name of a table that is about to be altered
  82964. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  82965. ** If the table is a system table, this function leaves an error message
  82966. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  82967. **
  82968. ** Or, if zName is not a system table, zero is returned.
  82969. */
  82970. static int isSystemTable(Parse *pParse, const char *zName){
  82971. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  82972. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  82973. return 1;
  82974. }
  82975. return 0;
  82976. }
  82977. /*
  82978. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  82979. ** command.
  82980. */
  82981. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  82982. Parse *pParse, /* Parser context. */
  82983. SrcList *pSrc, /* The table to rename. */
  82984. Token *pName /* The new table name. */
  82985. ){
  82986. int iDb; /* Database that contains the table */
  82987. char *zDb; /* Name of database iDb */
  82988. Table *pTab; /* Table being renamed */
  82989. char *zName = 0; /* NULL-terminated version of pName */
  82990. sqlite3 *db = pParse->db; /* Database connection */
  82991. int nTabName; /* Number of UTF-8 characters in zTabName */
  82992. const char *zTabName; /* Original name of the table */
  82993. Vdbe *v;
  82994. #ifndef SQLITE_OMIT_TRIGGER
  82995. char *zWhere = 0; /* Where clause to locate temp triggers */
  82996. #endif
  82997. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  82998. int savedDbFlags; /* Saved value of db->flags */
  82999. savedDbFlags = db->flags;
  83000. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  83001. assert( pSrc->nSrc==1 );
  83002. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  83003. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  83004. if( !pTab ) goto exit_rename_table;
  83005. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83006. zDb = db->aDb[iDb].zName;
  83007. db->flags |= SQLITE_PreferBuiltin;
  83008. /* Get a NULL terminated version of the new table name. */
  83009. zName = sqlite3NameFromToken(db, pName);
  83010. if( !zName ) goto exit_rename_table;
  83011. /* Check that a table or index named 'zName' does not already exist
  83012. ** in database iDb. If so, this is an error.
  83013. */
  83014. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  83015. sqlite3ErrorMsg(pParse,
  83016. "there is already another table or index with this name: %s", zName);
  83017. goto exit_rename_table;
  83018. }
  83019. /* Make sure it is not a system table being altered, or a reserved name
  83020. ** that the table is being renamed to.
  83021. */
  83022. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  83023. goto exit_rename_table;
  83024. }
  83025. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  83026. exit_rename_table;
  83027. }
  83028. #ifndef SQLITE_OMIT_VIEW
  83029. if( pTab->pSelect ){
  83030. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  83031. goto exit_rename_table;
  83032. }
  83033. #endif
  83034. #ifndef SQLITE_OMIT_AUTHORIZATION
  83035. /* Invoke the authorization callback. */
  83036. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  83037. goto exit_rename_table;
  83038. }
  83039. #endif
  83040. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83041. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  83042. goto exit_rename_table;
  83043. }
  83044. if( IsVirtual(pTab) ){
  83045. pVTab = sqlite3GetVTable(db, pTab);
  83046. if( pVTab->pVtab->pModule->xRename==0 ){
  83047. pVTab = 0;
  83048. }
  83049. }
  83050. #endif
  83051. /* Begin a transaction for database iDb.
  83052. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  83053. ** schema). Open a statement transaction if the table is a virtual
  83054. ** table.
  83055. */
  83056. v = sqlite3GetVdbe(pParse);
  83057. if( v==0 ){
  83058. goto exit_rename_table;
  83059. }
  83060. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  83061. sqlite3ChangeCookie(pParse, iDb);
  83062. /* If this is a virtual table, invoke the xRename() function if
  83063. ** one is defined. The xRename() callback will modify the names
  83064. ** of any resources used by the v-table implementation (including other
  83065. ** SQLite tables) that are identified by the name of the virtual table.
  83066. */
  83067. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83068. if( pVTab ){
  83069. int i = ++pParse->nMem;
  83070. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  83071. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  83072. sqlite3MayAbort(pParse);
  83073. }
  83074. #endif
  83075. /* figure out how many UTF-8 characters are in zName */
  83076. zTabName = pTab->zName;
  83077. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  83078. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  83079. if( db->flags&SQLITE_ForeignKeys ){
  83080. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  83081. ** statements corresponding to all child tables of foreign key constraints
  83082. ** for which the renamed table is the parent table. */
  83083. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  83084. sqlite3NestedParse(pParse,
  83085. "UPDATE \"%w\".%s SET "
  83086. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  83087. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  83088. sqlite3DbFree(db, zWhere);
  83089. }
  83090. }
  83091. #endif
  83092. /* Modify the sqlite_master table to use the new table name. */
  83093. sqlite3NestedParse(pParse,
  83094. "UPDATE %Q.%s SET "
  83095. #ifdef SQLITE_OMIT_TRIGGER
  83096. "sql = sqlite_rename_table(sql, %Q), "
  83097. #else
  83098. "sql = CASE "
  83099. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  83100. "ELSE sqlite_rename_table(sql, %Q) END, "
  83101. #endif
  83102. "tbl_name = %Q, "
  83103. "name = CASE "
  83104. "WHEN type='table' THEN %Q "
  83105. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  83106. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  83107. "ELSE name END "
  83108. "WHERE tbl_name=%Q COLLATE nocase AND "
  83109. "(type='table' OR type='index' OR type='trigger');",
  83110. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  83111. #ifndef SQLITE_OMIT_TRIGGER
  83112. zName,
  83113. #endif
  83114. zName, nTabName, zTabName
  83115. );
  83116. #ifndef SQLITE_OMIT_AUTOINCREMENT
  83117. /* If the sqlite_sequence table exists in this database, then update
  83118. ** it with the new table name.
  83119. */
  83120. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  83121. sqlite3NestedParse(pParse,
  83122. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  83123. zDb, zName, pTab->zName);
  83124. }
  83125. #endif
  83126. #ifndef SQLITE_OMIT_TRIGGER
  83127. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  83128. ** table. Don't do this if the table being ALTERed is itself located in
  83129. ** the temp database.
  83130. */
  83131. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  83132. sqlite3NestedParse(pParse,
  83133. "UPDATE sqlite_temp_master SET "
  83134. "sql = sqlite_rename_trigger(sql, %Q), "
  83135. "tbl_name = %Q "
  83136. "WHERE %s;", zName, zName, zWhere);
  83137. sqlite3DbFree(db, zWhere);
  83138. }
  83139. #endif
  83140. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  83141. if( db->flags&SQLITE_ForeignKeys ){
  83142. FKey *p;
  83143. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  83144. Table *pFrom = p->pFrom;
  83145. if( pFrom!=pTab ){
  83146. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  83147. }
  83148. }
  83149. }
  83150. #endif
  83151. /* Drop and reload the internal table schema. */
  83152. reloadTableSchema(pParse, pTab, zName);
  83153. exit_rename_table:
  83154. sqlite3SrcListDelete(db, pSrc);
  83155. sqlite3DbFree(db, zName);
  83156. db->flags = savedDbFlags;
  83157. }
  83158. /*
  83159. ** Generate code to make sure the file format number is at least minFormat.
  83160. ** The generated code will increase the file format number if necessary.
  83161. */
  83162. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  83163. Vdbe *v;
  83164. v = sqlite3GetVdbe(pParse);
  83165. /* The VDBE should have been allocated before this routine is called.
  83166. ** If that allocation failed, we would have quit before reaching this
  83167. ** point */
  83168. if( ALWAYS(v) ){
  83169. int r1 = sqlite3GetTempReg(pParse);
  83170. int r2 = sqlite3GetTempReg(pParse);
  83171. int j1;
  83172. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  83173. sqlite3VdbeUsesBtree(v, iDb);
  83174. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  83175. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  83176. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
  83177. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  83178. sqlite3VdbeJumpHere(v, j1);
  83179. sqlite3ReleaseTempReg(pParse, r1);
  83180. sqlite3ReleaseTempReg(pParse, r2);
  83181. }
  83182. }
  83183. /*
  83184. ** This function is called after an "ALTER TABLE ... ADD" statement
  83185. ** has been parsed. Argument pColDef contains the text of the new
  83186. ** column definition.
  83187. **
  83188. ** The Table structure pParse->pNewTable was extended to include
  83189. ** the new column during parsing.
  83190. */
  83191. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  83192. Table *pNew; /* Copy of pParse->pNewTable */
  83193. Table *pTab; /* Table being altered */
  83194. int iDb; /* Database number */
  83195. const char *zDb; /* Database name */
  83196. const char *zTab; /* Table name */
  83197. char *zCol; /* Null-terminated column definition */
  83198. Column *pCol; /* The new column */
  83199. Expr *pDflt; /* Default value for the new column */
  83200. sqlite3 *db; /* The database connection; */
  83201. db = pParse->db;
  83202. if( pParse->nErr || db->mallocFailed ) return;
  83203. pNew = pParse->pNewTable;
  83204. assert( pNew );
  83205. assert( sqlite3BtreeHoldsAllMutexes(db) );
  83206. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  83207. zDb = db->aDb[iDb].zName;
  83208. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  83209. pCol = &pNew->aCol[pNew->nCol-1];
  83210. pDflt = pCol->pDflt;
  83211. pTab = sqlite3FindTable(db, zTab, zDb);
  83212. assert( pTab );
  83213. #ifndef SQLITE_OMIT_AUTHORIZATION
  83214. /* Invoke the authorization callback. */
  83215. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  83216. return;
  83217. }
  83218. #endif
  83219. /* If the default value for the new column was specified with a
  83220. ** literal NULL, then set pDflt to 0. This simplifies checking
  83221. ** for an SQL NULL default below.
  83222. */
  83223. if( pDflt && pDflt->op==TK_NULL ){
  83224. pDflt = 0;
  83225. }
  83226. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  83227. ** If there is a NOT NULL constraint, then the default value for the
  83228. ** column must not be NULL.
  83229. */
  83230. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  83231. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  83232. return;
  83233. }
  83234. if( pNew->pIndex ){
  83235. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  83236. return;
  83237. }
  83238. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  83239. sqlite3ErrorMsg(pParse,
  83240. "Cannot add a REFERENCES column with non-NULL default value");
  83241. return;
  83242. }
  83243. if( pCol->notNull && !pDflt ){
  83244. sqlite3ErrorMsg(pParse,
  83245. "Cannot add a NOT NULL column with default value NULL");
  83246. return;
  83247. }
  83248. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  83249. ** can handle (i.e. not CURRENT_TIME etc.)
  83250. */
  83251. if( pDflt ){
  83252. sqlite3_value *pVal = 0;
  83253. int rc;
  83254. rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
  83255. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  83256. if( rc!=SQLITE_OK ){
  83257. db->mallocFailed = 1;
  83258. return;
  83259. }
  83260. if( !pVal ){
  83261. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  83262. return;
  83263. }
  83264. sqlite3ValueFree(pVal);
  83265. }
  83266. /* Modify the CREATE TABLE statement. */
  83267. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  83268. if( zCol ){
  83269. char *zEnd = &zCol[pColDef->n-1];
  83270. int savedDbFlags = db->flags;
  83271. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  83272. *zEnd-- = '\0';
  83273. }
  83274. db->flags |= SQLITE_PreferBuiltin;
  83275. sqlite3NestedParse(pParse,
  83276. "UPDATE \"%w\".%s SET "
  83277. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  83278. "WHERE type = 'table' AND name = %Q",
  83279. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  83280. zTab
  83281. );
  83282. sqlite3DbFree(db, zCol);
  83283. db->flags = savedDbFlags;
  83284. }
  83285. /* If the default value of the new column is NULL, then set the file
  83286. ** format to 2. If the default value of the new column is not NULL,
  83287. ** the file format becomes 3.
  83288. */
  83289. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  83290. /* Reload the schema of the modified table. */
  83291. reloadTableSchema(pParse, pTab, pTab->zName);
  83292. }
  83293. /*
  83294. ** This function is called by the parser after the table-name in
  83295. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  83296. ** pSrc is the full-name of the table being altered.
  83297. **
  83298. ** This routine makes a (partial) copy of the Table structure
  83299. ** for the table being altered and sets Parse.pNewTable to point
  83300. ** to it. Routines called by the parser as the column definition
  83301. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  83302. ** the copy. The copy of the Table structure is deleted by tokenize.c
  83303. ** after parsing is finished.
  83304. **
  83305. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  83306. ** coding the "ALTER TABLE ... ADD" statement.
  83307. */
  83308. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  83309. Table *pNew;
  83310. Table *pTab;
  83311. Vdbe *v;
  83312. int iDb;
  83313. int i;
  83314. int nAlloc;
  83315. sqlite3 *db = pParse->db;
  83316. /* Look up the table being altered. */
  83317. assert( pParse->pNewTable==0 );
  83318. assert( sqlite3BtreeHoldsAllMutexes(db) );
  83319. if( db->mallocFailed ) goto exit_begin_add_column;
  83320. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  83321. if( !pTab ) goto exit_begin_add_column;
  83322. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83323. if( IsVirtual(pTab) ){
  83324. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  83325. goto exit_begin_add_column;
  83326. }
  83327. #endif
  83328. /* Make sure this is not an attempt to ALTER a view. */
  83329. if( pTab->pSelect ){
  83330. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  83331. goto exit_begin_add_column;
  83332. }
  83333. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  83334. goto exit_begin_add_column;
  83335. }
  83336. assert( pTab->addColOffset>0 );
  83337. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83338. /* Put a copy of the Table struct in Parse.pNewTable for the
  83339. ** sqlite3AddColumn() function and friends to modify. But modify
  83340. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  83341. ** prefix, we insure that the name will not collide with an existing
  83342. ** table because user table are not allowed to have the "sqlite_"
  83343. ** prefix on their name.
  83344. */
  83345. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  83346. if( !pNew ) goto exit_begin_add_column;
  83347. pParse->pNewTable = pNew;
  83348. pNew->nRef = 1;
  83349. pNew->nCol = pTab->nCol;
  83350. assert( pNew->nCol>0 );
  83351. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  83352. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  83353. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  83354. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  83355. if( !pNew->aCol || !pNew->zName ){
  83356. db->mallocFailed = 1;
  83357. goto exit_begin_add_column;
  83358. }
  83359. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  83360. for(i=0; i<pNew->nCol; i++){
  83361. Column *pCol = &pNew->aCol[i];
  83362. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  83363. pCol->zColl = 0;
  83364. pCol->zType = 0;
  83365. pCol->pDflt = 0;
  83366. pCol->zDflt = 0;
  83367. }
  83368. pNew->pSchema = db->aDb[iDb].pSchema;
  83369. pNew->addColOffset = pTab->addColOffset;
  83370. pNew->nRef = 1;
  83371. /* Begin a transaction and increment the schema cookie. */
  83372. sqlite3BeginWriteOperation(pParse, 0, iDb);
  83373. v = sqlite3GetVdbe(pParse);
  83374. if( !v ) goto exit_begin_add_column;
  83375. sqlite3ChangeCookie(pParse, iDb);
  83376. exit_begin_add_column:
  83377. sqlite3SrcListDelete(db, pSrc);
  83378. return;
  83379. }
  83380. #endif /* SQLITE_ALTER_TABLE */
  83381. /************** End of alter.c ***********************************************/
  83382. /************** Begin file analyze.c *****************************************/
  83383. /*
  83384. ** 2005-07-08
  83385. **
  83386. ** The author disclaims copyright to this source code. In place of
  83387. ** a legal notice, here is a blessing:
  83388. **
  83389. ** May you do good and not evil.
  83390. ** May you find forgiveness for yourself and forgive others.
  83391. ** May you share freely, never taking more than you give.
  83392. **
  83393. *************************************************************************
  83394. ** This file contains code associated with the ANALYZE command.
  83395. **
  83396. ** The ANALYZE command gather statistics about the content of tables
  83397. ** and indices. These statistics are made available to the query planner
  83398. ** to help it make better decisions about how to perform queries.
  83399. **
  83400. ** The following system tables are or have been supported:
  83401. **
  83402. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  83403. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  83404. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  83405. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  83406. **
  83407. ** Additional tables might be added in future releases of SQLite.
  83408. ** The sqlite_stat2 table is not created or used unless the SQLite version
  83409. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  83410. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  83411. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  83412. ** created and used by SQLite versions 3.7.9 and later and with
  83413. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  83414. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  83415. ** version of sqlite_stat3 and is only available when compiled with
  83416. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  83417. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  83418. ** are both enabled, then STAT4 takes precedence.
  83419. **
  83420. ** For most applications, sqlite_stat1 provides all the statistics required
  83421. ** for the query planner to make good choices.
  83422. **
  83423. ** Format of sqlite_stat1:
  83424. **
  83425. ** There is normally one row per index, with the index identified by the
  83426. ** name in the idx column. The tbl column is the name of the table to
  83427. ** which the index belongs. In each such row, the stat column will be
  83428. ** a string consisting of a list of integers. The first integer in this
  83429. ** list is the number of rows in the index. (This is the same as the
  83430. ** number of rows in the table, except for partial indices.) The second
  83431. ** integer is the average number of rows in the index that have the same
  83432. ** value in the first column of the index. The third integer is the average
  83433. ** number of rows in the index that have the same value for the first two
  83434. ** columns. The N-th integer (for N>1) is the average number of rows in
  83435. ** the index which have the same value for the first N-1 columns. For
  83436. ** a K-column index, there will be K+1 integers in the stat column. If
  83437. ** the index is unique, then the last integer will be 1.
  83438. **
  83439. ** The list of integers in the stat column can optionally be followed
  83440. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  83441. ** must be separated from the last integer by a single space. If the
  83442. ** "unordered" keyword is present, then the query planner assumes that
  83443. ** the index is unordered and will not use the index for a range query.
  83444. **
  83445. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  83446. ** column contains a single integer which is the (estimated) number of
  83447. ** rows in the table identified by sqlite_stat1.tbl.
  83448. **
  83449. ** Format of sqlite_stat2:
  83450. **
  83451. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  83452. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  83453. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  83454. ** about the distribution of keys within an index. The index is identified by
  83455. ** the "idx" column and the "tbl" column is the name of the table to which
  83456. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  83457. ** table for each index.
  83458. **
  83459. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  83460. ** inclusive are samples of the left-most key value in the index taken at
  83461. ** evenly spaced points along the index. Let the number of samples be S
  83462. ** (10 in the standard build) and let C be the number of rows in the index.
  83463. ** Then the sampled rows are given by:
  83464. **
  83465. ** rownumber = (i*C*2 + C)/(S*2)
  83466. **
  83467. ** For i between 0 and S-1. Conceptually, the index space is divided into
  83468. ** S uniform buckets and the samples are the middle row from each bucket.
  83469. **
  83470. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  83471. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  83472. ** writes the sqlite_stat2 table. This version of SQLite only supports
  83473. ** sqlite_stat3.
  83474. **
  83475. ** Format for sqlite_stat3:
  83476. **
  83477. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  83478. ** sqlite_stat4 format will be described first. Further information
  83479. ** about sqlite_stat3 follows the sqlite_stat4 description.
  83480. **
  83481. ** Format for sqlite_stat4:
  83482. **
  83483. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  83484. ** to aid the query planner in choosing good indices based on the values
  83485. ** that indexed columns are compared against in the WHERE clauses of
  83486. ** queries.
  83487. **
  83488. ** The sqlite_stat4 table contains multiple entries for each index.
  83489. ** The idx column names the index and the tbl column is the table of the
  83490. ** index. If the idx and tbl columns are the same, then the sample is
  83491. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  83492. ** binary encoding of a key from the index. The nEq column is a
  83493. ** list of integers. The first integer is the approximate number
  83494. ** of entries in the index whose left-most column exactly matches
  83495. ** the left-most column of the sample. The second integer in nEq
  83496. ** is the approximate number of entries in the index where the
  83497. ** first two columns match the first two columns of the sample.
  83498. ** And so forth. nLt is another list of integers that show the approximate
  83499. ** number of entries that are strictly less than the sample. The first
  83500. ** integer in nLt contains the number of entries in the index where the
  83501. ** left-most column is less than the left-most column of the sample.
  83502. ** The K-th integer in the nLt entry is the number of index entries
  83503. ** where the first K columns are less than the first K columns of the
  83504. ** sample. The nDLt column is like nLt except that it contains the
  83505. ** number of distinct entries in the index that are less than the
  83506. ** sample.
  83507. **
  83508. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  83509. ** The ANALYZE command will typically generate sqlite_stat4 tables
  83510. ** that contain between 10 and 40 samples which are distributed across
  83511. ** the key space, though not uniformly, and which include samples with
  83512. ** large nEq values.
  83513. **
  83514. ** Format for sqlite_stat3 redux:
  83515. **
  83516. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  83517. ** looks at the left-most column of the index. The sqlite_stat3.sample
  83518. ** column contains the actual value of the left-most column instead
  83519. ** of a blob encoding of the complete index key as is found in
  83520. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  83521. ** all contain just a single integer which is the same as the first
  83522. ** integer in the equivalent columns in sqlite_stat4.
  83523. */
  83524. #ifndef SQLITE_OMIT_ANALYZE
  83525. /* #include "sqliteInt.h" */
  83526. #if defined(SQLITE_ENABLE_STAT4)
  83527. # define IsStat4 1
  83528. # define IsStat3 0
  83529. #elif defined(SQLITE_ENABLE_STAT3)
  83530. # define IsStat4 0
  83531. # define IsStat3 1
  83532. #else
  83533. # define IsStat4 0
  83534. # define IsStat3 0
  83535. # undef SQLITE_STAT4_SAMPLES
  83536. # define SQLITE_STAT4_SAMPLES 1
  83537. #endif
  83538. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  83539. /*
  83540. ** This routine generates code that opens the sqlite_statN tables.
  83541. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  83542. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  83543. ** appropriate compile-time options are provided.
  83544. **
  83545. ** If the sqlite_statN tables do not previously exist, it is created.
  83546. **
  83547. ** Argument zWhere may be a pointer to a buffer containing a table name,
  83548. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  83549. ** the sqlite_statN tables associated with the named table are deleted.
  83550. ** If zWhere==0, then code is generated to delete all stat table entries.
  83551. */
  83552. static void openStatTable(
  83553. Parse *pParse, /* Parsing context */
  83554. int iDb, /* The database we are looking in */
  83555. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  83556. const char *zWhere, /* Delete entries for this table or index */
  83557. const char *zWhereType /* Either "tbl" or "idx" */
  83558. ){
  83559. static const struct {
  83560. const char *zName;
  83561. const char *zCols;
  83562. } aTable[] = {
  83563. { "sqlite_stat1", "tbl,idx,stat" },
  83564. #if defined(SQLITE_ENABLE_STAT4)
  83565. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  83566. { "sqlite_stat3", 0 },
  83567. #elif defined(SQLITE_ENABLE_STAT3)
  83568. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  83569. { "sqlite_stat4", 0 },
  83570. #else
  83571. { "sqlite_stat3", 0 },
  83572. { "sqlite_stat4", 0 },
  83573. #endif
  83574. };
  83575. int i;
  83576. sqlite3 *db = pParse->db;
  83577. Db *pDb;
  83578. Vdbe *v = sqlite3GetVdbe(pParse);
  83579. int aRoot[ArraySize(aTable)];
  83580. u8 aCreateTbl[ArraySize(aTable)];
  83581. if( v==0 ) return;
  83582. assert( sqlite3BtreeHoldsAllMutexes(db) );
  83583. assert( sqlite3VdbeDb(v)==db );
  83584. pDb = &db->aDb[iDb];
  83585. /* Create new statistic tables if they do not exist, or clear them
  83586. ** if they do already exist.
  83587. */
  83588. for(i=0; i<ArraySize(aTable); i++){
  83589. const char *zTab = aTable[i].zName;
  83590. Table *pStat;
  83591. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  83592. if( aTable[i].zCols ){
  83593. /* The sqlite_statN table does not exist. Create it. Note that a
  83594. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  83595. ** of the new table in register pParse->regRoot. This is important
  83596. ** because the OpenWrite opcode below will be needing it. */
  83597. sqlite3NestedParse(pParse,
  83598. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  83599. );
  83600. aRoot[i] = pParse->regRoot;
  83601. aCreateTbl[i] = OPFLAG_P2ISREG;
  83602. }
  83603. }else{
  83604. /* The table already exists. If zWhere is not NULL, delete all entries
  83605. ** associated with the table zWhere. If zWhere is NULL, delete the
  83606. ** entire contents of the table. */
  83607. aRoot[i] = pStat->tnum;
  83608. aCreateTbl[i] = 0;
  83609. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  83610. if( zWhere ){
  83611. sqlite3NestedParse(pParse,
  83612. "DELETE FROM %Q.%s WHERE %s=%Q",
  83613. pDb->zName, zTab, zWhereType, zWhere
  83614. );
  83615. }else{
  83616. /* The sqlite_stat[134] table already exists. Delete all rows. */
  83617. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  83618. }
  83619. }
  83620. }
  83621. /* Open the sqlite_stat[134] tables for writing. */
  83622. for(i=0; aTable[i].zCols; i++){
  83623. assert( i<ArraySize(aTable) );
  83624. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  83625. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  83626. VdbeComment((v, aTable[i].zName));
  83627. }
  83628. }
  83629. /*
  83630. ** Recommended number of samples for sqlite_stat4
  83631. */
  83632. #ifndef SQLITE_STAT4_SAMPLES
  83633. # define SQLITE_STAT4_SAMPLES 24
  83634. #endif
  83635. /*
  83636. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  83637. ** share an instance of the following structure to hold their state
  83638. ** information.
  83639. */
  83640. typedef struct Stat4Accum Stat4Accum;
  83641. typedef struct Stat4Sample Stat4Sample;
  83642. struct Stat4Sample {
  83643. tRowcnt *anEq; /* sqlite_stat4.nEq */
  83644. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  83645. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83646. tRowcnt *anLt; /* sqlite_stat4.nLt */
  83647. union {
  83648. i64 iRowid; /* Rowid in main table of the key */
  83649. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  83650. } u;
  83651. u32 nRowid; /* Sizeof aRowid[] */
  83652. u8 isPSample; /* True if a periodic sample */
  83653. int iCol; /* If !isPSample, the reason for inclusion */
  83654. u32 iHash; /* Tiebreaker hash */
  83655. #endif
  83656. };
  83657. struct Stat4Accum {
  83658. tRowcnt nRow; /* Number of rows in the entire table */
  83659. tRowcnt nPSample; /* How often to do a periodic sample */
  83660. int nCol; /* Number of columns in index + pk/rowid */
  83661. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  83662. int mxSample; /* Maximum number of samples to accumulate */
  83663. Stat4Sample current; /* Current row as a Stat4Sample */
  83664. u32 iPrn; /* Pseudo-random number used for sampling */
  83665. Stat4Sample *aBest; /* Array of nCol best samples */
  83666. int iMin; /* Index in a[] of entry with minimum score */
  83667. int nSample; /* Current number of samples */
  83668. int iGet; /* Index of current sample accessed by stat_get() */
  83669. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  83670. sqlite3 *db; /* Database connection, for malloc() */
  83671. };
  83672. /* Reclaim memory used by a Stat4Sample
  83673. */
  83674. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83675. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  83676. assert( db!=0 );
  83677. if( p->nRowid ){
  83678. sqlite3DbFree(db, p->u.aRowid);
  83679. p->nRowid = 0;
  83680. }
  83681. }
  83682. #endif
  83683. /* Initialize the BLOB value of a ROWID
  83684. */
  83685. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83686. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  83687. assert( db!=0 );
  83688. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  83689. p->u.aRowid = sqlite3DbMallocRaw(db, n);
  83690. if( p->u.aRowid ){
  83691. p->nRowid = n;
  83692. memcpy(p->u.aRowid, pData, n);
  83693. }else{
  83694. p->nRowid = 0;
  83695. }
  83696. }
  83697. #endif
  83698. /* Initialize the INTEGER value of a ROWID.
  83699. */
  83700. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83701. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  83702. assert( db!=0 );
  83703. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  83704. p->nRowid = 0;
  83705. p->u.iRowid = iRowid;
  83706. }
  83707. #endif
  83708. /*
  83709. ** Copy the contents of object (*pFrom) into (*pTo).
  83710. */
  83711. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83712. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  83713. pTo->isPSample = pFrom->isPSample;
  83714. pTo->iCol = pFrom->iCol;
  83715. pTo->iHash = pFrom->iHash;
  83716. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  83717. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  83718. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  83719. if( pFrom->nRowid ){
  83720. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  83721. }else{
  83722. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  83723. }
  83724. }
  83725. #endif
  83726. /*
  83727. ** Reclaim all memory of a Stat4Accum structure.
  83728. */
  83729. static void stat4Destructor(void *pOld){
  83730. Stat4Accum *p = (Stat4Accum*)pOld;
  83731. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83732. int i;
  83733. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  83734. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  83735. sampleClear(p->db, &p->current);
  83736. #endif
  83737. sqlite3DbFree(p->db, p);
  83738. }
  83739. /*
  83740. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  83741. ** are:
  83742. ** N: The number of columns in the index including the rowid/pk (note 1)
  83743. ** K: The number of columns in the index excluding the rowid/pk.
  83744. ** C: The number of rows in the index (note 2)
  83745. **
  83746. ** Note 1: In the special case of the covering index that implements a
  83747. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  83748. ** total number of columns in the table.
  83749. **
  83750. ** Note 2: C is only used for STAT3 and STAT4.
  83751. **
  83752. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  83753. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  83754. ** PRIMARY KEY of the table. The covering index that implements the
  83755. ** original WITHOUT ROWID table as N==K as a special case.
  83756. **
  83757. ** This routine allocates the Stat4Accum object in heap memory. The return
  83758. ** value is a pointer to the Stat4Accum object. The datatype of the
  83759. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  83760. ** object.
  83761. */
  83762. static void statInit(
  83763. sqlite3_context *context,
  83764. int argc,
  83765. sqlite3_value **argv
  83766. ){
  83767. Stat4Accum *p;
  83768. int nCol; /* Number of columns in index being sampled */
  83769. int nKeyCol; /* Number of key columns */
  83770. int nColUp; /* nCol rounded up for alignment */
  83771. int n; /* Bytes of space to allocate */
  83772. sqlite3 *db; /* Database connection */
  83773. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83774. int mxSample = SQLITE_STAT4_SAMPLES;
  83775. #endif
  83776. /* Decode the three function arguments */
  83777. UNUSED_PARAMETER(argc);
  83778. nCol = sqlite3_value_int(argv[0]);
  83779. assert( nCol>0 );
  83780. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  83781. nKeyCol = sqlite3_value_int(argv[1]);
  83782. assert( nKeyCol<=nCol );
  83783. assert( nKeyCol>0 );
  83784. /* Allocate the space required for the Stat4Accum object */
  83785. n = sizeof(*p)
  83786. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  83787. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  83788. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83789. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  83790. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  83791. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  83792. #endif
  83793. ;
  83794. db = sqlite3_context_db_handle(context);
  83795. p = sqlite3DbMallocZero(db, n);
  83796. if( p==0 ){
  83797. sqlite3_result_error_nomem(context);
  83798. return;
  83799. }
  83800. p->db = db;
  83801. p->nRow = 0;
  83802. p->nCol = nCol;
  83803. p->nKeyCol = nKeyCol;
  83804. p->current.anDLt = (tRowcnt*)&p[1];
  83805. p->current.anEq = &p->current.anDLt[nColUp];
  83806. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83807. {
  83808. u8 *pSpace; /* Allocated space not yet assigned */
  83809. int i; /* Used to iterate through p->aSample[] */
  83810. p->iGet = -1;
  83811. p->mxSample = mxSample;
  83812. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  83813. p->current.anLt = &p->current.anEq[nColUp];
  83814. p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
  83815. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  83816. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  83817. p->aBest = &p->a[mxSample];
  83818. pSpace = (u8*)(&p->a[mxSample+nCol]);
  83819. for(i=0; i<(mxSample+nCol); i++){
  83820. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  83821. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  83822. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  83823. }
  83824. assert( (pSpace - (u8*)p)==n );
  83825. for(i=0; i<nCol; i++){
  83826. p->aBest[i].iCol = i;
  83827. }
  83828. }
  83829. #endif
  83830. /* Return a pointer to the allocated object to the caller. Note that
  83831. ** only the pointer (the 2nd parameter) matters. The size of the object
  83832. ** (given by the 3rd parameter) is never used and can be any positive
  83833. ** value. */
  83834. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  83835. }
  83836. static const FuncDef statInitFuncdef = {
  83837. 2+IsStat34, /* nArg */
  83838. SQLITE_UTF8, /* funcFlags */
  83839. 0, /* pUserData */
  83840. 0, /* pNext */
  83841. statInit, /* xFunc */
  83842. 0, /* xStep */
  83843. 0, /* xFinalize */
  83844. "stat_init", /* zName */
  83845. 0, /* pHash */
  83846. 0 /* pDestructor */
  83847. };
  83848. #ifdef SQLITE_ENABLE_STAT4
  83849. /*
  83850. ** pNew and pOld are both candidate non-periodic samples selected for
  83851. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  83852. ** considering only any trailing columns and the sample hash value, this
  83853. ** function returns true if sample pNew is to be preferred over pOld.
  83854. ** In other words, if we assume that the cardinalities of the selected
  83855. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  83856. **
  83857. ** This function assumes that for each argument sample, the contents of
  83858. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  83859. */
  83860. static int sampleIsBetterPost(
  83861. Stat4Accum *pAccum,
  83862. Stat4Sample *pNew,
  83863. Stat4Sample *pOld
  83864. ){
  83865. int nCol = pAccum->nCol;
  83866. int i;
  83867. assert( pNew->iCol==pOld->iCol );
  83868. for(i=pNew->iCol+1; i<nCol; i++){
  83869. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  83870. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  83871. }
  83872. if( pNew->iHash>pOld->iHash ) return 1;
  83873. return 0;
  83874. }
  83875. #endif
  83876. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83877. /*
  83878. ** Return true if pNew is to be preferred over pOld.
  83879. **
  83880. ** This function assumes that for each argument sample, the contents of
  83881. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  83882. */
  83883. static int sampleIsBetter(
  83884. Stat4Accum *pAccum,
  83885. Stat4Sample *pNew,
  83886. Stat4Sample *pOld
  83887. ){
  83888. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  83889. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  83890. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  83891. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  83892. if( (nEqNew>nEqOld) ) return 1;
  83893. #ifdef SQLITE_ENABLE_STAT4
  83894. if( nEqNew==nEqOld ){
  83895. if( pNew->iCol<pOld->iCol ) return 1;
  83896. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  83897. }
  83898. return 0;
  83899. #else
  83900. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  83901. #endif
  83902. }
  83903. /*
  83904. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  83905. ** remove the least desirable sample from p->a[] to make room.
  83906. */
  83907. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  83908. Stat4Sample *pSample = 0;
  83909. int i;
  83910. assert( IsStat4 || nEqZero==0 );
  83911. #ifdef SQLITE_ENABLE_STAT4
  83912. if( pNew->isPSample==0 ){
  83913. Stat4Sample *pUpgrade = 0;
  83914. assert( pNew->anEq[pNew->iCol]>0 );
  83915. /* This sample is being added because the prefix that ends in column
  83916. ** iCol occurs many times in the table. However, if we have already
  83917. ** added a sample that shares this prefix, there is no need to add
  83918. ** this one. Instead, upgrade the priority of the highest priority
  83919. ** existing sample that shares this prefix. */
  83920. for(i=p->nSample-1; i>=0; i--){
  83921. Stat4Sample *pOld = &p->a[i];
  83922. if( pOld->anEq[pNew->iCol]==0 ){
  83923. if( pOld->isPSample ) return;
  83924. assert( pOld->iCol>pNew->iCol );
  83925. assert( sampleIsBetter(p, pNew, pOld) );
  83926. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  83927. pUpgrade = pOld;
  83928. }
  83929. }
  83930. }
  83931. if( pUpgrade ){
  83932. pUpgrade->iCol = pNew->iCol;
  83933. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  83934. goto find_new_min;
  83935. }
  83936. }
  83937. #endif
  83938. /* If necessary, remove sample iMin to make room for the new sample. */
  83939. if( p->nSample>=p->mxSample ){
  83940. Stat4Sample *pMin = &p->a[p->iMin];
  83941. tRowcnt *anEq = pMin->anEq;
  83942. tRowcnt *anLt = pMin->anLt;
  83943. tRowcnt *anDLt = pMin->anDLt;
  83944. sampleClear(p->db, pMin);
  83945. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  83946. pSample = &p->a[p->nSample-1];
  83947. pSample->nRowid = 0;
  83948. pSample->anEq = anEq;
  83949. pSample->anDLt = anDLt;
  83950. pSample->anLt = anLt;
  83951. p->nSample = p->mxSample-1;
  83952. }
  83953. /* The "rows less-than" for the rowid column must be greater than that
  83954. ** for the last sample in the p->a[] array. Otherwise, the samples would
  83955. ** be out of order. */
  83956. #ifdef SQLITE_ENABLE_STAT4
  83957. assert( p->nSample==0
  83958. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  83959. #endif
  83960. /* Insert the new sample */
  83961. pSample = &p->a[p->nSample];
  83962. sampleCopy(p, pSample, pNew);
  83963. p->nSample++;
  83964. /* Zero the first nEqZero entries in the anEq[] array. */
  83965. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  83966. #ifdef SQLITE_ENABLE_STAT4
  83967. find_new_min:
  83968. #endif
  83969. if( p->nSample>=p->mxSample ){
  83970. int iMin = -1;
  83971. for(i=0; i<p->mxSample; i++){
  83972. if( p->a[i].isPSample ) continue;
  83973. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  83974. iMin = i;
  83975. }
  83976. }
  83977. assert( iMin>=0 );
  83978. p->iMin = iMin;
  83979. }
  83980. }
  83981. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  83982. /*
  83983. ** Field iChng of the index being scanned has changed. So at this point
  83984. ** p->current contains a sample that reflects the previous row of the
  83985. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  83986. ** correct at this point.
  83987. */
  83988. static void samplePushPrevious(Stat4Accum *p, int iChng){
  83989. #ifdef SQLITE_ENABLE_STAT4
  83990. int i;
  83991. /* Check if any samples from the aBest[] array should be pushed
  83992. ** into IndexSample.a[] at this point. */
  83993. for(i=(p->nCol-2); i>=iChng; i--){
  83994. Stat4Sample *pBest = &p->aBest[i];
  83995. pBest->anEq[i] = p->current.anEq[i];
  83996. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  83997. sampleInsert(p, pBest, i);
  83998. }
  83999. }
  84000. /* Update the anEq[] fields of any samples already collected. */
  84001. for(i=p->nSample-1; i>=0; i--){
  84002. int j;
  84003. for(j=iChng; j<p->nCol; j++){
  84004. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  84005. }
  84006. }
  84007. #endif
  84008. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  84009. if( iChng==0 ){
  84010. tRowcnt nLt = p->current.anLt[0];
  84011. tRowcnt nEq = p->current.anEq[0];
  84012. /* Check if this is to be a periodic sample. If so, add it. */
  84013. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  84014. p->current.isPSample = 1;
  84015. sampleInsert(p, &p->current, 0);
  84016. p->current.isPSample = 0;
  84017. }else
  84018. /* Or if it is a non-periodic sample. Add it in this case too. */
  84019. if( p->nSample<p->mxSample
  84020. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  84021. ){
  84022. sampleInsert(p, &p->current, 0);
  84023. }
  84024. }
  84025. #endif
  84026. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  84027. UNUSED_PARAMETER( p );
  84028. UNUSED_PARAMETER( iChng );
  84029. #endif
  84030. }
  84031. /*
  84032. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  84033. ** Arguments:
  84034. **
  84035. ** P Pointer to the Stat4Accum object created by stat_init()
  84036. ** C Index of left-most column to differ from previous row
  84037. ** R Rowid for the current row. Might be a key record for
  84038. ** WITHOUT ROWID tables.
  84039. **
  84040. ** This SQL function always returns NULL. It's purpose it to accumulate
  84041. ** statistical data and/or samples in the Stat4Accum object about the
  84042. ** index being analyzed. The stat_get() SQL function will later be used to
  84043. ** extract relevant information for constructing the sqlite_statN tables.
  84044. **
  84045. ** The R parameter is only used for STAT3 and STAT4
  84046. */
  84047. static void statPush(
  84048. sqlite3_context *context,
  84049. int argc,
  84050. sqlite3_value **argv
  84051. ){
  84052. int i;
  84053. /* The three function arguments */
  84054. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  84055. int iChng = sqlite3_value_int(argv[1]);
  84056. UNUSED_PARAMETER( argc );
  84057. UNUSED_PARAMETER( context );
  84058. assert( p->nCol>0 );
  84059. assert( iChng<p->nCol );
  84060. if( p->nRow==0 ){
  84061. /* This is the first call to this function. Do initialization. */
  84062. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  84063. }else{
  84064. /* Second and subsequent calls get processed here */
  84065. samplePushPrevious(p, iChng);
  84066. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  84067. ** to the current row of the index. */
  84068. for(i=0; i<iChng; i++){
  84069. p->current.anEq[i]++;
  84070. }
  84071. for(i=iChng; i<p->nCol; i++){
  84072. p->current.anDLt[i]++;
  84073. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84074. p->current.anLt[i] += p->current.anEq[i];
  84075. #endif
  84076. p->current.anEq[i] = 1;
  84077. }
  84078. }
  84079. p->nRow++;
  84080. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84081. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  84082. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  84083. }else{
  84084. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  84085. sqlite3_value_blob(argv[2]));
  84086. }
  84087. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  84088. #endif
  84089. #ifdef SQLITE_ENABLE_STAT4
  84090. {
  84091. tRowcnt nLt = p->current.anLt[p->nCol-1];
  84092. /* Check if this is to be a periodic sample. If so, add it. */
  84093. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  84094. p->current.isPSample = 1;
  84095. p->current.iCol = 0;
  84096. sampleInsert(p, &p->current, p->nCol-1);
  84097. p->current.isPSample = 0;
  84098. }
  84099. /* Update the aBest[] array. */
  84100. for(i=0; i<(p->nCol-1); i++){
  84101. p->current.iCol = i;
  84102. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  84103. sampleCopy(p, &p->aBest[i], &p->current);
  84104. }
  84105. }
  84106. }
  84107. #endif
  84108. }
  84109. static const FuncDef statPushFuncdef = {
  84110. 2+IsStat34, /* nArg */
  84111. SQLITE_UTF8, /* funcFlags */
  84112. 0, /* pUserData */
  84113. 0, /* pNext */
  84114. statPush, /* xFunc */
  84115. 0, /* xStep */
  84116. 0, /* xFinalize */
  84117. "stat_push", /* zName */
  84118. 0, /* pHash */
  84119. 0 /* pDestructor */
  84120. };
  84121. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  84122. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  84123. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  84124. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  84125. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  84126. /*
  84127. ** Implementation of the stat_get(P,J) SQL function. This routine is
  84128. ** used to query statistical information that has been gathered into
  84129. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  84130. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  84131. ** The content to returned is determined by the parameter J
  84132. ** which is one of the STAT_GET_xxxx values defined above.
  84133. **
  84134. ** If neither STAT3 nor STAT4 are enabled, then J is always
  84135. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  84136. ** a one-parameter function, stat_get(P), that always returns the
  84137. ** stat1 table entry information.
  84138. */
  84139. static void statGet(
  84140. sqlite3_context *context,
  84141. int argc,
  84142. sqlite3_value **argv
  84143. ){
  84144. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  84145. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84146. /* STAT3 and STAT4 have a parameter on this routine. */
  84147. int eCall = sqlite3_value_int(argv[1]);
  84148. assert( argc==2 );
  84149. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  84150. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  84151. || eCall==STAT_GET_NDLT
  84152. );
  84153. if( eCall==STAT_GET_STAT1 )
  84154. #else
  84155. assert( argc==1 );
  84156. #endif
  84157. {
  84158. /* Return the value to store in the "stat" column of the sqlite_stat1
  84159. ** table for this index.
  84160. **
  84161. ** The value is a string composed of a list of integers describing
  84162. ** the index. The first integer in the list is the total number of
  84163. ** entries in the index. There is one additional integer in the list
  84164. ** for each indexed column. This additional integer is an estimate of
  84165. ** the number of rows matched by a stabbing query on the index using
  84166. ** a key with the corresponding number of fields. In other words,
  84167. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  84168. ** "100 10 2", then SQLite estimates that:
  84169. **
  84170. ** * the index contains 100 rows,
  84171. ** * "WHERE a=?" matches 10 rows, and
  84172. ** * "WHERE a=? AND b=?" matches 2 rows.
  84173. **
  84174. ** If D is the count of distinct values and K is the total number of
  84175. ** rows, then each estimate is computed as:
  84176. **
  84177. ** I = (K+D-1)/D
  84178. */
  84179. char *z;
  84180. int i;
  84181. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  84182. if( zRet==0 ){
  84183. sqlite3_result_error_nomem(context);
  84184. return;
  84185. }
  84186. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  84187. z = zRet + sqlite3Strlen30(zRet);
  84188. for(i=0; i<p->nKeyCol; i++){
  84189. u64 nDistinct = p->current.anDLt[i] + 1;
  84190. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  84191. sqlite3_snprintf(24, z, " %llu", iVal);
  84192. z += sqlite3Strlen30(z);
  84193. assert( p->current.anEq[i] );
  84194. }
  84195. assert( z[0]=='\0' && z>zRet );
  84196. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  84197. }
  84198. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84199. else if( eCall==STAT_GET_ROWID ){
  84200. if( p->iGet<0 ){
  84201. samplePushPrevious(p, 0);
  84202. p->iGet = 0;
  84203. }
  84204. if( p->iGet<p->nSample ){
  84205. Stat4Sample *pS = p->a + p->iGet;
  84206. if( pS->nRowid==0 ){
  84207. sqlite3_result_int64(context, pS->u.iRowid);
  84208. }else{
  84209. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  84210. SQLITE_TRANSIENT);
  84211. }
  84212. }
  84213. }else{
  84214. tRowcnt *aCnt = 0;
  84215. assert( p->iGet<p->nSample );
  84216. switch( eCall ){
  84217. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  84218. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  84219. default: {
  84220. aCnt = p->a[p->iGet].anDLt;
  84221. p->iGet++;
  84222. break;
  84223. }
  84224. }
  84225. if( IsStat3 ){
  84226. sqlite3_result_int64(context, (i64)aCnt[0]);
  84227. }else{
  84228. char *zRet = sqlite3MallocZero(p->nCol * 25);
  84229. if( zRet==0 ){
  84230. sqlite3_result_error_nomem(context);
  84231. }else{
  84232. int i;
  84233. char *z = zRet;
  84234. for(i=0; i<p->nCol; i++){
  84235. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  84236. z += sqlite3Strlen30(z);
  84237. }
  84238. assert( z[0]=='\0' && z>zRet );
  84239. z[-1] = '\0';
  84240. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  84241. }
  84242. }
  84243. }
  84244. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  84245. #ifndef SQLITE_DEBUG
  84246. UNUSED_PARAMETER( argc );
  84247. #endif
  84248. }
  84249. static const FuncDef statGetFuncdef = {
  84250. 1+IsStat34, /* nArg */
  84251. SQLITE_UTF8, /* funcFlags */
  84252. 0, /* pUserData */
  84253. 0, /* pNext */
  84254. statGet, /* xFunc */
  84255. 0, /* xStep */
  84256. 0, /* xFinalize */
  84257. "stat_get", /* zName */
  84258. 0, /* pHash */
  84259. 0 /* pDestructor */
  84260. };
  84261. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  84262. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  84263. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84264. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  84265. #elif SQLITE_DEBUG
  84266. assert( iParam==STAT_GET_STAT1 );
  84267. #else
  84268. UNUSED_PARAMETER( iParam );
  84269. #endif
  84270. sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4, regOut);
  84271. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  84272. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  84273. }
  84274. /*
  84275. ** Generate code to do an analysis of all indices associated with
  84276. ** a single table.
  84277. */
  84278. static void analyzeOneTable(
  84279. Parse *pParse, /* Parser context */
  84280. Table *pTab, /* Table whose indices are to be analyzed */
  84281. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  84282. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  84283. int iMem, /* Available memory locations begin here */
  84284. int iTab /* Next available cursor */
  84285. ){
  84286. sqlite3 *db = pParse->db; /* Database handle */
  84287. Index *pIdx; /* An index to being analyzed */
  84288. int iIdxCur; /* Cursor open on index being analyzed */
  84289. int iTabCur; /* Table cursor */
  84290. Vdbe *v; /* The virtual machine being built up */
  84291. int i; /* Loop counter */
  84292. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  84293. int iDb; /* Index of database containing pTab */
  84294. u8 needTableCnt = 1; /* True to count the table */
  84295. int regNewRowid = iMem++; /* Rowid for the inserted record */
  84296. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  84297. int regChng = iMem++; /* Index of changed index field */
  84298. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84299. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  84300. #endif
  84301. int regTemp = iMem++; /* Temporary use register */
  84302. int regTabname = iMem++; /* Register containing table name */
  84303. int regIdxname = iMem++; /* Register containing index name */
  84304. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  84305. int regPrev = iMem; /* MUST BE LAST (see below) */
  84306. pParse->nMem = MAX(pParse->nMem, iMem);
  84307. v = sqlite3GetVdbe(pParse);
  84308. if( v==0 || NEVER(pTab==0) ){
  84309. return;
  84310. }
  84311. if( pTab->tnum==0 ){
  84312. /* Do not gather statistics on views or virtual tables */
  84313. return;
  84314. }
  84315. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  84316. /* Do not gather statistics on system tables */
  84317. return;
  84318. }
  84319. assert( sqlite3BtreeHoldsAllMutexes(db) );
  84320. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  84321. assert( iDb>=0 );
  84322. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84323. #ifndef SQLITE_OMIT_AUTHORIZATION
  84324. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  84325. db->aDb[iDb].zName ) ){
  84326. return;
  84327. }
  84328. #endif
  84329. /* Establish a read-lock on the table at the shared-cache level.
  84330. ** Open a read-only cursor on the table. Also allocate a cursor number
  84331. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  84332. ** this time though. */
  84333. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  84334. iTabCur = iTab++;
  84335. iIdxCur = iTab++;
  84336. pParse->nTab = MAX(pParse->nTab, iTab);
  84337. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  84338. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  84339. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  84340. int nCol; /* Number of columns in pIdx. "N" */
  84341. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  84342. int addrNextRow; /* Address of "next_row:" */
  84343. const char *zIdxName; /* Name of the index */
  84344. int nColTest; /* Number of columns to test for changes */
  84345. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  84346. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  84347. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  84348. nCol = pIdx->nKeyCol;
  84349. zIdxName = pTab->zName;
  84350. nColTest = nCol - 1;
  84351. }else{
  84352. nCol = pIdx->nColumn;
  84353. zIdxName = pIdx->zName;
  84354. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  84355. }
  84356. /* Populate the register containing the index name. */
  84357. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
  84358. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  84359. /*
  84360. ** Pseudo-code for loop that calls stat_push():
  84361. **
  84362. ** Rewind csr
  84363. ** if eof(csr) goto end_of_scan;
  84364. ** regChng = 0
  84365. ** goto chng_addr_0;
  84366. **
  84367. ** next_row:
  84368. ** regChng = 0
  84369. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  84370. ** regChng = 1
  84371. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  84372. ** ...
  84373. ** regChng = N
  84374. ** goto chng_addr_N
  84375. **
  84376. ** chng_addr_0:
  84377. ** regPrev(0) = idx(0)
  84378. ** chng_addr_1:
  84379. ** regPrev(1) = idx(1)
  84380. ** ...
  84381. **
  84382. ** endDistinctTest:
  84383. ** regRowid = idx(rowid)
  84384. ** stat_push(P, regChng, regRowid)
  84385. ** Next csr
  84386. ** if !eof(csr) goto next_row;
  84387. **
  84388. ** end_of_scan:
  84389. */
  84390. /* Make sure there are enough memory cells allocated to accommodate
  84391. ** the regPrev array and a trailing rowid (the rowid slot is required
  84392. ** when building a record to insert into the sample column of
  84393. ** the sqlite_stat4 table. */
  84394. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  84395. /* Open a read-only cursor on the index being analyzed. */
  84396. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  84397. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  84398. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  84399. VdbeComment((v, "%s", pIdx->zName));
  84400. /* Invoke the stat_init() function. The arguments are:
  84401. **
  84402. ** (1) the number of columns in the index including the rowid
  84403. ** (or for a WITHOUT ROWID table, the number of PK columns),
  84404. ** (2) the number of columns in the key without the rowid/pk
  84405. ** (3) the number of rows in the index,
  84406. **
  84407. **
  84408. ** The third argument is only used for STAT3 and STAT4
  84409. */
  84410. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84411. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  84412. #endif
  84413. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  84414. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  84415. sqlite3VdbeAddOp3(v, OP_Function0, 0, regStat4+1, regStat4);
  84416. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  84417. sqlite3VdbeChangeP5(v, 2+IsStat34);
  84418. /* Implementation of the following:
  84419. **
  84420. ** Rewind csr
  84421. ** if eof(csr) goto end_of_scan;
  84422. ** regChng = 0
  84423. ** goto next_push_0;
  84424. **
  84425. */
  84426. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  84427. VdbeCoverage(v);
  84428. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  84429. addrNextRow = sqlite3VdbeCurrentAddr(v);
  84430. if( nColTest>0 ){
  84431. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  84432. int *aGotoChng; /* Array of jump instruction addresses */
  84433. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
  84434. if( aGotoChng==0 ) continue;
  84435. /*
  84436. ** next_row:
  84437. ** regChng = 0
  84438. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  84439. ** regChng = 1
  84440. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  84441. ** ...
  84442. ** regChng = N
  84443. ** goto endDistinctTest
  84444. */
  84445. sqlite3VdbeAddOp0(v, OP_Goto);
  84446. addrNextRow = sqlite3VdbeCurrentAddr(v);
  84447. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  84448. /* For a single-column UNIQUE index, once we have found a non-NULL
  84449. ** row, we know that all the rest will be distinct, so skip
  84450. ** subsequent distinctness tests. */
  84451. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  84452. VdbeCoverage(v);
  84453. }
  84454. for(i=0; i<nColTest; i++){
  84455. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  84456. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  84457. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  84458. aGotoChng[i] =
  84459. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  84460. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  84461. VdbeCoverage(v);
  84462. }
  84463. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  84464. sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
  84465. /*
  84466. ** chng_addr_0:
  84467. ** regPrev(0) = idx(0)
  84468. ** chng_addr_1:
  84469. ** regPrev(1) = idx(1)
  84470. ** ...
  84471. */
  84472. sqlite3VdbeJumpHere(v, addrNextRow-1);
  84473. for(i=0; i<nColTest; i++){
  84474. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  84475. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  84476. }
  84477. sqlite3VdbeResolveLabel(v, endDistinctTest);
  84478. sqlite3DbFree(db, aGotoChng);
  84479. }
  84480. /*
  84481. ** chng_addr_N:
  84482. ** regRowid = idx(rowid) // STAT34 only
  84483. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  84484. ** Next csr
  84485. ** if !eof(csr) goto next_row;
  84486. */
  84487. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84488. assert( regRowid==(regStat4+2) );
  84489. if( HasRowid(pTab) ){
  84490. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  84491. }else{
  84492. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  84493. int j, k, regKey;
  84494. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  84495. for(j=0; j<pPk->nKeyCol; j++){
  84496. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  84497. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  84498. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  84499. }
  84500. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  84501. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  84502. }
  84503. #endif
  84504. assert( regChng==(regStat4+1) );
  84505. sqlite3VdbeAddOp3(v, OP_Function0, 1, regStat4, regTemp);
  84506. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  84507. sqlite3VdbeChangeP5(v, 2+IsStat34);
  84508. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  84509. /* Add the entry to the stat1 table. */
  84510. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  84511. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  84512. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  84513. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  84514. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  84515. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84516. /* Add the entries to the stat3 or stat4 table. */
  84517. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84518. {
  84519. int regEq = regStat1;
  84520. int regLt = regStat1+1;
  84521. int regDLt = regStat1+2;
  84522. int regSample = regStat1+3;
  84523. int regCol = regStat1+4;
  84524. int regSampleRowid = regCol + nCol;
  84525. int addrNext;
  84526. int addrIsNull;
  84527. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  84528. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  84529. addrNext = sqlite3VdbeCurrentAddr(v);
  84530. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  84531. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  84532. VdbeCoverage(v);
  84533. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  84534. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  84535. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  84536. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  84537. /* We know that the regSampleRowid row exists because it was read by
  84538. ** the previous loop. Thus the not-found jump of seekOp will never
  84539. ** be taken */
  84540. VdbeCoverageNeverTaken(v);
  84541. #ifdef SQLITE_ENABLE_STAT3
  84542. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  84543. pIdx->aiColumn[0], regSample);
  84544. #else
  84545. for(i=0; i<nCol; i++){
  84546. i16 iCol = pIdx->aiColumn[i];
  84547. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  84548. }
  84549. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  84550. #endif
  84551. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  84552. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  84553. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  84554. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  84555. sqlite3VdbeJumpHere(v, addrIsNull);
  84556. }
  84557. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  84558. /* End of analysis */
  84559. sqlite3VdbeJumpHere(v, addrRewind);
  84560. }
  84561. /* Create a single sqlite_stat1 entry containing NULL as the index
  84562. ** name and the row count as the content.
  84563. */
  84564. if( pOnlyIdx==0 && needTableCnt ){
  84565. VdbeComment((v, "%s", pTab->zName));
  84566. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  84567. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  84568. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  84569. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  84570. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  84571. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  84572. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  84573. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  84574. sqlite3VdbeJumpHere(v, jZeroRows);
  84575. }
  84576. }
  84577. /*
  84578. ** Generate code that will cause the most recent index analysis to
  84579. ** be loaded into internal hash tables where is can be used.
  84580. */
  84581. static void loadAnalysis(Parse *pParse, int iDb){
  84582. Vdbe *v = sqlite3GetVdbe(pParse);
  84583. if( v ){
  84584. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  84585. }
  84586. }
  84587. /*
  84588. ** Generate code that will do an analysis of an entire database
  84589. */
  84590. static void analyzeDatabase(Parse *pParse, int iDb){
  84591. sqlite3 *db = pParse->db;
  84592. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  84593. HashElem *k;
  84594. int iStatCur;
  84595. int iMem;
  84596. int iTab;
  84597. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84598. iStatCur = pParse->nTab;
  84599. pParse->nTab += 3;
  84600. openStatTable(pParse, iDb, iStatCur, 0, 0);
  84601. iMem = pParse->nMem+1;
  84602. iTab = pParse->nTab;
  84603. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84604. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  84605. Table *pTab = (Table*)sqliteHashData(k);
  84606. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  84607. }
  84608. loadAnalysis(pParse, iDb);
  84609. }
  84610. /*
  84611. ** Generate code that will do an analysis of a single table in
  84612. ** a database. If pOnlyIdx is not NULL then it is a single index
  84613. ** in pTab that should be analyzed.
  84614. */
  84615. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  84616. int iDb;
  84617. int iStatCur;
  84618. assert( pTab!=0 );
  84619. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  84620. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84621. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84622. iStatCur = pParse->nTab;
  84623. pParse->nTab += 3;
  84624. if( pOnlyIdx ){
  84625. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  84626. }else{
  84627. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  84628. }
  84629. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  84630. loadAnalysis(pParse, iDb);
  84631. }
  84632. /*
  84633. ** Generate code for the ANALYZE command. The parser calls this routine
  84634. ** when it recognizes an ANALYZE command.
  84635. **
  84636. ** ANALYZE -- 1
  84637. ** ANALYZE <database> -- 2
  84638. ** ANALYZE ?<database>.?<tablename> -- 3
  84639. **
  84640. ** Form 1 causes all indices in all attached databases to be analyzed.
  84641. ** Form 2 analyzes all indices the single database named.
  84642. ** Form 3 analyzes all indices associated with the named table.
  84643. */
  84644. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  84645. sqlite3 *db = pParse->db;
  84646. int iDb;
  84647. int i;
  84648. char *z, *zDb;
  84649. Table *pTab;
  84650. Index *pIdx;
  84651. Token *pTableName;
  84652. Vdbe *v;
  84653. /* Read the database schema. If an error occurs, leave an error message
  84654. ** and code in pParse and return NULL. */
  84655. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  84656. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  84657. return;
  84658. }
  84659. assert( pName2!=0 || pName1==0 );
  84660. if( pName1==0 ){
  84661. /* Form 1: Analyze everything */
  84662. for(i=0; i<db->nDb; i++){
  84663. if( i==1 ) continue; /* Do not analyze the TEMP database */
  84664. analyzeDatabase(pParse, i);
  84665. }
  84666. }else if( pName2->n==0 ){
  84667. /* Form 2: Analyze the database or table named */
  84668. iDb = sqlite3FindDb(db, pName1);
  84669. if( iDb>=0 ){
  84670. analyzeDatabase(pParse, iDb);
  84671. }else{
  84672. z = sqlite3NameFromToken(db, pName1);
  84673. if( z ){
  84674. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  84675. analyzeTable(pParse, pIdx->pTable, pIdx);
  84676. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  84677. analyzeTable(pParse, pTab, 0);
  84678. }
  84679. sqlite3DbFree(db, z);
  84680. }
  84681. }
  84682. }else{
  84683. /* Form 3: Analyze the fully qualified table name */
  84684. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  84685. if( iDb>=0 ){
  84686. zDb = db->aDb[iDb].zName;
  84687. z = sqlite3NameFromToken(db, pTableName);
  84688. if( z ){
  84689. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  84690. analyzeTable(pParse, pIdx->pTable, pIdx);
  84691. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  84692. analyzeTable(pParse, pTab, 0);
  84693. }
  84694. sqlite3DbFree(db, z);
  84695. }
  84696. }
  84697. }
  84698. v = sqlite3GetVdbe(pParse);
  84699. if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
  84700. }
  84701. /*
  84702. ** Used to pass information from the analyzer reader through to the
  84703. ** callback routine.
  84704. */
  84705. typedef struct analysisInfo analysisInfo;
  84706. struct analysisInfo {
  84707. sqlite3 *db;
  84708. const char *zDatabase;
  84709. };
  84710. /*
  84711. ** The first argument points to a nul-terminated string containing a
  84712. ** list of space separated integers. Read the first nOut of these into
  84713. ** the array aOut[].
  84714. */
  84715. static void decodeIntArray(
  84716. char *zIntArray, /* String containing int array to decode */
  84717. int nOut, /* Number of slots in aOut[] */
  84718. tRowcnt *aOut, /* Store integers here */
  84719. LogEst *aLog, /* Or, if aOut==0, here */
  84720. Index *pIndex /* Handle extra flags for this index, if not NULL */
  84721. ){
  84722. char *z = zIntArray;
  84723. int c;
  84724. int i;
  84725. tRowcnt v;
  84726. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84727. if( z==0 ) z = "";
  84728. #else
  84729. assert( z!=0 );
  84730. #endif
  84731. for(i=0; *z && i<nOut; i++){
  84732. v = 0;
  84733. while( (c=z[0])>='0' && c<='9' ){
  84734. v = v*10 + c - '0';
  84735. z++;
  84736. }
  84737. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84738. if( aOut ) aOut[i] = v;
  84739. if( aLog ) aLog[i] = sqlite3LogEst(v);
  84740. #else
  84741. assert( aOut==0 );
  84742. UNUSED_PARAMETER(aOut);
  84743. assert( aLog!=0 );
  84744. aLog[i] = sqlite3LogEst(v);
  84745. #endif
  84746. if( *z==' ' ) z++;
  84747. }
  84748. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  84749. assert( pIndex!=0 ); {
  84750. #else
  84751. if( pIndex ){
  84752. #endif
  84753. pIndex->bUnordered = 0;
  84754. pIndex->noSkipScan = 0;
  84755. while( z[0] ){
  84756. if( sqlite3_strglob("unordered*", z)==0 ){
  84757. pIndex->bUnordered = 1;
  84758. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  84759. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  84760. }else if( sqlite3_strglob("noskipscan*", z)==0 ){
  84761. pIndex->noSkipScan = 1;
  84762. }
  84763. #ifdef SQLITE_ENABLE_COSTMULT
  84764. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  84765. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  84766. }
  84767. #endif
  84768. while( z[0]!=0 && z[0]!=' ' ) z++;
  84769. while( z[0]==' ' ) z++;
  84770. }
  84771. }
  84772. }
  84773. /*
  84774. ** This callback is invoked once for each index when reading the
  84775. ** sqlite_stat1 table.
  84776. **
  84777. ** argv[0] = name of the table
  84778. ** argv[1] = name of the index (might be NULL)
  84779. ** argv[2] = results of analysis - on integer for each column
  84780. **
  84781. ** Entries for which argv[1]==NULL simply record the number of rows in
  84782. ** the table.
  84783. */
  84784. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  84785. analysisInfo *pInfo = (analysisInfo*)pData;
  84786. Index *pIndex;
  84787. Table *pTable;
  84788. const char *z;
  84789. assert( argc==3 );
  84790. UNUSED_PARAMETER2(NotUsed, argc);
  84791. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  84792. return 0;
  84793. }
  84794. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  84795. if( pTable==0 ){
  84796. return 0;
  84797. }
  84798. if( argv[1]==0 ){
  84799. pIndex = 0;
  84800. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  84801. pIndex = sqlite3PrimaryKeyIndex(pTable);
  84802. }else{
  84803. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  84804. }
  84805. z = argv[2];
  84806. if( pIndex ){
  84807. tRowcnt *aiRowEst = 0;
  84808. int nCol = pIndex->nKeyCol+1;
  84809. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84810. /* Index.aiRowEst may already be set here if there are duplicate
  84811. ** sqlite_stat1 entries for this index. In that case just clobber
  84812. ** the old data with the new instead of allocating a new array. */
  84813. if( pIndex->aiRowEst==0 ){
  84814. pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
  84815. if( pIndex->aiRowEst==0 ) pInfo->db->mallocFailed = 1;
  84816. }
  84817. aiRowEst = pIndex->aiRowEst;
  84818. #endif
  84819. pIndex->bUnordered = 0;
  84820. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  84821. if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  84822. }else{
  84823. Index fakeIdx;
  84824. fakeIdx.szIdxRow = pTable->szTabRow;
  84825. #ifdef SQLITE_ENABLE_COSTMULT
  84826. fakeIdx.pTable = pTable;
  84827. #endif
  84828. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  84829. pTable->szTabRow = fakeIdx.szIdxRow;
  84830. }
  84831. return 0;
  84832. }
  84833. /*
  84834. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  84835. ** and its contents.
  84836. */
  84837. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  84838. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84839. if( pIdx->aSample ){
  84840. int j;
  84841. for(j=0; j<pIdx->nSample; j++){
  84842. IndexSample *p = &pIdx->aSample[j];
  84843. sqlite3DbFree(db, p->p);
  84844. }
  84845. sqlite3DbFree(db, pIdx->aSample);
  84846. }
  84847. if( db && db->pnBytesFreed==0 ){
  84848. pIdx->nSample = 0;
  84849. pIdx->aSample = 0;
  84850. }
  84851. #else
  84852. UNUSED_PARAMETER(db);
  84853. UNUSED_PARAMETER(pIdx);
  84854. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  84855. }
  84856. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  84857. /*
  84858. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  84859. ** stored in pIdx->aSample[].
  84860. */
  84861. static void initAvgEq(Index *pIdx){
  84862. if( pIdx ){
  84863. IndexSample *aSample = pIdx->aSample;
  84864. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  84865. int iCol;
  84866. int nCol = 1;
  84867. if( pIdx->nSampleCol>1 ){
  84868. /* If this is stat4 data, then calculate aAvgEq[] values for all
  84869. ** sample columns except the last. The last is always set to 1, as
  84870. ** once the trailing PK fields are considered all index keys are
  84871. ** unique. */
  84872. nCol = pIdx->nSampleCol-1;
  84873. pIdx->aAvgEq[nCol] = 1;
  84874. }
  84875. for(iCol=0; iCol<nCol; iCol++){
  84876. int nSample = pIdx->nSample;
  84877. int i; /* Used to iterate through samples */
  84878. tRowcnt sumEq = 0; /* Sum of the nEq values */
  84879. tRowcnt avgEq = 0;
  84880. tRowcnt nRow; /* Number of rows in index */
  84881. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  84882. i64 nDist100; /* Number of distinct values in index */
  84883. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  84884. nRow = pFinal->anLt[iCol];
  84885. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  84886. nSample--;
  84887. }else{
  84888. nRow = pIdx->aiRowEst[0];
  84889. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  84890. }
  84891. pIdx->nRowEst0 = nRow;
  84892. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  84893. ** occur in the stat4 table for this index. Set sumEq to the sum of
  84894. ** the nEq values for column iCol for the same set (adding the value
  84895. ** only once where there exist duplicate prefixes). */
  84896. for(i=0; i<nSample; i++){
  84897. if( i==(pIdx->nSample-1)
  84898. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  84899. ){
  84900. sumEq += aSample[i].anEq[iCol];
  84901. nSum100 += 100;
  84902. }
  84903. }
  84904. if( nDist100>nSum100 ){
  84905. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  84906. }
  84907. if( avgEq==0 ) avgEq = 1;
  84908. pIdx->aAvgEq[iCol] = avgEq;
  84909. }
  84910. }
  84911. }
  84912. /*
  84913. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  84914. ** is supplied instead, find the PRIMARY KEY index for that table.
  84915. */
  84916. static Index *findIndexOrPrimaryKey(
  84917. sqlite3 *db,
  84918. const char *zName,
  84919. const char *zDb
  84920. ){
  84921. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  84922. if( pIdx==0 ){
  84923. Table *pTab = sqlite3FindTable(db, zName, zDb);
  84924. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  84925. }
  84926. return pIdx;
  84927. }
  84928. /*
  84929. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  84930. ** into the relevant Index.aSample[] arrays.
  84931. **
  84932. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  84933. ** data equivalent to the following (statements are different for stat3,
  84934. ** see the caller of this function for details):
  84935. **
  84936. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  84937. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  84938. **
  84939. ** where %Q is replaced with the database name before the SQL is executed.
  84940. */
  84941. static int loadStatTbl(
  84942. sqlite3 *db, /* Database handle */
  84943. int bStat3, /* Assume single column records only */
  84944. const char *zSql1, /* SQL statement 1 (see above) */
  84945. const char *zSql2, /* SQL statement 2 (see above) */
  84946. const char *zDb /* Database name (e.g. "main") */
  84947. ){
  84948. int rc; /* Result codes from subroutines */
  84949. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  84950. char *zSql; /* Text of the SQL statement */
  84951. Index *pPrevIdx = 0; /* Previous index in the loop */
  84952. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  84953. assert( db->lookaside.bEnabled==0 );
  84954. zSql = sqlite3MPrintf(db, zSql1, zDb);
  84955. if( !zSql ){
  84956. return SQLITE_NOMEM;
  84957. }
  84958. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  84959. sqlite3DbFree(db, zSql);
  84960. if( rc ) return rc;
  84961. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  84962. int nIdxCol = 1; /* Number of columns in stat4 records */
  84963. char *zIndex; /* Index name */
  84964. Index *pIdx; /* Pointer to the index object */
  84965. int nSample; /* Number of samples */
  84966. int nByte; /* Bytes of space required */
  84967. int i; /* Bytes of space required */
  84968. tRowcnt *pSpace;
  84969. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  84970. if( zIndex==0 ) continue;
  84971. nSample = sqlite3_column_int(pStmt, 1);
  84972. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  84973. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  84974. /* Index.nSample is non-zero at this point if data has already been
  84975. ** loaded from the stat4 table. In this case ignore stat3 data. */
  84976. if( pIdx==0 || pIdx->nSample ) continue;
  84977. if( bStat3==0 ){
  84978. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  84979. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  84980. nIdxCol = pIdx->nKeyCol;
  84981. }else{
  84982. nIdxCol = pIdx->nColumn;
  84983. }
  84984. }
  84985. pIdx->nSampleCol = nIdxCol;
  84986. nByte = sizeof(IndexSample) * nSample;
  84987. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  84988. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  84989. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  84990. if( pIdx->aSample==0 ){
  84991. sqlite3_finalize(pStmt);
  84992. return SQLITE_NOMEM;
  84993. }
  84994. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  84995. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  84996. for(i=0; i<nSample; i++){
  84997. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  84998. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  84999. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  85000. }
  85001. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  85002. }
  85003. rc = sqlite3_finalize(pStmt);
  85004. if( rc ) return rc;
  85005. zSql = sqlite3MPrintf(db, zSql2, zDb);
  85006. if( !zSql ){
  85007. return SQLITE_NOMEM;
  85008. }
  85009. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  85010. sqlite3DbFree(db, zSql);
  85011. if( rc ) return rc;
  85012. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  85013. char *zIndex; /* Index name */
  85014. Index *pIdx; /* Pointer to the index object */
  85015. int nCol = 1; /* Number of columns in index */
  85016. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  85017. if( zIndex==0 ) continue;
  85018. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  85019. if( pIdx==0 ) continue;
  85020. /* This next condition is true if data has already been loaded from
  85021. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  85022. nCol = pIdx->nSampleCol;
  85023. if( bStat3 && nCol>1 ) continue;
  85024. if( pIdx!=pPrevIdx ){
  85025. initAvgEq(pPrevIdx);
  85026. pPrevIdx = pIdx;
  85027. }
  85028. pSample = &pIdx->aSample[pIdx->nSample];
  85029. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  85030. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  85031. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  85032. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  85033. ** This is in case the sample record is corrupted. In that case, the
  85034. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  85035. ** end of the allocated buffer before it realizes it is dealing with
  85036. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  85037. ** a buffer overread. */
  85038. pSample->n = sqlite3_column_bytes(pStmt, 4);
  85039. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  85040. if( pSample->p==0 ){
  85041. sqlite3_finalize(pStmt);
  85042. return SQLITE_NOMEM;
  85043. }
  85044. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  85045. pIdx->nSample++;
  85046. }
  85047. rc = sqlite3_finalize(pStmt);
  85048. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  85049. return rc;
  85050. }
  85051. /*
  85052. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  85053. ** the Index.aSample[] arrays of all indices.
  85054. */
  85055. static int loadStat4(sqlite3 *db, const char *zDb){
  85056. int rc = SQLITE_OK; /* Result codes from subroutines */
  85057. assert( db->lookaside.bEnabled==0 );
  85058. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  85059. rc = loadStatTbl(db, 0,
  85060. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  85061. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  85062. zDb
  85063. );
  85064. }
  85065. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  85066. rc = loadStatTbl(db, 1,
  85067. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  85068. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  85069. zDb
  85070. );
  85071. }
  85072. return rc;
  85073. }
  85074. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  85075. /*
  85076. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  85077. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  85078. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  85079. ** Index.aSample[] arrays.
  85080. **
  85081. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  85082. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  85083. ** during compilation and the sqlite_stat3/4 table is present, no data is
  85084. ** read from it.
  85085. **
  85086. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  85087. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  85088. ** returned. However, in this case, data is read from the sqlite_stat1
  85089. ** table (if it is present) before returning.
  85090. **
  85091. ** If an OOM error occurs, this function always sets db->mallocFailed.
  85092. ** This means if the caller does not care about other errors, the return
  85093. ** code may be ignored.
  85094. */
  85095. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  85096. analysisInfo sInfo;
  85097. HashElem *i;
  85098. char *zSql;
  85099. int rc;
  85100. assert( iDb>=0 && iDb<db->nDb );
  85101. assert( db->aDb[iDb].pBt!=0 );
  85102. /* Clear any prior statistics */
  85103. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85104. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  85105. Index *pIdx = sqliteHashData(i);
  85106. sqlite3DefaultRowEst(pIdx);
  85107. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85108. sqlite3DeleteIndexSamples(db, pIdx);
  85109. pIdx->aSample = 0;
  85110. #endif
  85111. }
  85112. /* Check to make sure the sqlite_stat1 table exists */
  85113. sInfo.db = db;
  85114. sInfo.zDatabase = db->aDb[iDb].zName;
  85115. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  85116. return SQLITE_ERROR;
  85117. }
  85118. /* Load new statistics out of the sqlite_stat1 table */
  85119. zSql = sqlite3MPrintf(db,
  85120. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  85121. if( zSql==0 ){
  85122. rc = SQLITE_NOMEM;
  85123. }else{
  85124. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  85125. sqlite3DbFree(db, zSql);
  85126. }
  85127. /* Load the statistics from the sqlite_stat4 table. */
  85128. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  85129. if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
  85130. int lookasideEnabled = db->lookaside.bEnabled;
  85131. db->lookaside.bEnabled = 0;
  85132. rc = loadStat4(db, sInfo.zDatabase);
  85133. db->lookaside.bEnabled = lookasideEnabled;
  85134. }
  85135. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  85136. Index *pIdx = sqliteHashData(i);
  85137. sqlite3_free(pIdx->aiRowEst);
  85138. pIdx->aiRowEst = 0;
  85139. }
  85140. #endif
  85141. if( rc==SQLITE_NOMEM ){
  85142. db->mallocFailed = 1;
  85143. }
  85144. return rc;
  85145. }
  85146. #endif /* SQLITE_OMIT_ANALYZE */
  85147. /************** End of analyze.c *********************************************/
  85148. /************** Begin file attach.c ******************************************/
  85149. /*
  85150. ** 2003 April 6
  85151. **
  85152. ** The author disclaims copyright to this source code. In place of
  85153. ** a legal notice, here is a blessing:
  85154. **
  85155. ** May you do good and not evil.
  85156. ** May you find forgiveness for yourself and forgive others.
  85157. ** May you share freely, never taking more than you give.
  85158. **
  85159. *************************************************************************
  85160. ** This file contains code used to implement the ATTACH and DETACH commands.
  85161. */
  85162. /* #include "sqliteInt.h" */
  85163. #ifndef SQLITE_OMIT_ATTACH
  85164. /*
  85165. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  85166. ** is slightly different from resolving a normal SQL expression, because simple
  85167. ** identifiers are treated as strings, not possible column names or aliases.
  85168. **
  85169. ** i.e. if the parser sees:
  85170. **
  85171. ** ATTACH DATABASE abc AS def
  85172. **
  85173. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  85174. ** looking for columns of the same name.
  85175. **
  85176. ** This only applies to the root node of pExpr, so the statement:
  85177. **
  85178. ** ATTACH DATABASE abc||def AS 'db2'
  85179. **
  85180. ** will fail because neither abc or def can be resolved.
  85181. */
  85182. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  85183. {
  85184. int rc = SQLITE_OK;
  85185. if( pExpr ){
  85186. if( pExpr->op!=TK_ID ){
  85187. rc = sqlite3ResolveExprNames(pName, pExpr);
  85188. }else{
  85189. pExpr->op = TK_STRING;
  85190. }
  85191. }
  85192. return rc;
  85193. }
  85194. /*
  85195. ** An SQL user-function registered to do the work of an ATTACH statement. The
  85196. ** three arguments to the function come directly from an attach statement:
  85197. **
  85198. ** ATTACH DATABASE x AS y KEY z
  85199. **
  85200. ** SELECT sqlite_attach(x, y, z)
  85201. **
  85202. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  85203. ** third argument.
  85204. */
  85205. static void attachFunc(
  85206. sqlite3_context *context,
  85207. int NotUsed,
  85208. sqlite3_value **argv
  85209. ){
  85210. int i;
  85211. int rc = 0;
  85212. sqlite3 *db = sqlite3_context_db_handle(context);
  85213. const char *zName;
  85214. const char *zFile;
  85215. char *zPath = 0;
  85216. char *zErr = 0;
  85217. unsigned int flags;
  85218. Db *aNew;
  85219. char *zErrDyn = 0;
  85220. sqlite3_vfs *pVfs;
  85221. UNUSED_PARAMETER(NotUsed);
  85222. zFile = (const char *)sqlite3_value_text(argv[0]);
  85223. zName = (const char *)sqlite3_value_text(argv[1]);
  85224. if( zFile==0 ) zFile = "";
  85225. if( zName==0 ) zName = "";
  85226. /* Check for the following errors:
  85227. **
  85228. ** * Too many attached databases,
  85229. ** * Transaction currently open
  85230. ** * Specified database name already being used.
  85231. */
  85232. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  85233. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  85234. db->aLimit[SQLITE_LIMIT_ATTACHED]
  85235. );
  85236. goto attach_error;
  85237. }
  85238. if( !db->autoCommit ){
  85239. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  85240. goto attach_error;
  85241. }
  85242. for(i=0; i<db->nDb; i++){
  85243. char *z = db->aDb[i].zName;
  85244. assert( z && zName );
  85245. if( sqlite3StrICmp(z, zName)==0 ){
  85246. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  85247. goto attach_error;
  85248. }
  85249. }
  85250. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  85251. ** hash tables.
  85252. */
  85253. if( db->aDb==db->aDbStatic ){
  85254. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  85255. if( aNew==0 ) return;
  85256. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  85257. }else{
  85258. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  85259. if( aNew==0 ) return;
  85260. }
  85261. db->aDb = aNew;
  85262. aNew = &db->aDb[db->nDb];
  85263. memset(aNew, 0, sizeof(*aNew));
  85264. /* Open the database file. If the btree is successfully opened, use
  85265. ** it to obtain the database schema. At this point the schema may
  85266. ** or may not be initialized.
  85267. */
  85268. flags = db->openFlags;
  85269. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  85270. if( rc!=SQLITE_OK ){
  85271. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  85272. sqlite3_result_error(context, zErr, -1);
  85273. sqlite3_free(zErr);
  85274. return;
  85275. }
  85276. assert( pVfs );
  85277. flags |= SQLITE_OPEN_MAIN_DB;
  85278. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  85279. sqlite3_free( zPath );
  85280. db->nDb++;
  85281. if( rc==SQLITE_CONSTRAINT ){
  85282. rc = SQLITE_ERROR;
  85283. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  85284. }else if( rc==SQLITE_OK ){
  85285. Pager *pPager;
  85286. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  85287. if( !aNew->pSchema ){
  85288. rc = SQLITE_NOMEM;
  85289. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  85290. zErrDyn = sqlite3MPrintf(db,
  85291. "attached databases must use the same text encoding as main database");
  85292. rc = SQLITE_ERROR;
  85293. }
  85294. sqlite3BtreeEnter(aNew->pBt);
  85295. pPager = sqlite3BtreePager(aNew->pBt);
  85296. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  85297. sqlite3BtreeSecureDelete(aNew->pBt,
  85298. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  85299. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  85300. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  85301. #endif
  85302. sqlite3BtreeLeave(aNew->pBt);
  85303. }
  85304. aNew->safety_level = 3;
  85305. aNew->zName = sqlite3DbStrDup(db, zName);
  85306. if( rc==SQLITE_OK && aNew->zName==0 ){
  85307. rc = SQLITE_NOMEM;
  85308. }
  85309. #ifdef SQLITE_HAS_CODEC
  85310. if( rc==SQLITE_OK ){
  85311. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  85312. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  85313. int nKey;
  85314. char *zKey;
  85315. int t = sqlite3_value_type(argv[2]);
  85316. switch( t ){
  85317. case SQLITE_INTEGER:
  85318. case SQLITE_FLOAT:
  85319. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  85320. rc = SQLITE_ERROR;
  85321. break;
  85322. case SQLITE_TEXT:
  85323. case SQLITE_BLOB:
  85324. nKey = sqlite3_value_bytes(argv[2]);
  85325. zKey = (char *)sqlite3_value_blob(argv[2]);
  85326. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  85327. break;
  85328. case SQLITE_NULL:
  85329. /* No key specified. Use the key from the main database */
  85330. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  85331. if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
  85332. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  85333. }
  85334. break;
  85335. }
  85336. }
  85337. #endif
  85338. /* If the file was opened successfully, read the schema for the new database.
  85339. ** If this fails, or if opening the file failed, then close the file and
  85340. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  85341. ** we found it.
  85342. */
  85343. if( rc==SQLITE_OK ){
  85344. sqlite3BtreeEnterAll(db);
  85345. rc = sqlite3Init(db, &zErrDyn);
  85346. sqlite3BtreeLeaveAll(db);
  85347. }
  85348. #ifdef SQLITE_USER_AUTHENTICATION
  85349. if( rc==SQLITE_OK ){
  85350. u8 newAuth = 0;
  85351. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  85352. if( newAuth<db->auth.authLevel ){
  85353. rc = SQLITE_AUTH_USER;
  85354. }
  85355. }
  85356. #endif
  85357. if( rc ){
  85358. int iDb = db->nDb - 1;
  85359. assert( iDb>=2 );
  85360. if( db->aDb[iDb].pBt ){
  85361. sqlite3BtreeClose(db->aDb[iDb].pBt);
  85362. db->aDb[iDb].pBt = 0;
  85363. db->aDb[iDb].pSchema = 0;
  85364. }
  85365. sqlite3ResetAllSchemasOfConnection(db);
  85366. db->nDb = iDb;
  85367. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  85368. db->mallocFailed = 1;
  85369. sqlite3DbFree(db, zErrDyn);
  85370. zErrDyn = sqlite3MPrintf(db, "out of memory");
  85371. }else if( zErrDyn==0 ){
  85372. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  85373. }
  85374. goto attach_error;
  85375. }
  85376. return;
  85377. attach_error:
  85378. /* Return an error if we get here */
  85379. if( zErrDyn ){
  85380. sqlite3_result_error(context, zErrDyn, -1);
  85381. sqlite3DbFree(db, zErrDyn);
  85382. }
  85383. if( rc ) sqlite3_result_error_code(context, rc);
  85384. }
  85385. /*
  85386. ** An SQL user-function registered to do the work of an DETACH statement. The
  85387. ** three arguments to the function come directly from a detach statement:
  85388. **
  85389. ** DETACH DATABASE x
  85390. **
  85391. ** SELECT sqlite_detach(x)
  85392. */
  85393. static void detachFunc(
  85394. sqlite3_context *context,
  85395. int NotUsed,
  85396. sqlite3_value **argv
  85397. ){
  85398. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  85399. sqlite3 *db = sqlite3_context_db_handle(context);
  85400. int i;
  85401. Db *pDb = 0;
  85402. char zErr[128];
  85403. UNUSED_PARAMETER(NotUsed);
  85404. if( zName==0 ) zName = "";
  85405. for(i=0; i<db->nDb; i++){
  85406. pDb = &db->aDb[i];
  85407. if( pDb->pBt==0 ) continue;
  85408. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  85409. }
  85410. if( i>=db->nDb ){
  85411. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  85412. goto detach_error;
  85413. }
  85414. if( i<2 ){
  85415. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  85416. goto detach_error;
  85417. }
  85418. if( !db->autoCommit ){
  85419. sqlite3_snprintf(sizeof(zErr), zErr,
  85420. "cannot DETACH database within transaction");
  85421. goto detach_error;
  85422. }
  85423. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  85424. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  85425. goto detach_error;
  85426. }
  85427. sqlite3BtreeClose(pDb->pBt);
  85428. pDb->pBt = 0;
  85429. pDb->pSchema = 0;
  85430. sqlite3CollapseDatabaseArray(db);
  85431. return;
  85432. detach_error:
  85433. sqlite3_result_error(context, zErr, -1);
  85434. }
  85435. /*
  85436. ** This procedure generates VDBE code for a single invocation of either the
  85437. ** sqlite_detach() or sqlite_attach() SQL user functions.
  85438. */
  85439. static void codeAttach(
  85440. Parse *pParse, /* The parser context */
  85441. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  85442. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  85443. Expr *pAuthArg, /* Expression to pass to authorization callback */
  85444. Expr *pFilename, /* Name of database file */
  85445. Expr *pDbname, /* Name of the database to use internally */
  85446. Expr *pKey /* Database key for encryption extension */
  85447. ){
  85448. int rc;
  85449. NameContext sName;
  85450. Vdbe *v;
  85451. sqlite3* db = pParse->db;
  85452. int regArgs;
  85453. memset(&sName, 0, sizeof(NameContext));
  85454. sName.pParse = pParse;
  85455. if(
  85456. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  85457. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  85458. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  85459. ){
  85460. goto attach_end;
  85461. }
  85462. #ifndef SQLITE_OMIT_AUTHORIZATION
  85463. if( pAuthArg ){
  85464. char *zAuthArg;
  85465. if( pAuthArg->op==TK_STRING ){
  85466. zAuthArg = pAuthArg->u.zToken;
  85467. }else{
  85468. zAuthArg = 0;
  85469. }
  85470. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  85471. if(rc!=SQLITE_OK ){
  85472. goto attach_end;
  85473. }
  85474. }
  85475. #endif /* SQLITE_OMIT_AUTHORIZATION */
  85476. v = sqlite3GetVdbe(pParse);
  85477. regArgs = sqlite3GetTempRange(pParse, 4);
  85478. sqlite3ExprCode(pParse, pFilename, regArgs);
  85479. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  85480. sqlite3ExprCode(pParse, pKey, regArgs+2);
  85481. assert( v || db->mallocFailed );
  85482. if( v ){
  85483. sqlite3VdbeAddOp3(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3);
  85484. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  85485. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  85486. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  85487. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  85488. ** statement only). For DETACH, set it to false (expire all existing
  85489. ** statements).
  85490. */
  85491. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  85492. }
  85493. attach_end:
  85494. sqlite3ExprDelete(db, pFilename);
  85495. sqlite3ExprDelete(db, pDbname);
  85496. sqlite3ExprDelete(db, pKey);
  85497. }
  85498. /*
  85499. ** Called by the parser to compile a DETACH statement.
  85500. **
  85501. ** DETACH pDbname
  85502. */
  85503. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  85504. static const FuncDef detach_func = {
  85505. 1, /* nArg */
  85506. SQLITE_UTF8, /* funcFlags */
  85507. 0, /* pUserData */
  85508. 0, /* pNext */
  85509. detachFunc, /* xFunc */
  85510. 0, /* xStep */
  85511. 0, /* xFinalize */
  85512. "sqlite_detach", /* zName */
  85513. 0, /* pHash */
  85514. 0 /* pDestructor */
  85515. };
  85516. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  85517. }
  85518. /*
  85519. ** Called by the parser to compile an ATTACH statement.
  85520. **
  85521. ** ATTACH p AS pDbname KEY pKey
  85522. */
  85523. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  85524. static const FuncDef attach_func = {
  85525. 3, /* nArg */
  85526. SQLITE_UTF8, /* funcFlags */
  85527. 0, /* pUserData */
  85528. 0, /* pNext */
  85529. attachFunc, /* xFunc */
  85530. 0, /* xStep */
  85531. 0, /* xFinalize */
  85532. "sqlite_attach", /* zName */
  85533. 0, /* pHash */
  85534. 0 /* pDestructor */
  85535. };
  85536. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  85537. }
  85538. #endif /* SQLITE_OMIT_ATTACH */
  85539. /*
  85540. ** Initialize a DbFixer structure. This routine must be called prior
  85541. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  85542. */
  85543. SQLITE_PRIVATE void sqlite3FixInit(
  85544. DbFixer *pFix, /* The fixer to be initialized */
  85545. Parse *pParse, /* Error messages will be written here */
  85546. int iDb, /* This is the database that must be used */
  85547. const char *zType, /* "view", "trigger", or "index" */
  85548. const Token *pName /* Name of the view, trigger, or index */
  85549. ){
  85550. sqlite3 *db;
  85551. db = pParse->db;
  85552. assert( db->nDb>iDb );
  85553. pFix->pParse = pParse;
  85554. pFix->zDb = db->aDb[iDb].zName;
  85555. pFix->pSchema = db->aDb[iDb].pSchema;
  85556. pFix->zType = zType;
  85557. pFix->pName = pName;
  85558. pFix->bVarOnly = (iDb==1);
  85559. }
  85560. /*
  85561. ** The following set of routines walk through the parse tree and assign
  85562. ** a specific database to all table references where the database name
  85563. ** was left unspecified in the original SQL statement. The pFix structure
  85564. ** must have been initialized by a prior call to sqlite3FixInit().
  85565. **
  85566. ** These routines are used to make sure that an index, trigger, or
  85567. ** view in one database does not refer to objects in a different database.
  85568. ** (Exception: indices, triggers, and views in the TEMP database are
  85569. ** allowed to refer to anything.) If a reference is explicitly made
  85570. ** to an object in a different database, an error message is added to
  85571. ** pParse->zErrMsg and these routines return non-zero. If everything
  85572. ** checks out, these routines return 0.
  85573. */
  85574. SQLITE_PRIVATE int sqlite3FixSrcList(
  85575. DbFixer *pFix, /* Context of the fixation */
  85576. SrcList *pList /* The Source list to check and modify */
  85577. ){
  85578. int i;
  85579. const char *zDb;
  85580. struct SrcList_item *pItem;
  85581. if( NEVER(pList==0) ) return 0;
  85582. zDb = pFix->zDb;
  85583. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  85584. if( pFix->bVarOnly==0 ){
  85585. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  85586. sqlite3ErrorMsg(pFix->pParse,
  85587. "%s %T cannot reference objects in database %s",
  85588. pFix->zType, pFix->pName, pItem->zDatabase);
  85589. return 1;
  85590. }
  85591. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  85592. pItem->zDatabase = 0;
  85593. pItem->pSchema = pFix->pSchema;
  85594. }
  85595. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  85596. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  85597. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  85598. #endif
  85599. }
  85600. return 0;
  85601. }
  85602. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  85603. SQLITE_PRIVATE int sqlite3FixSelect(
  85604. DbFixer *pFix, /* Context of the fixation */
  85605. Select *pSelect /* The SELECT statement to be fixed to one database */
  85606. ){
  85607. while( pSelect ){
  85608. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  85609. return 1;
  85610. }
  85611. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  85612. return 1;
  85613. }
  85614. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  85615. return 1;
  85616. }
  85617. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  85618. return 1;
  85619. }
  85620. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  85621. return 1;
  85622. }
  85623. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  85624. return 1;
  85625. }
  85626. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  85627. return 1;
  85628. }
  85629. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  85630. return 1;
  85631. }
  85632. pSelect = pSelect->pPrior;
  85633. }
  85634. return 0;
  85635. }
  85636. SQLITE_PRIVATE int sqlite3FixExpr(
  85637. DbFixer *pFix, /* Context of the fixation */
  85638. Expr *pExpr /* The expression to be fixed to one database */
  85639. ){
  85640. while( pExpr ){
  85641. if( pExpr->op==TK_VARIABLE ){
  85642. if( pFix->pParse->db->init.busy ){
  85643. pExpr->op = TK_NULL;
  85644. }else{
  85645. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  85646. return 1;
  85647. }
  85648. }
  85649. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  85650. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  85651. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  85652. }else{
  85653. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  85654. }
  85655. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  85656. return 1;
  85657. }
  85658. pExpr = pExpr->pLeft;
  85659. }
  85660. return 0;
  85661. }
  85662. SQLITE_PRIVATE int sqlite3FixExprList(
  85663. DbFixer *pFix, /* Context of the fixation */
  85664. ExprList *pList /* The expression to be fixed to one database */
  85665. ){
  85666. int i;
  85667. struct ExprList_item *pItem;
  85668. if( pList==0 ) return 0;
  85669. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  85670. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  85671. return 1;
  85672. }
  85673. }
  85674. return 0;
  85675. }
  85676. #endif
  85677. #ifndef SQLITE_OMIT_TRIGGER
  85678. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  85679. DbFixer *pFix, /* Context of the fixation */
  85680. TriggerStep *pStep /* The trigger step be fixed to one database */
  85681. ){
  85682. while( pStep ){
  85683. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  85684. return 1;
  85685. }
  85686. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  85687. return 1;
  85688. }
  85689. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  85690. return 1;
  85691. }
  85692. pStep = pStep->pNext;
  85693. }
  85694. return 0;
  85695. }
  85696. #endif
  85697. /************** End of attach.c **********************************************/
  85698. /************** Begin file auth.c ********************************************/
  85699. /*
  85700. ** 2003 January 11
  85701. **
  85702. ** The author disclaims copyright to this source code. In place of
  85703. ** a legal notice, here is a blessing:
  85704. **
  85705. ** May you do good and not evil.
  85706. ** May you find forgiveness for yourself and forgive others.
  85707. ** May you share freely, never taking more than you give.
  85708. **
  85709. *************************************************************************
  85710. ** This file contains code used to implement the sqlite3_set_authorizer()
  85711. ** API. This facility is an optional feature of the library. Embedded
  85712. ** systems that do not need this facility may omit it by recompiling
  85713. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  85714. */
  85715. /* #include "sqliteInt.h" */
  85716. /*
  85717. ** All of the code in this file may be omitted by defining a single
  85718. ** macro.
  85719. */
  85720. #ifndef SQLITE_OMIT_AUTHORIZATION
  85721. /*
  85722. ** Set or clear the access authorization function.
  85723. **
  85724. ** The access authorization function is be called during the compilation
  85725. ** phase to verify that the user has read and/or write access permission on
  85726. ** various fields of the database. The first argument to the auth function
  85727. ** is a copy of the 3rd argument to this routine. The second argument
  85728. ** to the auth function is one of these constants:
  85729. **
  85730. ** SQLITE_CREATE_INDEX
  85731. ** SQLITE_CREATE_TABLE
  85732. ** SQLITE_CREATE_TEMP_INDEX
  85733. ** SQLITE_CREATE_TEMP_TABLE
  85734. ** SQLITE_CREATE_TEMP_TRIGGER
  85735. ** SQLITE_CREATE_TEMP_VIEW
  85736. ** SQLITE_CREATE_TRIGGER
  85737. ** SQLITE_CREATE_VIEW
  85738. ** SQLITE_DELETE
  85739. ** SQLITE_DROP_INDEX
  85740. ** SQLITE_DROP_TABLE
  85741. ** SQLITE_DROP_TEMP_INDEX
  85742. ** SQLITE_DROP_TEMP_TABLE
  85743. ** SQLITE_DROP_TEMP_TRIGGER
  85744. ** SQLITE_DROP_TEMP_VIEW
  85745. ** SQLITE_DROP_TRIGGER
  85746. ** SQLITE_DROP_VIEW
  85747. ** SQLITE_INSERT
  85748. ** SQLITE_PRAGMA
  85749. ** SQLITE_READ
  85750. ** SQLITE_SELECT
  85751. ** SQLITE_TRANSACTION
  85752. ** SQLITE_UPDATE
  85753. **
  85754. ** The third and fourth arguments to the auth function are the name of
  85755. ** the table and the column that are being accessed. The auth function
  85756. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  85757. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  85758. ** means that the SQL statement will never-run - the sqlite3_exec() call
  85759. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  85760. ** should run but attempts to read the specified column will return NULL
  85761. ** and attempts to write the column will be ignored.
  85762. **
  85763. ** Setting the auth function to NULL disables this hook. The default
  85764. ** setting of the auth function is NULL.
  85765. */
  85766. SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
  85767. sqlite3 *db,
  85768. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  85769. void *pArg
  85770. ){
  85771. #ifdef SQLITE_ENABLE_API_ARMOR
  85772. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  85773. #endif
  85774. sqlite3_mutex_enter(db->mutex);
  85775. db->xAuth = (sqlite3_xauth)xAuth;
  85776. db->pAuthArg = pArg;
  85777. sqlite3ExpirePreparedStatements(db);
  85778. sqlite3_mutex_leave(db->mutex);
  85779. return SQLITE_OK;
  85780. }
  85781. /*
  85782. ** Write an error message into pParse->zErrMsg that explains that the
  85783. ** user-supplied authorization function returned an illegal value.
  85784. */
  85785. static void sqliteAuthBadReturnCode(Parse *pParse){
  85786. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  85787. pParse->rc = SQLITE_ERROR;
  85788. }
  85789. /*
  85790. ** Invoke the authorization callback for permission to read column zCol from
  85791. ** table zTab in database zDb. This function assumes that an authorization
  85792. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  85793. **
  85794. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  85795. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  85796. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  85797. */
  85798. SQLITE_PRIVATE int sqlite3AuthReadCol(
  85799. Parse *pParse, /* The parser context */
  85800. const char *zTab, /* Table name */
  85801. const char *zCol, /* Column name */
  85802. int iDb /* Index of containing database. */
  85803. ){
  85804. sqlite3 *db = pParse->db; /* Database handle */
  85805. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  85806. int rc; /* Auth callback return code */
  85807. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  85808. #ifdef SQLITE_USER_AUTHENTICATION
  85809. ,db->auth.zAuthUser
  85810. #endif
  85811. );
  85812. if( rc==SQLITE_DENY ){
  85813. if( db->nDb>2 || iDb!=0 ){
  85814. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  85815. }else{
  85816. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  85817. }
  85818. pParse->rc = SQLITE_AUTH;
  85819. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  85820. sqliteAuthBadReturnCode(pParse);
  85821. }
  85822. return rc;
  85823. }
  85824. /*
  85825. ** The pExpr should be a TK_COLUMN expression. The table referred to
  85826. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  85827. ** Check to see if it is OK to read this particular column.
  85828. **
  85829. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  85830. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  85831. ** then generate an error.
  85832. */
  85833. SQLITE_PRIVATE void sqlite3AuthRead(
  85834. Parse *pParse, /* The parser context */
  85835. Expr *pExpr, /* The expression to check authorization on */
  85836. Schema *pSchema, /* The schema of the expression */
  85837. SrcList *pTabList /* All table that pExpr might refer to */
  85838. ){
  85839. sqlite3 *db = pParse->db;
  85840. Table *pTab = 0; /* The table being read */
  85841. const char *zCol; /* Name of the column of the table */
  85842. int iSrc; /* Index in pTabList->a[] of table being read */
  85843. int iDb; /* The index of the database the expression refers to */
  85844. int iCol; /* Index of column in table */
  85845. if( db->xAuth==0 ) return;
  85846. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  85847. if( iDb<0 ){
  85848. /* An attempt to read a column out of a subquery or other
  85849. ** temporary table. */
  85850. return;
  85851. }
  85852. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  85853. if( pExpr->op==TK_TRIGGER ){
  85854. pTab = pParse->pTriggerTab;
  85855. }else{
  85856. assert( pTabList );
  85857. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  85858. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  85859. pTab = pTabList->a[iSrc].pTab;
  85860. break;
  85861. }
  85862. }
  85863. }
  85864. iCol = pExpr->iColumn;
  85865. if( NEVER(pTab==0) ) return;
  85866. if( iCol>=0 ){
  85867. assert( iCol<pTab->nCol );
  85868. zCol = pTab->aCol[iCol].zName;
  85869. }else if( pTab->iPKey>=0 ){
  85870. assert( pTab->iPKey<pTab->nCol );
  85871. zCol = pTab->aCol[pTab->iPKey].zName;
  85872. }else{
  85873. zCol = "ROWID";
  85874. }
  85875. assert( iDb>=0 && iDb<db->nDb );
  85876. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  85877. pExpr->op = TK_NULL;
  85878. }
  85879. }
  85880. /*
  85881. ** Do an authorization check using the code and arguments given. Return
  85882. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  85883. ** is returned, then the error count and error message in pParse are
  85884. ** modified appropriately.
  85885. */
  85886. SQLITE_PRIVATE int sqlite3AuthCheck(
  85887. Parse *pParse,
  85888. int code,
  85889. const char *zArg1,
  85890. const char *zArg2,
  85891. const char *zArg3
  85892. ){
  85893. sqlite3 *db = pParse->db;
  85894. int rc;
  85895. /* Don't do any authorization checks if the database is initialising
  85896. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  85897. */
  85898. if( db->init.busy || IN_DECLARE_VTAB ){
  85899. return SQLITE_OK;
  85900. }
  85901. if( db->xAuth==0 ){
  85902. return SQLITE_OK;
  85903. }
  85904. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  85905. #ifdef SQLITE_USER_AUTHENTICATION
  85906. ,db->auth.zAuthUser
  85907. #endif
  85908. );
  85909. if( rc==SQLITE_DENY ){
  85910. sqlite3ErrorMsg(pParse, "not authorized");
  85911. pParse->rc = SQLITE_AUTH;
  85912. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  85913. rc = SQLITE_DENY;
  85914. sqliteAuthBadReturnCode(pParse);
  85915. }
  85916. return rc;
  85917. }
  85918. /*
  85919. ** Push an authorization context. After this routine is called, the
  85920. ** zArg3 argument to authorization callbacks will be zContext until
  85921. ** popped. Or if pParse==0, this routine is a no-op.
  85922. */
  85923. SQLITE_PRIVATE void sqlite3AuthContextPush(
  85924. Parse *pParse,
  85925. AuthContext *pContext,
  85926. const char *zContext
  85927. ){
  85928. assert( pParse );
  85929. pContext->pParse = pParse;
  85930. pContext->zAuthContext = pParse->zAuthContext;
  85931. pParse->zAuthContext = zContext;
  85932. }
  85933. /*
  85934. ** Pop an authorization context that was previously pushed
  85935. ** by sqlite3AuthContextPush
  85936. */
  85937. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  85938. if( pContext->pParse ){
  85939. pContext->pParse->zAuthContext = pContext->zAuthContext;
  85940. pContext->pParse = 0;
  85941. }
  85942. }
  85943. #endif /* SQLITE_OMIT_AUTHORIZATION */
  85944. /************** End of auth.c ************************************************/
  85945. /************** Begin file build.c *******************************************/
  85946. /*
  85947. ** 2001 September 15
  85948. **
  85949. ** The author disclaims copyright to this source code. In place of
  85950. ** a legal notice, here is a blessing:
  85951. **
  85952. ** May you do good and not evil.
  85953. ** May you find forgiveness for yourself and forgive others.
  85954. ** May you share freely, never taking more than you give.
  85955. **
  85956. *************************************************************************
  85957. ** This file contains C code routines that are called by the SQLite parser
  85958. ** when syntax rules are reduced. The routines in this file handle the
  85959. ** following kinds of SQL syntax:
  85960. **
  85961. ** CREATE TABLE
  85962. ** DROP TABLE
  85963. ** CREATE INDEX
  85964. ** DROP INDEX
  85965. ** creating ID lists
  85966. ** BEGIN TRANSACTION
  85967. ** COMMIT
  85968. ** ROLLBACK
  85969. */
  85970. /* #include "sqliteInt.h" */
  85971. /*
  85972. ** This routine is called when a new SQL statement is beginning to
  85973. ** be parsed. Initialize the pParse structure as needed.
  85974. */
  85975. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  85976. pParse->explain = (u8)explainFlag;
  85977. pParse->nVar = 0;
  85978. }
  85979. #ifndef SQLITE_OMIT_SHARED_CACHE
  85980. /*
  85981. ** The TableLock structure is only used by the sqlite3TableLock() and
  85982. ** codeTableLocks() functions.
  85983. */
  85984. struct TableLock {
  85985. int iDb; /* The database containing the table to be locked */
  85986. int iTab; /* The root page of the table to be locked */
  85987. u8 isWriteLock; /* True for write lock. False for a read lock */
  85988. const char *zName; /* Name of the table */
  85989. };
  85990. /*
  85991. ** Record the fact that we want to lock a table at run-time.
  85992. **
  85993. ** The table to be locked has root page iTab and is found in database iDb.
  85994. ** A read or a write lock can be taken depending on isWritelock.
  85995. **
  85996. ** This routine just records the fact that the lock is desired. The
  85997. ** code to make the lock occur is generated by a later call to
  85998. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  85999. */
  86000. SQLITE_PRIVATE void sqlite3TableLock(
  86001. Parse *pParse, /* Parsing context */
  86002. int iDb, /* Index of the database containing the table to lock */
  86003. int iTab, /* Root page number of the table to be locked */
  86004. u8 isWriteLock, /* True for a write lock */
  86005. const char *zName /* Name of the table to be locked */
  86006. ){
  86007. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86008. int i;
  86009. int nBytes;
  86010. TableLock *p;
  86011. assert( iDb>=0 );
  86012. for(i=0; i<pToplevel->nTableLock; i++){
  86013. p = &pToplevel->aTableLock[i];
  86014. if( p->iDb==iDb && p->iTab==iTab ){
  86015. p->isWriteLock = (p->isWriteLock || isWriteLock);
  86016. return;
  86017. }
  86018. }
  86019. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  86020. pToplevel->aTableLock =
  86021. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  86022. if( pToplevel->aTableLock ){
  86023. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  86024. p->iDb = iDb;
  86025. p->iTab = iTab;
  86026. p->isWriteLock = isWriteLock;
  86027. p->zName = zName;
  86028. }else{
  86029. pToplevel->nTableLock = 0;
  86030. pToplevel->db->mallocFailed = 1;
  86031. }
  86032. }
  86033. /*
  86034. ** Code an OP_TableLock instruction for each table locked by the
  86035. ** statement (configured by calls to sqlite3TableLock()).
  86036. */
  86037. static void codeTableLocks(Parse *pParse){
  86038. int i;
  86039. Vdbe *pVdbe;
  86040. pVdbe = sqlite3GetVdbe(pParse);
  86041. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  86042. for(i=0; i<pParse->nTableLock; i++){
  86043. TableLock *p = &pParse->aTableLock[i];
  86044. int p1 = p->iDb;
  86045. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  86046. p->zName, P4_STATIC);
  86047. }
  86048. }
  86049. #else
  86050. #define codeTableLocks(x)
  86051. #endif
  86052. /*
  86053. ** Return TRUE if the given yDbMask object is empty - if it contains no
  86054. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  86055. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  86056. */
  86057. #if SQLITE_MAX_ATTACHED>30
  86058. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  86059. int i;
  86060. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  86061. return 1;
  86062. }
  86063. #endif
  86064. /*
  86065. ** This routine is called after a single SQL statement has been
  86066. ** parsed and a VDBE program to execute that statement has been
  86067. ** prepared. This routine puts the finishing touches on the
  86068. ** VDBE program and resets the pParse structure for the next
  86069. ** parse.
  86070. **
  86071. ** Note that if an error occurred, it might be the case that
  86072. ** no VDBE code was generated.
  86073. */
  86074. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  86075. sqlite3 *db;
  86076. Vdbe *v;
  86077. assert( pParse->pToplevel==0 );
  86078. db = pParse->db;
  86079. if( pParse->nested ) return;
  86080. if( db->mallocFailed || pParse->nErr ){
  86081. if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
  86082. return;
  86083. }
  86084. /* Begin by generating some termination code at the end of the
  86085. ** vdbe program
  86086. */
  86087. v = sqlite3GetVdbe(pParse);
  86088. assert( !pParse->isMultiWrite
  86089. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  86090. if( v ){
  86091. while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
  86092. sqlite3VdbeAddOp0(v, OP_Halt);
  86093. #if SQLITE_USER_AUTHENTICATION
  86094. if( pParse->nTableLock>0 && db->init.busy==0 ){
  86095. sqlite3UserAuthInit(db);
  86096. if( db->auth.authLevel<UAUTH_User ){
  86097. pParse->rc = SQLITE_AUTH_USER;
  86098. sqlite3ErrorMsg(pParse, "user not authenticated");
  86099. return;
  86100. }
  86101. }
  86102. #endif
  86103. /* The cookie mask contains one bit for each database file open.
  86104. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  86105. ** set for each database that is used. Generate code to start a
  86106. ** transaction on each used database and to verify the schema cookie
  86107. ** on each used database.
  86108. */
  86109. if( db->mallocFailed==0
  86110. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  86111. ){
  86112. int iDb, i;
  86113. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  86114. sqlite3VdbeJumpHere(v, 0);
  86115. for(iDb=0; iDb<db->nDb; iDb++){
  86116. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  86117. sqlite3VdbeUsesBtree(v, iDb);
  86118. sqlite3VdbeAddOp4Int(v,
  86119. OP_Transaction, /* Opcode */
  86120. iDb, /* P1 */
  86121. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  86122. pParse->cookieValue[iDb], /* P3 */
  86123. db->aDb[iDb].pSchema->iGeneration /* P4 */
  86124. );
  86125. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  86126. }
  86127. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86128. for(i=0; i<pParse->nVtabLock; i++){
  86129. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  86130. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  86131. }
  86132. pParse->nVtabLock = 0;
  86133. #endif
  86134. /* Once all the cookies have been verified and transactions opened,
  86135. ** obtain the required table-locks. This is a no-op unless the
  86136. ** shared-cache feature is enabled.
  86137. */
  86138. codeTableLocks(pParse);
  86139. /* Initialize any AUTOINCREMENT data structures required.
  86140. */
  86141. sqlite3AutoincrementBegin(pParse);
  86142. /* Code constant expressions that where factored out of inner loops */
  86143. if( pParse->pConstExpr ){
  86144. ExprList *pEL = pParse->pConstExpr;
  86145. pParse->okConstFactor = 0;
  86146. for(i=0; i<pEL->nExpr; i++){
  86147. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  86148. }
  86149. }
  86150. /* Finally, jump back to the beginning of the executable code. */
  86151. sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
  86152. }
  86153. }
  86154. /* Get the VDBE program ready for execution
  86155. */
  86156. if( v && pParse->nErr==0 && !db->mallocFailed ){
  86157. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  86158. /* A minimum of one cursor is required if autoincrement is used
  86159. * See ticket [a696379c1f08866] */
  86160. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  86161. sqlite3VdbeMakeReady(v, pParse);
  86162. pParse->rc = SQLITE_DONE;
  86163. pParse->colNamesSet = 0;
  86164. }else{
  86165. pParse->rc = SQLITE_ERROR;
  86166. }
  86167. pParse->nTab = 0;
  86168. pParse->nMem = 0;
  86169. pParse->nSet = 0;
  86170. pParse->nVar = 0;
  86171. DbMaskZero(pParse->cookieMask);
  86172. }
  86173. /*
  86174. ** Run the parser and code generator recursively in order to generate
  86175. ** code for the SQL statement given onto the end of the pParse context
  86176. ** currently under construction. When the parser is run recursively
  86177. ** this way, the final OP_Halt is not appended and other initialization
  86178. ** and finalization steps are omitted because those are handling by the
  86179. ** outermost parser.
  86180. **
  86181. ** Not everything is nestable. This facility is designed to permit
  86182. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  86183. ** care if you decide to try to use this routine for some other purposes.
  86184. */
  86185. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  86186. va_list ap;
  86187. char *zSql;
  86188. char *zErrMsg = 0;
  86189. sqlite3 *db = pParse->db;
  86190. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  86191. char saveBuf[SAVE_SZ];
  86192. if( pParse->nErr ) return;
  86193. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  86194. va_start(ap, zFormat);
  86195. zSql = sqlite3VMPrintf(db, zFormat, ap);
  86196. va_end(ap);
  86197. if( zSql==0 ){
  86198. return; /* A malloc must have failed */
  86199. }
  86200. pParse->nested++;
  86201. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  86202. memset(&pParse->nVar, 0, SAVE_SZ);
  86203. sqlite3RunParser(pParse, zSql, &zErrMsg);
  86204. sqlite3DbFree(db, zErrMsg);
  86205. sqlite3DbFree(db, zSql);
  86206. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  86207. pParse->nested--;
  86208. }
  86209. #if SQLITE_USER_AUTHENTICATION
  86210. /*
  86211. ** Return TRUE if zTable is the name of the system table that stores the
  86212. ** list of users and their access credentials.
  86213. */
  86214. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  86215. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  86216. }
  86217. #endif
  86218. /*
  86219. ** Locate the in-memory structure that describes a particular database
  86220. ** table given the name of that table and (optionally) the name of the
  86221. ** database containing the table. Return NULL if not found.
  86222. **
  86223. ** If zDatabase is 0, all databases are searched for the table and the
  86224. ** first matching table is returned. (No checking for duplicate table
  86225. ** names is done.) The search order is TEMP first, then MAIN, then any
  86226. ** auxiliary databases added using the ATTACH command.
  86227. **
  86228. ** See also sqlite3LocateTable().
  86229. */
  86230. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  86231. Table *p = 0;
  86232. int i;
  86233. /* All mutexes are required for schema access. Make sure we hold them. */
  86234. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  86235. #if SQLITE_USER_AUTHENTICATION
  86236. /* Only the admin user is allowed to know that the sqlite_user table
  86237. ** exists */
  86238. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  86239. return 0;
  86240. }
  86241. #endif
  86242. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  86243. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  86244. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  86245. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  86246. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  86247. if( p ) break;
  86248. }
  86249. return p;
  86250. }
  86251. /*
  86252. ** Locate the in-memory structure that describes a particular database
  86253. ** table given the name of that table and (optionally) the name of the
  86254. ** database containing the table. Return NULL if not found. Also leave an
  86255. ** error message in pParse->zErrMsg.
  86256. **
  86257. ** The difference between this routine and sqlite3FindTable() is that this
  86258. ** routine leaves an error message in pParse->zErrMsg where
  86259. ** sqlite3FindTable() does not.
  86260. */
  86261. SQLITE_PRIVATE Table *sqlite3LocateTable(
  86262. Parse *pParse, /* context in which to report errors */
  86263. int isView, /* True if looking for a VIEW rather than a TABLE */
  86264. const char *zName, /* Name of the table we are looking for */
  86265. const char *zDbase /* Name of the database. Might be NULL */
  86266. ){
  86267. Table *p;
  86268. /* Read the database schema. If an error occurs, leave an error message
  86269. ** and code in pParse and return NULL. */
  86270. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  86271. return 0;
  86272. }
  86273. p = sqlite3FindTable(pParse->db, zName, zDbase);
  86274. if( p==0 ){
  86275. const char *zMsg = isView ? "no such view" : "no such table";
  86276. if( zDbase ){
  86277. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  86278. }else{
  86279. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  86280. }
  86281. pParse->checkSchema = 1;
  86282. }
  86283. #if SQLITE_USER_AUTHENICATION
  86284. else if( pParse->db->auth.authLevel<UAUTH_User ){
  86285. sqlite3ErrorMsg(pParse, "user not authenticated");
  86286. p = 0;
  86287. }
  86288. #endif
  86289. return p;
  86290. }
  86291. /*
  86292. ** Locate the table identified by *p.
  86293. **
  86294. ** This is a wrapper around sqlite3LocateTable(). The difference between
  86295. ** sqlite3LocateTable() and this function is that this function restricts
  86296. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  86297. ** non-NULL if it is part of a view or trigger program definition. See
  86298. ** sqlite3FixSrcList() for details.
  86299. */
  86300. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  86301. Parse *pParse,
  86302. int isView,
  86303. struct SrcList_item *p
  86304. ){
  86305. const char *zDb;
  86306. assert( p->pSchema==0 || p->zDatabase==0 );
  86307. if( p->pSchema ){
  86308. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  86309. zDb = pParse->db->aDb[iDb].zName;
  86310. }else{
  86311. zDb = p->zDatabase;
  86312. }
  86313. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  86314. }
  86315. /*
  86316. ** Locate the in-memory structure that describes
  86317. ** a particular index given the name of that index
  86318. ** and the name of the database that contains the index.
  86319. ** Return NULL if not found.
  86320. **
  86321. ** If zDatabase is 0, all databases are searched for the
  86322. ** table and the first matching index is returned. (No checking
  86323. ** for duplicate index names is done.) The search order is
  86324. ** TEMP first, then MAIN, then any auxiliary databases added
  86325. ** using the ATTACH command.
  86326. */
  86327. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  86328. Index *p = 0;
  86329. int i;
  86330. /* All mutexes are required for schema access. Make sure we hold them. */
  86331. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  86332. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  86333. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  86334. Schema *pSchema = db->aDb[j].pSchema;
  86335. assert( pSchema );
  86336. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  86337. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  86338. p = sqlite3HashFind(&pSchema->idxHash, zName);
  86339. if( p ) break;
  86340. }
  86341. return p;
  86342. }
  86343. /*
  86344. ** Reclaim the memory used by an index
  86345. */
  86346. static void freeIndex(sqlite3 *db, Index *p){
  86347. #ifndef SQLITE_OMIT_ANALYZE
  86348. sqlite3DeleteIndexSamples(db, p);
  86349. #endif
  86350. sqlite3ExprDelete(db, p->pPartIdxWhere);
  86351. sqlite3DbFree(db, p->zColAff);
  86352. if( p->isResized ) sqlite3DbFree(db, p->azColl);
  86353. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  86354. sqlite3_free(p->aiRowEst);
  86355. #endif
  86356. sqlite3DbFree(db, p);
  86357. }
  86358. /*
  86359. ** For the index called zIdxName which is found in the database iDb,
  86360. ** unlike that index from its Table then remove the index from
  86361. ** the index hash table and free all memory structures associated
  86362. ** with the index.
  86363. */
  86364. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  86365. Index *pIndex;
  86366. Hash *pHash;
  86367. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86368. pHash = &db->aDb[iDb].pSchema->idxHash;
  86369. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  86370. if( ALWAYS(pIndex) ){
  86371. if( pIndex->pTable->pIndex==pIndex ){
  86372. pIndex->pTable->pIndex = pIndex->pNext;
  86373. }else{
  86374. Index *p;
  86375. /* Justification of ALWAYS(); The index must be on the list of
  86376. ** indices. */
  86377. p = pIndex->pTable->pIndex;
  86378. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  86379. if( ALWAYS(p && p->pNext==pIndex) ){
  86380. p->pNext = pIndex->pNext;
  86381. }
  86382. }
  86383. freeIndex(db, pIndex);
  86384. }
  86385. db->flags |= SQLITE_InternChanges;
  86386. }
  86387. /*
  86388. ** Look through the list of open database files in db->aDb[] and if
  86389. ** any have been closed, remove them from the list. Reallocate the
  86390. ** db->aDb[] structure to a smaller size, if possible.
  86391. **
  86392. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  86393. ** are never candidates for being collapsed.
  86394. */
  86395. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  86396. int i, j;
  86397. for(i=j=2; i<db->nDb; i++){
  86398. struct Db *pDb = &db->aDb[i];
  86399. if( pDb->pBt==0 ){
  86400. sqlite3DbFree(db, pDb->zName);
  86401. pDb->zName = 0;
  86402. continue;
  86403. }
  86404. if( j<i ){
  86405. db->aDb[j] = db->aDb[i];
  86406. }
  86407. j++;
  86408. }
  86409. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  86410. db->nDb = j;
  86411. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  86412. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  86413. sqlite3DbFree(db, db->aDb);
  86414. db->aDb = db->aDbStatic;
  86415. }
  86416. }
  86417. /*
  86418. ** Reset the schema for the database at index iDb. Also reset the
  86419. ** TEMP schema.
  86420. */
  86421. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  86422. Db *pDb;
  86423. assert( iDb<db->nDb );
  86424. /* Case 1: Reset the single schema identified by iDb */
  86425. pDb = &db->aDb[iDb];
  86426. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86427. assert( pDb->pSchema!=0 );
  86428. sqlite3SchemaClear(pDb->pSchema);
  86429. /* If any database other than TEMP is reset, then also reset TEMP
  86430. ** since TEMP might be holding triggers that reference tables in the
  86431. ** other database.
  86432. */
  86433. if( iDb!=1 ){
  86434. pDb = &db->aDb[1];
  86435. assert( pDb->pSchema!=0 );
  86436. sqlite3SchemaClear(pDb->pSchema);
  86437. }
  86438. return;
  86439. }
  86440. /*
  86441. ** Erase all schema information from all attached databases (including
  86442. ** "main" and "temp") for a single database connection.
  86443. */
  86444. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  86445. int i;
  86446. sqlite3BtreeEnterAll(db);
  86447. for(i=0; i<db->nDb; i++){
  86448. Db *pDb = &db->aDb[i];
  86449. if( pDb->pSchema ){
  86450. sqlite3SchemaClear(pDb->pSchema);
  86451. }
  86452. }
  86453. db->flags &= ~SQLITE_InternChanges;
  86454. sqlite3VtabUnlockList(db);
  86455. sqlite3BtreeLeaveAll(db);
  86456. sqlite3CollapseDatabaseArray(db);
  86457. }
  86458. /*
  86459. ** This routine is called when a commit occurs.
  86460. */
  86461. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  86462. db->flags &= ~SQLITE_InternChanges;
  86463. }
  86464. /*
  86465. ** Delete memory allocated for the column names of a table or view (the
  86466. ** Table.aCol[] array).
  86467. */
  86468. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  86469. int i;
  86470. Column *pCol;
  86471. assert( pTable!=0 );
  86472. if( (pCol = pTable->aCol)!=0 ){
  86473. for(i=0; i<pTable->nCol; i++, pCol++){
  86474. sqlite3DbFree(db, pCol->zName);
  86475. sqlite3ExprDelete(db, pCol->pDflt);
  86476. sqlite3DbFree(db, pCol->zDflt);
  86477. sqlite3DbFree(db, pCol->zType);
  86478. sqlite3DbFree(db, pCol->zColl);
  86479. }
  86480. sqlite3DbFree(db, pTable->aCol);
  86481. }
  86482. }
  86483. /*
  86484. ** Remove the memory data structures associated with the given
  86485. ** Table. No changes are made to disk by this routine.
  86486. **
  86487. ** This routine just deletes the data structure. It does not unlink
  86488. ** the table data structure from the hash table. But it does destroy
  86489. ** memory structures of the indices and foreign keys associated with
  86490. ** the table.
  86491. **
  86492. ** The db parameter is optional. It is needed if the Table object
  86493. ** contains lookaside memory. (Table objects in the schema do not use
  86494. ** lookaside memory, but some ephemeral Table objects do.) Or the
  86495. ** db parameter can be used with db->pnBytesFreed to measure the memory
  86496. ** used by the Table object.
  86497. */
  86498. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  86499. Index *pIndex, *pNext;
  86500. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  86501. assert( !pTable || pTable->nRef>0 );
  86502. /* Do not delete the table until the reference count reaches zero. */
  86503. if( !pTable ) return;
  86504. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  86505. /* Record the number of outstanding lookaside allocations in schema Tables
  86506. ** prior to doing any free() operations. Since schema Tables do not use
  86507. ** lookaside, this number should not change. */
  86508. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  86509. db->lookaside.nOut : 0 );
  86510. /* Delete all indices associated with this table. */
  86511. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  86512. pNext = pIndex->pNext;
  86513. assert( pIndex->pSchema==pTable->pSchema );
  86514. if( !db || db->pnBytesFreed==0 ){
  86515. char *zName = pIndex->zName;
  86516. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  86517. &pIndex->pSchema->idxHash, zName, 0
  86518. );
  86519. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  86520. assert( pOld==pIndex || pOld==0 );
  86521. }
  86522. freeIndex(db, pIndex);
  86523. }
  86524. /* Delete any foreign keys attached to this table. */
  86525. sqlite3FkDelete(db, pTable);
  86526. /* Delete the Table structure itself.
  86527. */
  86528. sqliteDeleteColumnNames(db, pTable);
  86529. sqlite3DbFree(db, pTable->zName);
  86530. sqlite3DbFree(db, pTable->zColAff);
  86531. sqlite3SelectDelete(db, pTable->pSelect);
  86532. #ifndef SQLITE_OMIT_CHECK
  86533. sqlite3ExprListDelete(db, pTable->pCheck);
  86534. #endif
  86535. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86536. sqlite3VtabClear(db, pTable);
  86537. #endif
  86538. sqlite3DbFree(db, pTable);
  86539. /* Verify that no lookaside memory was used by schema tables */
  86540. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  86541. }
  86542. /*
  86543. ** Unlink the given table from the hash tables and the delete the
  86544. ** table structure with all its indices and foreign keys.
  86545. */
  86546. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  86547. Table *p;
  86548. Db *pDb;
  86549. assert( db!=0 );
  86550. assert( iDb>=0 && iDb<db->nDb );
  86551. assert( zTabName );
  86552. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86553. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  86554. pDb = &db->aDb[iDb];
  86555. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  86556. sqlite3DeleteTable(db, p);
  86557. db->flags |= SQLITE_InternChanges;
  86558. }
  86559. /*
  86560. ** Given a token, return a string that consists of the text of that
  86561. ** token. Space to hold the returned string
  86562. ** is obtained from sqliteMalloc() and must be freed by the calling
  86563. ** function.
  86564. **
  86565. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  86566. ** surround the body of the token are removed.
  86567. **
  86568. ** Tokens are often just pointers into the original SQL text and so
  86569. ** are not \000 terminated and are not persistent. The returned string
  86570. ** is \000 terminated and is persistent.
  86571. */
  86572. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  86573. char *zName;
  86574. if( pName ){
  86575. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  86576. sqlite3Dequote(zName);
  86577. }else{
  86578. zName = 0;
  86579. }
  86580. return zName;
  86581. }
  86582. /*
  86583. ** Open the sqlite_master table stored in database number iDb for
  86584. ** writing. The table is opened using cursor 0.
  86585. */
  86586. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  86587. Vdbe *v = sqlite3GetVdbe(p);
  86588. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  86589. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  86590. if( p->nTab==0 ){
  86591. p->nTab = 1;
  86592. }
  86593. }
  86594. /*
  86595. ** Parameter zName points to a nul-terminated buffer containing the name
  86596. ** of a database ("main", "temp" or the name of an attached db). This
  86597. ** function returns the index of the named database in db->aDb[], or
  86598. ** -1 if the named db cannot be found.
  86599. */
  86600. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  86601. int i = -1; /* Database number */
  86602. if( zName ){
  86603. Db *pDb;
  86604. int n = sqlite3Strlen30(zName);
  86605. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  86606. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  86607. 0==sqlite3StrICmp(pDb->zName, zName) ){
  86608. break;
  86609. }
  86610. }
  86611. }
  86612. return i;
  86613. }
  86614. /*
  86615. ** The token *pName contains the name of a database (either "main" or
  86616. ** "temp" or the name of an attached db). This routine returns the
  86617. ** index of the named database in db->aDb[], or -1 if the named db
  86618. ** does not exist.
  86619. */
  86620. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  86621. int i; /* Database number */
  86622. char *zName; /* Name we are searching for */
  86623. zName = sqlite3NameFromToken(db, pName);
  86624. i = sqlite3FindDbName(db, zName);
  86625. sqlite3DbFree(db, zName);
  86626. return i;
  86627. }
  86628. /* The table or view or trigger name is passed to this routine via tokens
  86629. ** pName1 and pName2. If the table name was fully qualified, for example:
  86630. **
  86631. ** CREATE TABLE xxx.yyy (...);
  86632. **
  86633. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  86634. ** the table name is not fully qualified, i.e.:
  86635. **
  86636. ** CREATE TABLE yyy(...);
  86637. **
  86638. ** Then pName1 is set to "yyy" and pName2 is "".
  86639. **
  86640. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  86641. ** pName2) that stores the unqualified table name. The index of the
  86642. ** database "xxx" is returned.
  86643. */
  86644. SQLITE_PRIVATE int sqlite3TwoPartName(
  86645. Parse *pParse, /* Parsing and code generating context */
  86646. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  86647. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  86648. Token **pUnqual /* Write the unqualified object name here */
  86649. ){
  86650. int iDb; /* Database holding the object */
  86651. sqlite3 *db = pParse->db;
  86652. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  86653. if( db->init.busy ) {
  86654. sqlite3ErrorMsg(pParse, "corrupt database");
  86655. return -1;
  86656. }
  86657. *pUnqual = pName2;
  86658. iDb = sqlite3FindDb(db, pName1);
  86659. if( iDb<0 ){
  86660. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  86661. return -1;
  86662. }
  86663. }else{
  86664. assert( db->init.iDb==0 || db->init.busy );
  86665. iDb = db->init.iDb;
  86666. *pUnqual = pName1;
  86667. }
  86668. return iDb;
  86669. }
  86670. /*
  86671. ** This routine is used to check if the UTF-8 string zName is a legal
  86672. ** unqualified name for a new schema object (table, index, view or
  86673. ** trigger). All names are legal except those that begin with the string
  86674. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  86675. ** is reserved for internal use.
  86676. */
  86677. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  86678. if( !pParse->db->init.busy && pParse->nested==0
  86679. && (pParse->db->flags & SQLITE_WriteSchema)==0
  86680. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  86681. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  86682. return SQLITE_ERROR;
  86683. }
  86684. return SQLITE_OK;
  86685. }
  86686. /*
  86687. ** Return the PRIMARY KEY index of a table
  86688. */
  86689. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  86690. Index *p;
  86691. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  86692. return p;
  86693. }
  86694. /*
  86695. ** Return the column of index pIdx that corresponds to table
  86696. ** column iCol. Return -1 if not found.
  86697. */
  86698. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  86699. int i;
  86700. for(i=0; i<pIdx->nColumn; i++){
  86701. if( iCol==pIdx->aiColumn[i] ) return i;
  86702. }
  86703. return -1;
  86704. }
  86705. /*
  86706. ** Begin constructing a new table representation in memory. This is
  86707. ** the first of several action routines that get called in response
  86708. ** to a CREATE TABLE statement. In particular, this routine is called
  86709. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  86710. ** flag is true if the table should be stored in the auxiliary database
  86711. ** file instead of in the main database file. This is normally the case
  86712. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  86713. ** CREATE and TABLE.
  86714. **
  86715. ** The new table record is initialized and put in pParse->pNewTable.
  86716. ** As more of the CREATE TABLE statement is parsed, additional action
  86717. ** routines will be called to add more information to this record.
  86718. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  86719. ** is called to complete the construction of the new table record.
  86720. */
  86721. SQLITE_PRIVATE void sqlite3StartTable(
  86722. Parse *pParse, /* Parser context */
  86723. Token *pName1, /* First part of the name of the table or view */
  86724. Token *pName2, /* Second part of the name of the table or view */
  86725. int isTemp, /* True if this is a TEMP table */
  86726. int isView, /* True if this is a VIEW */
  86727. int isVirtual, /* True if this is a VIRTUAL table */
  86728. int noErr /* Do nothing if table already exists */
  86729. ){
  86730. Table *pTable;
  86731. char *zName = 0; /* The name of the new table */
  86732. sqlite3 *db = pParse->db;
  86733. Vdbe *v;
  86734. int iDb; /* Database number to create the table in */
  86735. Token *pName; /* Unqualified name of the table to create */
  86736. /* The table or view name to create is passed to this routine via tokens
  86737. ** pName1 and pName2. If the table name was fully qualified, for example:
  86738. **
  86739. ** CREATE TABLE xxx.yyy (...);
  86740. **
  86741. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  86742. ** the table name is not fully qualified, i.e.:
  86743. **
  86744. ** CREATE TABLE yyy(...);
  86745. **
  86746. ** Then pName1 is set to "yyy" and pName2 is "".
  86747. **
  86748. ** The call below sets the pName pointer to point at the token (pName1 or
  86749. ** pName2) that stores the unqualified table name. The variable iDb is
  86750. ** set to the index of the database that the table or view is to be
  86751. ** created in.
  86752. */
  86753. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  86754. if( iDb<0 ) return;
  86755. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  86756. /* If creating a temp table, the name may not be qualified. Unless
  86757. ** the database name is "temp" anyway. */
  86758. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  86759. return;
  86760. }
  86761. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  86762. pParse->sNameToken = *pName;
  86763. zName = sqlite3NameFromToken(db, pName);
  86764. if( zName==0 ) return;
  86765. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  86766. goto begin_table_error;
  86767. }
  86768. if( db->init.iDb==1 ) isTemp = 1;
  86769. #ifndef SQLITE_OMIT_AUTHORIZATION
  86770. assert( (isTemp & 1)==isTemp );
  86771. {
  86772. int code;
  86773. char *zDb = db->aDb[iDb].zName;
  86774. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  86775. goto begin_table_error;
  86776. }
  86777. if( isView ){
  86778. if( !OMIT_TEMPDB && isTemp ){
  86779. code = SQLITE_CREATE_TEMP_VIEW;
  86780. }else{
  86781. code = SQLITE_CREATE_VIEW;
  86782. }
  86783. }else{
  86784. if( !OMIT_TEMPDB && isTemp ){
  86785. code = SQLITE_CREATE_TEMP_TABLE;
  86786. }else{
  86787. code = SQLITE_CREATE_TABLE;
  86788. }
  86789. }
  86790. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  86791. goto begin_table_error;
  86792. }
  86793. }
  86794. #endif
  86795. /* Make sure the new table name does not collide with an existing
  86796. ** index or table name in the same database. Issue an error message if
  86797. ** it does. The exception is if the statement being parsed was passed
  86798. ** to an sqlite3_declare_vtab() call. In that case only the column names
  86799. ** and types will be used, so there is no need to test for namespace
  86800. ** collisions.
  86801. */
  86802. if( !IN_DECLARE_VTAB ){
  86803. char *zDb = db->aDb[iDb].zName;
  86804. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  86805. goto begin_table_error;
  86806. }
  86807. pTable = sqlite3FindTable(db, zName, zDb);
  86808. if( pTable ){
  86809. if( !noErr ){
  86810. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  86811. }else{
  86812. assert( !db->init.busy || CORRUPT_DB );
  86813. sqlite3CodeVerifySchema(pParse, iDb);
  86814. }
  86815. goto begin_table_error;
  86816. }
  86817. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  86818. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  86819. goto begin_table_error;
  86820. }
  86821. }
  86822. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  86823. if( pTable==0 ){
  86824. db->mallocFailed = 1;
  86825. pParse->rc = SQLITE_NOMEM;
  86826. pParse->nErr++;
  86827. goto begin_table_error;
  86828. }
  86829. pTable->zName = zName;
  86830. pTable->iPKey = -1;
  86831. pTable->pSchema = db->aDb[iDb].pSchema;
  86832. pTable->nRef = 1;
  86833. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  86834. assert( pParse->pNewTable==0 );
  86835. pParse->pNewTable = pTable;
  86836. /* If this is the magic sqlite_sequence table used by autoincrement,
  86837. ** then record a pointer to this table in the main database structure
  86838. ** so that INSERT can find the table easily.
  86839. */
  86840. #ifndef SQLITE_OMIT_AUTOINCREMENT
  86841. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  86842. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86843. pTable->pSchema->pSeqTab = pTable;
  86844. }
  86845. #endif
  86846. /* Begin generating the code that will insert the table record into
  86847. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  86848. ** and allocate the record number for the table entry now. Before any
  86849. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  86850. ** indices to be created and the table record must come before the
  86851. ** indices. Hence, the record number for the table must be allocated
  86852. ** now.
  86853. */
  86854. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  86855. int j1;
  86856. int fileFormat;
  86857. int reg1, reg2, reg3;
  86858. sqlite3BeginWriteOperation(pParse, 1, iDb);
  86859. #ifndef SQLITE_OMIT_VIRTUALTABLE
  86860. if( isVirtual ){
  86861. sqlite3VdbeAddOp0(v, OP_VBegin);
  86862. }
  86863. #endif
  86864. /* If the file format and encoding in the database have not been set,
  86865. ** set them now.
  86866. */
  86867. reg1 = pParse->regRowid = ++pParse->nMem;
  86868. reg2 = pParse->regRoot = ++pParse->nMem;
  86869. reg3 = ++pParse->nMem;
  86870. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  86871. sqlite3VdbeUsesBtree(v, iDb);
  86872. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  86873. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  86874. 1 : SQLITE_MAX_FILE_FORMAT;
  86875. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  86876. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  86877. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  86878. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  86879. sqlite3VdbeJumpHere(v, j1);
  86880. /* This just creates a place-holder record in the sqlite_master table.
  86881. ** The record created does not contain anything yet. It will be replaced
  86882. ** by the real entry in code generated at sqlite3EndTable().
  86883. **
  86884. ** The rowid for the new entry is left in register pParse->regRowid.
  86885. ** The root page number of the new table is left in reg pParse->regRoot.
  86886. ** The rowid and root page number values are needed by the code that
  86887. ** sqlite3EndTable will generate.
  86888. */
  86889. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  86890. if( isView || isVirtual ){
  86891. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  86892. }else
  86893. #endif
  86894. {
  86895. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  86896. }
  86897. sqlite3OpenMasterTable(pParse, iDb);
  86898. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  86899. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  86900. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  86901. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  86902. sqlite3VdbeAddOp0(v, OP_Close);
  86903. }
  86904. /* Normal (non-error) return. */
  86905. return;
  86906. /* If an error occurs, we jump here */
  86907. begin_table_error:
  86908. sqlite3DbFree(db, zName);
  86909. return;
  86910. }
  86911. /*
  86912. ** This macro is used to compare two strings in a case-insensitive manner.
  86913. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  86914. ** produces larger code.
  86915. **
  86916. ** WARNING: This macro is not compatible with the strcmp() family. It
  86917. ** returns true if the two strings are equal, otherwise false.
  86918. */
  86919. #define STRICMP(x, y) (\
  86920. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  86921. sqlite3UpperToLower[*(unsigned char *)(y)] \
  86922. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  86923. /*
  86924. ** Add a new column to the table currently being constructed.
  86925. **
  86926. ** The parser calls this routine once for each column declaration
  86927. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  86928. ** first to get things going. Then this routine is called for each
  86929. ** column.
  86930. */
  86931. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  86932. Table *p;
  86933. int i;
  86934. char *z;
  86935. Column *pCol;
  86936. sqlite3 *db = pParse->db;
  86937. if( (p = pParse->pNewTable)==0 ) return;
  86938. #if SQLITE_MAX_COLUMN
  86939. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  86940. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  86941. return;
  86942. }
  86943. #endif
  86944. z = sqlite3NameFromToken(db, pName);
  86945. if( z==0 ) return;
  86946. for(i=0; i<p->nCol; i++){
  86947. if( STRICMP(z, p->aCol[i].zName) ){
  86948. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  86949. sqlite3DbFree(db, z);
  86950. return;
  86951. }
  86952. }
  86953. if( (p->nCol & 0x7)==0 ){
  86954. Column *aNew;
  86955. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  86956. if( aNew==0 ){
  86957. sqlite3DbFree(db, z);
  86958. return;
  86959. }
  86960. p->aCol = aNew;
  86961. }
  86962. pCol = &p->aCol[p->nCol];
  86963. memset(pCol, 0, sizeof(p->aCol[0]));
  86964. pCol->zName = z;
  86965. /* If there is no type specified, columns have the default affinity
  86966. ** 'BLOB'. If there is a type specified, then sqlite3AddColumnType() will
  86967. ** be called next to set pCol->affinity correctly.
  86968. */
  86969. pCol->affinity = SQLITE_AFF_BLOB;
  86970. pCol->szEst = 1;
  86971. p->nCol++;
  86972. }
  86973. /*
  86974. ** This routine is called by the parser while in the middle of
  86975. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  86976. ** been seen on a column. This routine sets the notNull flag on
  86977. ** the column currently under construction.
  86978. */
  86979. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  86980. Table *p;
  86981. p = pParse->pNewTable;
  86982. if( p==0 || NEVER(p->nCol<1) ) return;
  86983. p->aCol[p->nCol-1].notNull = (u8)onError;
  86984. }
  86985. /*
  86986. ** Scan the column type name zType (length nType) and return the
  86987. ** associated affinity type.
  86988. **
  86989. ** This routine does a case-independent search of zType for the
  86990. ** substrings in the following table. If one of the substrings is
  86991. ** found, the corresponding affinity is returned. If zType contains
  86992. ** more than one of the substrings, entries toward the top of
  86993. ** the table take priority. For example, if zType is 'BLOBINT',
  86994. ** SQLITE_AFF_INTEGER is returned.
  86995. **
  86996. ** Substring | Affinity
  86997. ** --------------------------------
  86998. ** 'INT' | SQLITE_AFF_INTEGER
  86999. ** 'CHAR' | SQLITE_AFF_TEXT
  87000. ** 'CLOB' | SQLITE_AFF_TEXT
  87001. ** 'TEXT' | SQLITE_AFF_TEXT
  87002. ** 'BLOB' | SQLITE_AFF_BLOB
  87003. ** 'REAL' | SQLITE_AFF_REAL
  87004. ** 'FLOA' | SQLITE_AFF_REAL
  87005. ** 'DOUB' | SQLITE_AFF_REAL
  87006. **
  87007. ** If none of the substrings in the above table are found,
  87008. ** SQLITE_AFF_NUMERIC is returned.
  87009. */
  87010. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  87011. u32 h = 0;
  87012. char aff = SQLITE_AFF_NUMERIC;
  87013. const char *zChar = 0;
  87014. if( zIn==0 ) return aff;
  87015. while( zIn[0] ){
  87016. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  87017. zIn++;
  87018. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  87019. aff = SQLITE_AFF_TEXT;
  87020. zChar = zIn;
  87021. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  87022. aff = SQLITE_AFF_TEXT;
  87023. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  87024. aff = SQLITE_AFF_TEXT;
  87025. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  87026. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  87027. aff = SQLITE_AFF_BLOB;
  87028. if( zIn[0]=='(' ) zChar = zIn;
  87029. #ifndef SQLITE_OMIT_FLOATING_POINT
  87030. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  87031. && aff==SQLITE_AFF_NUMERIC ){
  87032. aff = SQLITE_AFF_REAL;
  87033. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  87034. && aff==SQLITE_AFF_NUMERIC ){
  87035. aff = SQLITE_AFF_REAL;
  87036. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  87037. && aff==SQLITE_AFF_NUMERIC ){
  87038. aff = SQLITE_AFF_REAL;
  87039. #endif
  87040. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  87041. aff = SQLITE_AFF_INTEGER;
  87042. break;
  87043. }
  87044. }
  87045. /* If pszEst is not NULL, store an estimate of the field size. The
  87046. ** estimate is scaled so that the size of an integer is 1. */
  87047. if( pszEst ){
  87048. *pszEst = 1; /* default size is approx 4 bytes */
  87049. if( aff<SQLITE_AFF_NUMERIC ){
  87050. if( zChar ){
  87051. while( zChar[0] ){
  87052. if( sqlite3Isdigit(zChar[0]) ){
  87053. int v = 0;
  87054. sqlite3GetInt32(zChar, &v);
  87055. v = v/4 + 1;
  87056. if( v>255 ) v = 255;
  87057. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  87058. break;
  87059. }
  87060. zChar++;
  87061. }
  87062. }else{
  87063. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  87064. }
  87065. }
  87066. }
  87067. return aff;
  87068. }
  87069. /*
  87070. ** This routine is called by the parser while in the middle of
  87071. ** parsing a CREATE TABLE statement. The pFirst token is the first
  87072. ** token in the sequence of tokens that describe the type of the
  87073. ** column currently under construction. pLast is the last token
  87074. ** in the sequence. Use this information to construct a string
  87075. ** that contains the typename of the column and store that string
  87076. ** in zType.
  87077. */
  87078. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  87079. Table *p;
  87080. Column *pCol;
  87081. p = pParse->pNewTable;
  87082. if( p==0 || NEVER(p->nCol<1) ) return;
  87083. pCol = &p->aCol[p->nCol-1];
  87084. assert( pCol->zType==0 || CORRUPT_DB );
  87085. sqlite3DbFree(pParse->db, pCol->zType);
  87086. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  87087. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  87088. }
  87089. /*
  87090. ** The expression is the default value for the most recently added column
  87091. ** of the table currently under construction.
  87092. **
  87093. ** Default value expressions must be constant. Raise an exception if this
  87094. ** is not the case.
  87095. **
  87096. ** This routine is called by the parser while in the middle of
  87097. ** parsing a CREATE TABLE statement.
  87098. */
  87099. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  87100. Table *p;
  87101. Column *pCol;
  87102. sqlite3 *db = pParse->db;
  87103. p = pParse->pNewTable;
  87104. if( p!=0 ){
  87105. pCol = &(p->aCol[p->nCol-1]);
  87106. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  87107. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  87108. pCol->zName);
  87109. }else{
  87110. /* A copy of pExpr is used instead of the original, as pExpr contains
  87111. ** tokens that point to volatile memory. The 'span' of the expression
  87112. ** is required by pragma table_info.
  87113. */
  87114. sqlite3ExprDelete(db, pCol->pDflt);
  87115. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  87116. sqlite3DbFree(db, pCol->zDflt);
  87117. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  87118. (int)(pSpan->zEnd - pSpan->zStart));
  87119. }
  87120. }
  87121. sqlite3ExprDelete(db, pSpan->pExpr);
  87122. }
  87123. /*
  87124. ** Designate the PRIMARY KEY for the table. pList is a list of names
  87125. ** of columns that form the primary key. If pList is NULL, then the
  87126. ** most recently added column of the table is the primary key.
  87127. **
  87128. ** A table can have at most one primary key. If the table already has
  87129. ** a primary key (and this is the second primary key) then create an
  87130. ** error.
  87131. **
  87132. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  87133. ** then we will try to use that column as the rowid. Set the Table.iPKey
  87134. ** field of the table under construction to be the index of the
  87135. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  87136. ** no INTEGER PRIMARY KEY.
  87137. **
  87138. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  87139. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  87140. */
  87141. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  87142. Parse *pParse, /* Parsing context */
  87143. ExprList *pList, /* List of field names to be indexed */
  87144. int onError, /* What to do with a uniqueness conflict */
  87145. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  87146. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  87147. ){
  87148. Table *pTab = pParse->pNewTable;
  87149. char *zType = 0;
  87150. int iCol = -1, i;
  87151. int nTerm;
  87152. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  87153. if( pTab->tabFlags & TF_HasPrimaryKey ){
  87154. sqlite3ErrorMsg(pParse,
  87155. "table \"%s\" has more than one primary key", pTab->zName);
  87156. goto primary_key_exit;
  87157. }
  87158. pTab->tabFlags |= TF_HasPrimaryKey;
  87159. if( pList==0 ){
  87160. iCol = pTab->nCol - 1;
  87161. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  87162. zType = pTab->aCol[iCol].zType;
  87163. nTerm = 1;
  87164. }else{
  87165. nTerm = pList->nExpr;
  87166. for(i=0; i<nTerm; i++){
  87167. for(iCol=0; iCol<pTab->nCol; iCol++){
  87168. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  87169. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  87170. zType = pTab->aCol[iCol].zType;
  87171. break;
  87172. }
  87173. }
  87174. }
  87175. }
  87176. if( nTerm==1
  87177. && zType && sqlite3StrICmp(zType, "INTEGER")==0
  87178. && sortOrder==SQLITE_SO_ASC
  87179. ){
  87180. pTab->iPKey = iCol;
  87181. pTab->keyConf = (u8)onError;
  87182. assert( autoInc==0 || autoInc==1 );
  87183. pTab->tabFlags |= autoInc*TF_Autoincrement;
  87184. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  87185. }else if( autoInc ){
  87186. #ifndef SQLITE_OMIT_AUTOINCREMENT
  87187. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  87188. "INTEGER PRIMARY KEY");
  87189. #endif
  87190. }else{
  87191. Index *p;
  87192. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  87193. 0, sortOrder, 0);
  87194. if( p ){
  87195. p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  87196. }
  87197. pList = 0;
  87198. }
  87199. primary_key_exit:
  87200. sqlite3ExprListDelete(pParse->db, pList);
  87201. return;
  87202. }
  87203. /*
  87204. ** Add a new CHECK constraint to the table currently under construction.
  87205. */
  87206. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  87207. Parse *pParse, /* Parsing context */
  87208. Expr *pCheckExpr /* The check expression */
  87209. ){
  87210. #ifndef SQLITE_OMIT_CHECK
  87211. Table *pTab = pParse->pNewTable;
  87212. sqlite3 *db = pParse->db;
  87213. if( pTab && !IN_DECLARE_VTAB
  87214. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  87215. ){
  87216. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  87217. if( pParse->constraintName.n ){
  87218. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  87219. }
  87220. }else
  87221. #endif
  87222. {
  87223. sqlite3ExprDelete(pParse->db, pCheckExpr);
  87224. }
  87225. }
  87226. /*
  87227. ** Set the collation function of the most recently parsed table column
  87228. ** to the CollSeq given.
  87229. */
  87230. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  87231. Table *p;
  87232. int i;
  87233. char *zColl; /* Dequoted name of collation sequence */
  87234. sqlite3 *db;
  87235. if( (p = pParse->pNewTable)==0 ) return;
  87236. i = p->nCol-1;
  87237. db = pParse->db;
  87238. zColl = sqlite3NameFromToken(db, pToken);
  87239. if( !zColl ) return;
  87240. if( sqlite3LocateCollSeq(pParse, zColl) ){
  87241. Index *pIdx;
  87242. sqlite3DbFree(db, p->aCol[i].zColl);
  87243. p->aCol[i].zColl = zColl;
  87244. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  87245. ** then an index may have been created on this column before the
  87246. ** collation type was added. Correct this if it is the case.
  87247. */
  87248. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  87249. assert( pIdx->nKeyCol==1 );
  87250. if( pIdx->aiColumn[0]==i ){
  87251. pIdx->azColl[0] = p->aCol[i].zColl;
  87252. }
  87253. }
  87254. }else{
  87255. sqlite3DbFree(db, zColl);
  87256. }
  87257. }
  87258. /*
  87259. ** This function returns the collation sequence for database native text
  87260. ** encoding identified by the string zName, length nName.
  87261. **
  87262. ** If the requested collation sequence is not available, or not available
  87263. ** in the database native encoding, the collation factory is invoked to
  87264. ** request it. If the collation factory does not supply such a sequence,
  87265. ** and the sequence is available in another text encoding, then that is
  87266. ** returned instead.
  87267. **
  87268. ** If no versions of the requested collations sequence are available, or
  87269. ** another error occurs, NULL is returned and an error message written into
  87270. ** pParse.
  87271. **
  87272. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  87273. ** invokes the collation factory if the named collation cannot be found
  87274. ** and generates an error message.
  87275. **
  87276. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  87277. */
  87278. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  87279. sqlite3 *db = pParse->db;
  87280. u8 enc = ENC(db);
  87281. u8 initbusy = db->init.busy;
  87282. CollSeq *pColl;
  87283. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  87284. if( !initbusy && (!pColl || !pColl->xCmp) ){
  87285. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  87286. }
  87287. return pColl;
  87288. }
  87289. /*
  87290. ** Generate code that will increment the schema cookie.
  87291. **
  87292. ** The schema cookie is used to determine when the schema for the
  87293. ** database changes. After each schema change, the cookie value
  87294. ** changes. When a process first reads the schema it records the
  87295. ** cookie. Thereafter, whenever it goes to access the database,
  87296. ** it checks the cookie to make sure the schema has not changed
  87297. ** since it was last read.
  87298. **
  87299. ** This plan is not completely bullet-proof. It is possible for
  87300. ** the schema to change multiple times and for the cookie to be
  87301. ** set back to prior value. But schema changes are infrequent
  87302. ** and the probability of hitting the same cookie value is only
  87303. ** 1 chance in 2^32. So we're safe enough.
  87304. */
  87305. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  87306. int r1 = sqlite3GetTempReg(pParse);
  87307. sqlite3 *db = pParse->db;
  87308. Vdbe *v = pParse->pVdbe;
  87309. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87310. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  87311. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  87312. sqlite3ReleaseTempReg(pParse, r1);
  87313. }
  87314. /*
  87315. ** Measure the number of characters needed to output the given
  87316. ** identifier. The number returned includes any quotes used
  87317. ** but does not include the null terminator.
  87318. **
  87319. ** The estimate is conservative. It might be larger that what is
  87320. ** really needed.
  87321. */
  87322. static int identLength(const char *z){
  87323. int n;
  87324. for(n=0; *z; n++, z++){
  87325. if( *z=='"' ){ n++; }
  87326. }
  87327. return n + 2;
  87328. }
  87329. /*
  87330. ** The first parameter is a pointer to an output buffer. The second
  87331. ** parameter is a pointer to an integer that contains the offset at
  87332. ** which to write into the output buffer. This function copies the
  87333. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  87334. ** to the specified offset in the buffer and updates *pIdx to refer
  87335. ** to the first byte after the last byte written before returning.
  87336. **
  87337. ** If the string zSignedIdent consists entirely of alpha-numeric
  87338. ** characters, does not begin with a digit and is not an SQL keyword,
  87339. ** then it is copied to the output buffer exactly as it is. Otherwise,
  87340. ** it is quoted using double-quotes.
  87341. */
  87342. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  87343. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  87344. int i, j, needQuote;
  87345. i = *pIdx;
  87346. for(j=0; zIdent[j]; j++){
  87347. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  87348. }
  87349. needQuote = sqlite3Isdigit(zIdent[0])
  87350. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  87351. || zIdent[j]!=0
  87352. || j==0;
  87353. if( needQuote ) z[i++] = '"';
  87354. for(j=0; zIdent[j]; j++){
  87355. z[i++] = zIdent[j];
  87356. if( zIdent[j]=='"' ) z[i++] = '"';
  87357. }
  87358. if( needQuote ) z[i++] = '"';
  87359. z[i] = 0;
  87360. *pIdx = i;
  87361. }
  87362. /*
  87363. ** Generate a CREATE TABLE statement appropriate for the given
  87364. ** table. Memory to hold the text of the statement is obtained
  87365. ** from sqliteMalloc() and must be freed by the calling function.
  87366. */
  87367. static char *createTableStmt(sqlite3 *db, Table *p){
  87368. int i, k, n;
  87369. char *zStmt;
  87370. char *zSep, *zSep2, *zEnd;
  87371. Column *pCol;
  87372. n = 0;
  87373. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  87374. n += identLength(pCol->zName) + 5;
  87375. }
  87376. n += identLength(p->zName);
  87377. if( n<50 ){
  87378. zSep = "";
  87379. zSep2 = ",";
  87380. zEnd = ")";
  87381. }else{
  87382. zSep = "\n ";
  87383. zSep2 = ",\n ";
  87384. zEnd = "\n)";
  87385. }
  87386. n += 35 + 6*p->nCol;
  87387. zStmt = sqlite3DbMallocRaw(0, n);
  87388. if( zStmt==0 ){
  87389. db->mallocFailed = 1;
  87390. return 0;
  87391. }
  87392. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  87393. k = sqlite3Strlen30(zStmt);
  87394. identPut(zStmt, &k, p->zName);
  87395. zStmt[k++] = '(';
  87396. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  87397. static const char * const azType[] = {
  87398. /* SQLITE_AFF_BLOB */ "",
  87399. /* SQLITE_AFF_TEXT */ " TEXT",
  87400. /* SQLITE_AFF_NUMERIC */ " NUM",
  87401. /* SQLITE_AFF_INTEGER */ " INT",
  87402. /* SQLITE_AFF_REAL */ " REAL"
  87403. };
  87404. int len;
  87405. const char *zType;
  87406. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  87407. k += sqlite3Strlen30(&zStmt[k]);
  87408. zSep = zSep2;
  87409. identPut(zStmt, &k, pCol->zName);
  87410. assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
  87411. assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
  87412. testcase( pCol->affinity==SQLITE_AFF_BLOB );
  87413. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  87414. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  87415. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  87416. testcase( pCol->affinity==SQLITE_AFF_REAL );
  87417. zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
  87418. len = sqlite3Strlen30(zType);
  87419. assert( pCol->affinity==SQLITE_AFF_BLOB
  87420. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  87421. memcpy(&zStmt[k], zType, len);
  87422. k += len;
  87423. assert( k<=n );
  87424. }
  87425. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  87426. return zStmt;
  87427. }
  87428. /*
  87429. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  87430. ** on success and SQLITE_NOMEM on an OOM error.
  87431. */
  87432. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  87433. char *zExtra;
  87434. int nByte;
  87435. if( pIdx->nColumn>=N ) return SQLITE_OK;
  87436. assert( pIdx->isResized==0 );
  87437. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  87438. zExtra = sqlite3DbMallocZero(db, nByte);
  87439. if( zExtra==0 ) return SQLITE_NOMEM;
  87440. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  87441. pIdx->azColl = (char**)zExtra;
  87442. zExtra += sizeof(char*)*N;
  87443. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  87444. pIdx->aiColumn = (i16*)zExtra;
  87445. zExtra += sizeof(i16)*N;
  87446. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  87447. pIdx->aSortOrder = (u8*)zExtra;
  87448. pIdx->nColumn = N;
  87449. pIdx->isResized = 1;
  87450. return SQLITE_OK;
  87451. }
  87452. /*
  87453. ** Estimate the total row width for a table.
  87454. */
  87455. static void estimateTableWidth(Table *pTab){
  87456. unsigned wTable = 0;
  87457. const Column *pTabCol;
  87458. int i;
  87459. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  87460. wTable += pTabCol->szEst;
  87461. }
  87462. if( pTab->iPKey<0 ) wTable++;
  87463. pTab->szTabRow = sqlite3LogEst(wTable*4);
  87464. }
  87465. /*
  87466. ** Estimate the average size of a row for an index.
  87467. */
  87468. static void estimateIndexWidth(Index *pIdx){
  87469. unsigned wIndex = 0;
  87470. int i;
  87471. const Column *aCol = pIdx->pTable->aCol;
  87472. for(i=0; i<pIdx->nColumn; i++){
  87473. i16 x = pIdx->aiColumn[i];
  87474. assert( x<pIdx->pTable->nCol );
  87475. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  87476. }
  87477. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  87478. }
  87479. /* Return true if value x is found any of the first nCol entries of aiCol[]
  87480. */
  87481. static int hasColumn(const i16 *aiCol, int nCol, int x){
  87482. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  87483. return 0;
  87484. }
  87485. /*
  87486. ** This routine runs at the end of parsing a CREATE TABLE statement that
  87487. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  87488. ** internal schema data structures and the generated VDBE code so that they
  87489. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  87490. ** Changes include:
  87491. **
  87492. ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
  87493. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  87494. ** data storage is a covering index btree.
  87495. ** (2) Bypass the creation of the sqlite_master table entry
  87496. ** for the PRIMARY KEY as the primary key index is now
  87497. ** identified by the sqlite_master table entry of the table itself.
  87498. ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
  87499. ** schema to the rootpage from the main table.
  87500. ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  87501. ** (5) Add all table columns to the PRIMARY KEY Index object
  87502. ** so that the PRIMARY KEY is a covering index. The surplus
  87503. ** columns are part of KeyInfo.nXField and are not used for
  87504. ** sorting or lookup or uniqueness checks.
  87505. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  87506. ** indices with the PRIMARY KEY columns.
  87507. */
  87508. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  87509. Index *pIdx;
  87510. Index *pPk;
  87511. int nPk;
  87512. int i, j;
  87513. sqlite3 *db = pParse->db;
  87514. Vdbe *v = pParse->pVdbe;
  87515. /* Convert the OP_CreateTable opcode that would normally create the
  87516. ** root-page for the table into an OP_CreateIndex opcode. The index
  87517. ** created will become the PRIMARY KEY index.
  87518. */
  87519. if( pParse->addrCrTab ){
  87520. assert( v );
  87521. sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
  87522. }
  87523. /* Locate the PRIMARY KEY index. Or, if this table was originally
  87524. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  87525. */
  87526. if( pTab->iPKey>=0 ){
  87527. ExprList *pList;
  87528. pList = sqlite3ExprListAppend(pParse, 0, 0);
  87529. if( pList==0 ) return;
  87530. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  87531. pTab->aCol[pTab->iPKey].zName);
  87532. pList->a[0].sortOrder = pParse->iPkSortOrder;
  87533. assert( pParse->pNewTable==pTab );
  87534. pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  87535. if( pPk==0 ) return;
  87536. pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  87537. pTab->iPKey = -1;
  87538. }else{
  87539. pPk = sqlite3PrimaryKeyIndex(pTab);
  87540. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  87541. ** table entry. This is only required if currently generating VDBE
  87542. ** code for a CREATE TABLE (not when parsing one as part of reading
  87543. ** a database schema). */
  87544. if( v ){
  87545. assert( db->init.busy==0 );
  87546. sqlite3VdbeGetOp(v, pPk->tnum)->opcode = OP_Goto;
  87547. }
  87548. /*
  87549. ** Remove all redundant columns from the PRIMARY KEY. For example, change
  87550. ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
  87551. ** code assumes the PRIMARY KEY contains no repeated columns.
  87552. */
  87553. for(i=j=1; i<pPk->nKeyCol; i++){
  87554. if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
  87555. pPk->nColumn--;
  87556. }else{
  87557. pPk->aiColumn[j++] = pPk->aiColumn[i];
  87558. }
  87559. }
  87560. pPk->nKeyCol = j;
  87561. }
  87562. pPk->isCovering = 1;
  87563. assert( pPk!=0 );
  87564. nPk = pPk->nKeyCol;
  87565. /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
  87566. ** do not enforce this for imposter tables.) */
  87567. if( !db->init.imposterTable ){
  87568. for(i=0; i<nPk; i++){
  87569. pTab->aCol[pPk->aiColumn[i]].notNull = 1;
  87570. }
  87571. pPk->uniqNotNull = 1;
  87572. }
  87573. /* The root page of the PRIMARY KEY is the table root page */
  87574. pPk->tnum = pTab->tnum;
  87575. /* Update the in-memory representation of all UNIQUE indices by converting
  87576. ** the final rowid column into one or more columns of the PRIMARY KEY.
  87577. */
  87578. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87579. int n;
  87580. if( IsPrimaryKeyIndex(pIdx) ) continue;
  87581. for(i=n=0; i<nPk; i++){
  87582. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  87583. }
  87584. if( n==0 ){
  87585. /* This index is a superset of the primary key */
  87586. pIdx->nColumn = pIdx->nKeyCol;
  87587. continue;
  87588. }
  87589. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  87590. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  87591. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  87592. pIdx->aiColumn[j] = pPk->aiColumn[i];
  87593. pIdx->azColl[j] = pPk->azColl[i];
  87594. j++;
  87595. }
  87596. }
  87597. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  87598. assert( pIdx->nColumn>=j );
  87599. }
  87600. /* Add all table columns to the PRIMARY KEY index
  87601. */
  87602. if( nPk<pTab->nCol ){
  87603. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  87604. for(i=0, j=nPk; i<pTab->nCol; i++){
  87605. if( !hasColumn(pPk->aiColumn, j, i) ){
  87606. assert( j<pPk->nColumn );
  87607. pPk->aiColumn[j] = i;
  87608. pPk->azColl[j] = "BINARY";
  87609. j++;
  87610. }
  87611. }
  87612. assert( pPk->nColumn==j );
  87613. assert( pTab->nCol==j );
  87614. }else{
  87615. pPk->nColumn = pTab->nCol;
  87616. }
  87617. }
  87618. /*
  87619. ** This routine is called to report the final ")" that terminates
  87620. ** a CREATE TABLE statement.
  87621. **
  87622. ** The table structure that other action routines have been building
  87623. ** is added to the internal hash tables, assuming no errors have
  87624. ** occurred.
  87625. **
  87626. ** An entry for the table is made in the master table on disk, unless
  87627. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  87628. ** it means we are reading the sqlite_master table because we just
  87629. ** connected to the database or because the sqlite_master table has
  87630. ** recently changed, so the entry for this table already exists in
  87631. ** the sqlite_master table. We do not want to create it again.
  87632. **
  87633. ** If the pSelect argument is not NULL, it means that this routine
  87634. ** was called to create a table generated from a
  87635. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  87636. ** the new table will match the result set of the SELECT.
  87637. */
  87638. SQLITE_PRIVATE void sqlite3EndTable(
  87639. Parse *pParse, /* Parse context */
  87640. Token *pCons, /* The ',' token after the last column defn. */
  87641. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  87642. u8 tabOpts, /* Extra table options. Usually 0. */
  87643. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  87644. ){
  87645. Table *p; /* The new table */
  87646. sqlite3 *db = pParse->db; /* The database connection */
  87647. int iDb; /* Database in which the table lives */
  87648. Index *pIdx; /* An implied index of the table */
  87649. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  87650. return;
  87651. }
  87652. p = pParse->pNewTable;
  87653. if( p==0 ) return;
  87654. assert( !db->init.busy || !pSelect );
  87655. /* If the db->init.busy is 1 it means we are reading the SQL off the
  87656. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  87657. ** So do not write to the disk again. Extract the root page number
  87658. ** for the table from the db->init.newTnum field. (The page number
  87659. ** should have been put there by the sqliteOpenCb routine.)
  87660. */
  87661. if( db->init.busy ){
  87662. p->tnum = db->init.newTnum;
  87663. }
  87664. /* Special processing for WITHOUT ROWID Tables */
  87665. if( tabOpts & TF_WithoutRowid ){
  87666. if( (p->tabFlags & TF_Autoincrement) ){
  87667. sqlite3ErrorMsg(pParse,
  87668. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  87669. return;
  87670. }
  87671. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  87672. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  87673. }else{
  87674. p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
  87675. convertToWithoutRowidTable(pParse, p);
  87676. }
  87677. }
  87678. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  87679. #ifndef SQLITE_OMIT_CHECK
  87680. /* Resolve names in all CHECK constraint expressions.
  87681. */
  87682. if( p->pCheck ){
  87683. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  87684. }
  87685. #endif /* !defined(SQLITE_OMIT_CHECK) */
  87686. /* Estimate the average row size for the table and for all implied indices */
  87687. estimateTableWidth(p);
  87688. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  87689. estimateIndexWidth(pIdx);
  87690. }
  87691. /* If not initializing, then create a record for the new table
  87692. ** in the SQLITE_MASTER table of the database.
  87693. **
  87694. ** If this is a TEMPORARY table, write the entry into the auxiliary
  87695. ** file instead of into the main database file.
  87696. */
  87697. if( !db->init.busy ){
  87698. int n;
  87699. Vdbe *v;
  87700. char *zType; /* "view" or "table" */
  87701. char *zType2; /* "VIEW" or "TABLE" */
  87702. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  87703. v = sqlite3GetVdbe(pParse);
  87704. if( NEVER(v==0) ) return;
  87705. sqlite3VdbeAddOp1(v, OP_Close, 0);
  87706. /*
  87707. ** Initialize zType for the new view or table.
  87708. */
  87709. if( p->pSelect==0 ){
  87710. /* A regular table */
  87711. zType = "table";
  87712. zType2 = "TABLE";
  87713. #ifndef SQLITE_OMIT_VIEW
  87714. }else{
  87715. /* A view */
  87716. zType = "view";
  87717. zType2 = "VIEW";
  87718. #endif
  87719. }
  87720. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  87721. ** statement to populate the new table. The root-page number for the
  87722. ** new table is in register pParse->regRoot.
  87723. **
  87724. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  87725. ** suitable state to query for the column names and types to be used
  87726. ** by the new table.
  87727. **
  87728. ** A shared-cache write-lock is not required to write to the new table,
  87729. ** as a schema-lock must have already been obtained to create it. Since
  87730. ** a schema-lock excludes all other database users, the write-lock would
  87731. ** be redundant.
  87732. */
  87733. if( pSelect ){
  87734. SelectDest dest; /* Where the SELECT should store results */
  87735. int regYield; /* Register holding co-routine entry-point */
  87736. int addrTop; /* Top of the co-routine */
  87737. int regRec; /* A record to be insert into the new table */
  87738. int regRowid; /* Rowid of the next row to insert */
  87739. int addrInsLoop; /* Top of the loop for inserting rows */
  87740. Table *pSelTab; /* A table that describes the SELECT results */
  87741. regYield = ++pParse->nMem;
  87742. regRec = ++pParse->nMem;
  87743. regRowid = ++pParse->nMem;
  87744. assert(pParse->nTab==1);
  87745. sqlite3MayAbort(pParse);
  87746. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  87747. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  87748. pParse->nTab = 2;
  87749. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  87750. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  87751. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  87752. sqlite3Select(pParse, pSelect, &dest);
  87753. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  87754. sqlite3VdbeJumpHere(v, addrTop - 1);
  87755. if( pParse->nErr ) return;
  87756. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  87757. if( pSelTab==0 ) return;
  87758. assert( p->aCol==0 );
  87759. p->nCol = pSelTab->nCol;
  87760. p->aCol = pSelTab->aCol;
  87761. pSelTab->nCol = 0;
  87762. pSelTab->aCol = 0;
  87763. sqlite3DeleteTable(db, pSelTab);
  87764. addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  87765. VdbeCoverage(v);
  87766. sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
  87767. sqlite3TableAffinity(v, p, 0);
  87768. sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
  87769. sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
  87770. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInsLoop);
  87771. sqlite3VdbeJumpHere(v, addrInsLoop);
  87772. sqlite3VdbeAddOp1(v, OP_Close, 1);
  87773. }
  87774. /* Compute the complete text of the CREATE statement */
  87775. if( pSelect ){
  87776. zStmt = createTableStmt(db, p);
  87777. }else{
  87778. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  87779. n = (int)(pEnd2->z - pParse->sNameToken.z);
  87780. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  87781. zStmt = sqlite3MPrintf(db,
  87782. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  87783. );
  87784. }
  87785. /* A slot for the record has already been allocated in the
  87786. ** SQLITE_MASTER table. We just need to update that slot with all
  87787. ** the information we've collected.
  87788. */
  87789. sqlite3NestedParse(pParse,
  87790. "UPDATE %Q.%s "
  87791. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  87792. "WHERE rowid=#%d",
  87793. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  87794. zType,
  87795. p->zName,
  87796. p->zName,
  87797. pParse->regRoot,
  87798. zStmt,
  87799. pParse->regRowid
  87800. );
  87801. sqlite3DbFree(db, zStmt);
  87802. sqlite3ChangeCookie(pParse, iDb);
  87803. #ifndef SQLITE_OMIT_AUTOINCREMENT
  87804. /* Check to see if we need to create an sqlite_sequence table for
  87805. ** keeping track of autoincrement keys.
  87806. */
  87807. if( p->tabFlags & TF_Autoincrement ){
  87808. Db *pDb = &db->aDb[iDb];
  87809. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87810. if( pDb->pSchema->pSeqTab==0 ){
  87811. sqlite3NestedParse(pParse,
  87812. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  87813. pDb->zName
  87814. );
  87815. }
  87816. }
  87817. #endif
  87818. /* Reparse everything to update our internal data structures */
  87819. sqlite3VdbeAddParseSchemaOp(v, iDb,
  87820. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  87821. }
  87822. /* Add the table to the in-memory representation of the database.
  87823. */
  87824. if( db->init.busy ){
  87825. Table *pOld;
  87826. Schema *pSchema = p->pSchema;
  87827. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  87828. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  87829. if( pOld ){
  87830. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  87831. db->mallocFailed = 1;
  87832. return;
  87833. }
  87834. pParse->pNewTable = 0;
  87835. db->flags |= SQLITE_InternChanges;
  87836. #ifndef SQLITE_OMIT_ALTERTABLE
  87837. if( !p->pSelect ){
  87838. const char *zName = (const char *)pParse->sNameToken.z;
  87839. int nName;
  87840. assert( !pSelect && pCons && pEnd );
  87841. if( pCons->z==0 ){
  87842. pCons = pEnd;
  87843. }
  87844. nName = (int)((const char *)pCons->z - zName);
  87845. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  87846. }
  87847. #endif
  87848. }
  87849. }
  87850. #ifndef SQLITE_OMIT_VIEW
  87851. /*
  87852. ** The parser calls this routine in order to create a new VIEW
  87853. */
  87854. SQLITE_PRIVATE void sqlite3CreateView(
  87855. Parse *pParse, /* The parsing context */
  87856. Token *pBegin, /* The CREATE token that begins the statement */
  87857. Token *pName1, /* The token that holds the name of the view */
  87858. Token *pName2, /* The token that holds the name of the view */
  87859. Select *pSelect, /* A SELECT statement that will become the new view */
  87860. int isTemp, /* TRUE for a TEMPORARY view */
  87861. int noErr /* Suppress error messages if VIEW already exists */
  87862. ){
  87863. Table *p;
  87864. int n;
  87865. const char *z;
  87866. Token sEnd;
  87867. DbFixer sFix;
  87868. Token *pName = 0;
  87869. int iDb;
  87870. sqlite3 *db = pParse->db;
  87871. if( pParse->nVar>0 ){
  87872. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  87873. sqlite3SelectDelete(db, pSelect);
  87874. return;
  87875. }
  87876. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  87877. p = pParse->pNewTable;
  87878. if( p==0 || pParse->nErr ){
  87879. sqlite3SelectDelete(db, pSelect);
  87880. return;
  87881. }
  87882. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  87883. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  87884. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  87885. if( sqlite3FixSelect(&sFix, pSelect) ){
  87886. sqlite3SelectDelete(db, pSelect);
  87887. return;
  87888. }
  87889. /* Make a copy of the entire SELECT statement that defines the view.
  87890. ** This will force all the Expr.token.z values to be dynamically
  87891. ** allocated rather than point to the input string - which means that
  87892. ** they will persist after the current sqlite3_exec() call returns.
  87893. */
  87894. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  87895. sqlite3SelectDelete(db, pSelect);
  87896. if( db->mallocFailed ){
  87897. return;
  87898. }
  87899. if( !db->init.busy ){
  87900. sqlite3ViewGetColumnNames(pParse, p);
  87901. }
  87902. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  87903. ** the end.
  87904. */
  87905. sEnd = pParse->sLastToken;
  87906. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  87907. sEnd.z += sEnd.n;
  87908. }
  87909. sEnd.n = 0;
  87910. n = (int)(sEnd.z - pBegin->z);
  87911. z = pBegin->z;
  87912. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  87913. sEnd.z = &z[n-1];
  87914. sEnd.n = 1;
  87915. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  87916. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  87917. return;
  87918. }
  87919. #endif /* SQLITE_OMIT_VIEW */
  87920. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  87921. /*
  87922. ** The Table structure pTable is really a VIEW. Fill in the names of
  87923. ** the columns of the view in the pTable structure. Return the number
  87924. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  87925. */
  87926. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  87927. Table *pSelTab; /* A fake table from which we get the result set */
  87928. Select *pSel; /* Copy of the SELECT that implements the view */
  87929. int nErr = 0; /* Number of errors encountered */
  87930. int n; /* Temporarily holds the number of cursors assigned */
  87931. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  87932. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  87933. assert( pTable );
  87934. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87935. if( sqlite3VtabCallConnect(pParse, pTable) ){
  87936. return SQLITE_ERROR;
  87937. }
  87938. if( IsVirtual(pTable) ) return 0;
  87939. #endif
  87940. #ifndef SQLITE_OMIT_VIEW
  87941. /* A positive nCol means the columns names for this view are
  87942. ** already known.
  87943. */
  87944. if( pTable->nCol>0 ) return 0;
  87945. /* A negative nCol is a special marker meaning that we are currently
  87946. ** trying to compute the column names. If we enter this routine with
  87947. ** a negative nCol, it means two or more views form a loop, like this:
  87948. **
  87949. ** CREATE VIEW one AS SELECT * FROM two;
  87950. ** CREATE VIEW two AS SELECT * FROM one;
  87951. **
  87952. ** Actually, the error above is now caught prior to reaching this point.
  87953. ** But the following test is still important as it does come up
  87954. ** in the following:
  87955. **
  87956. ** CREATE TABLE main.ex1(a);
  87957. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  87958. ** SELECT * FROM temp.ex1;
  87959. */
  87960. if( pTable->nCol<0 ){
  87961. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  87962. return 1;
  87963. }
  87964. assert( pTable->nCol>=0 );
  87965. /* If we get this far, it means we need to compute the table names.
  87966. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  87967. ** "*" elements in the results set of the view and will assign cursors
  87968. ** to the elements of the FROM clause. But we do not want these changes
  87969. ** to be permanent. So the computation is done on a copy of the SELECT
  87970. ** statement that defines the view.
  87971. */
  87972. assert( pTable->pSelect );
  87973. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  87974. if( pSel ){
  87975. u8 enableLookaside = db->lookaside.bEnabled;
  87976. n = pParse->nTab;
  87977. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  87978. pTable->nCol = -1;
  87979. db->lookaside.bEnabled = 0;
  87980. #ifndef SQLITE_OMIT_AUTHORIZATION
  87981. xAuth = db->xAuth;
  87982. db->xAuth = 0;
  87983. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  87984. db->xAuth = xAuth;
  87985. #else
  87986. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  87987. #endif
  87988. db->lookaside.bEnabled = enableLookaside;
  87989. pParse->nTab = n;
  87990. if( pSelTab ){
  87991. assert( pTable->aCol==0 );
  87992. pTable->nCol = pSelTab->nCol;
  87993. pTable->aCol = pSelTab->aCol;
  87994. pSelTab->nCol = 0;
  87995. pSelTab->aCol = 0;
  87996. sqlite3DeleteTable(db, pSelTab);
  87997. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  87998. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  87999. }else{
  88000. pTable->nCol = 0;
  88001. nErr++;
  88002. }
  88003. sqlite3SelectDelete(db, pSel);
  88004. } else {
  88005. nErr++;
  88006. }
  88007. #endif /* SQLITE_OMIT_VIEW */
  88008. return nErr;
  88009. }
  88010. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  88011. #ifndef SQLITE_OMIT_VIEW
  88012. /*
  88013. ** Clear the column names from every VIEW in database idx.
  88014. */
  88015. static void sqliteViewResetAll(sqlite3 *db, int idx){
  88016. HashElem *i;
  88017. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  88018. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  88019. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  88020. Table *pTab = sqliteHashData(i);
  88021. if( pTab->pSelect ){
  88022. sqliteDeleteColumnNames(db, pTab);
  88023. pTab->aCol = 0;
  88024. pTab->nCol = 0;
  88025. }
  88026. }
  88027. DbClearProperty(db, idx, DB_UnresetViews);
  88028. }
  88029. #else
  88030. # define sqliteViewResetAll(A,B)
  88031. #endif /* SQLITE_OMIT_VIEW */
  88032. /*
  88033. ** This function is called by the VDBE to adjust the internal schema
  88034. ** used by SQLite when the btree layer moves a table root page. The
  88035. ** root-page of a table or index in database iDb has changed from iFrom
  88036. ** to iTo.
  88037. **
  88038. ** Ticket #1728: The symbol table might still contain information
  88039. ** on tables and/or indices that are the process of being deleted.
  88040. ** If you are unlucky, one of those deleted indices or tables might
  88041. ** have the same rootpage number as the real table or index that is
  88042. ** being moved. So we cannot stop searching after the first match
  88043. ** because the first match might be for one of the deleted indices
  88044. ** or tables and not the table/index that is actually being moved.
  88045. ** We must continue looping until all tables and indices with
  88046. ** rootpage==iFrom have been converted to have a rootpage of iTo
  88047. ** in order to be certain that we got the right one.
  88048. */
  88049. #ifndef SQLITE_OMIT_AUTOVACUUM
  88050. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  88051. HashElem *pElem;
  88052. Hash *pHash;
  88053. Db *pDb;
  88054. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88055. pDb = &db->aDb[iDb];
  88056. pHash = &pDb->pSchema->tblHash;
  88057. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  88058. Table *pTab = sqliteHashData(pElem);
  88059. if( pTab->tnum==iFrom ){
  88060. pTab->tnum = iTo;
  88061. }
  88062. }
  88063. pHash = &pDb->pSchema->idxHash;
  88064. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  88065. Index *pIdx = sqliteHashData(pElem);
  88066. if( pIdx->tnum==iFrom ){
  88067. pIdx->tnum = iTo;
  88068. }
  88069. }
  88070. }
  88071. #endif
  88072. /*
  88073. ** Write code to erase the table with root-page iTable from database iDb.
  88074. ** Also write code to modify the sqlite_master table and internal schema
  88075. ** if a root-page of another table is moved by the btree-layer whilst
  88076. ** erasing iTable (this can happen with an auto-vacuum database).
  88077. */
  88078. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  88079. Vdbe *v = sqlite3GetVdbe(pParse);
  88080. int r1 = sqlite3GetTempReg(pParse);
  88081. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  88082. sqlite3MayAbort(pParse);
  88083. #ifndef SQLITE_OMIT_AUTOVACUUM
  88084. /* OP_Destroy stores an in integer r1. If this integer
  88085. ** is non-zero, then it is the root page number of a table moved to
  88086. ** location iTable. The following code modifies the sqlite_master table to
  88087. ** reflect this.
  88088. **
  88089. ** The "#NNN" in the SQL is a special constant that means whatever value
  88090. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  88091. ** token for additional information.
  88092. */
  88093. sqlite3NestedParse(pParse,
  88094. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  88095. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  88096. #endif
  88097. sqlite3ReleaseTempReg(pParse, r1);
  88098. }
  88099. /*
  88100. ** Write VDBE code to erase table pTab and all associated indices on disk.
  88101. ** Code to update the sqlite_master tables and internal schema definitions
  88102. ** in case a root-page belonging to another table is moved by the btree layer
  88103. ** is also added (this can happen with an auto-vacuum database).
  88104. */
  88105. static void destroyTable(Parse *pParse, Table *pTab){
  88106. #ifdef SQLITE_OMIT_AUTOVACUUM
  88107. Index *pIdx;
  88108. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  88109. destroyRootPage(pParse, pTab->tnum, iDb);
  88110. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88111. destroyRootPage(pParse, pIdx->tnum, iDb);
  88112. }
  88113. #else
  88114. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  88115. ** is not defined), then it is important to call OP_Destroy on the
  88116. ** table and index root-pages in order, starting with the numerically
  88117. ** largest root-page number. This guarantees that none of the root-pages
  88118. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  88119. ** following were coded:
  88120. **
  88121. ** OP_Destroy 4 0
  88122. ** ...
  88123. ** OP_Destroy 5 0
  88124. **
  88125. ** and root page 5 happened to be the largest root-page number in the
  88126. ** database, then root page 5 would be moved to page 4 by the
  88127. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  88128. ** a free-list page.
  88129. */
  88130. int iTab = pTab->tnum;
  88131. int iDestroyed = 0;
  88132. while( 1 ){
  88133. Index *pIdx;
  88134. int iLargest = 0;
  88135. if( iDestroyed==0 || iTab<iDestroyed ){
  88136. iLargest = iTab;
  88137. }
  88138. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88139. int iIdx = pIdx->tnum;
  88140. assert( pIdx->pSchema==pTab->pSchema );
  88141. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  88142. iLargest = iIdx;
  88143. }
  88144. }
  88145. if( iLargest==0 ){
  88146. return;
  88147. }else{
  88148. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  88149. assert( iDb>=0 && iDb<pParse->db->nDb );
  88150. destroyRootPage(pParse, iLargest, iDb);
  88151. iDestroyed = iLargest;
  88152. }
  88153. }
  88154. #endif
  88155. }
  88156. /*
  88157. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  88158. ** after a DROP INDEX or DROP TABLE command.
  88159. */
  88160. static void sqlite3ClearStatTables(
  88161. Parse *pParse, /* The parsing context */
  88162. int iDb, /* The database number */
  88163. const char *zType, /* "idx" or "tbl" */
  88164. const char *zName /* Name of index or table */
  88165. ){
  88166. int i;
  88167. const char *zDbName = pParse->db->aDb[iDb].zName;
  88168. for(i=1; i<=4; i++){
  88169. char zTab[24];
  88170. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  88171. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  88172. sqlite3NestedParse(pParse,
  88173. "DELETE FROM %Q.%s WHERE %s=%Q",
  88174. zDbName, zTab, zType, zName
  88175. );
  88176. }
  88177. }
  88178. }
  88179. /*
  88180. ** Generate code to drop a table.
  88181. */
  88182. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  88183. Vdbe *v;
  88184. sqlite3 *db = pParse->db;
  88185. Trigger *pTrigger;
  88186. Db *pDb = &db->aDb[iDb];
  88187. v = sqlite3GetVdbe(pParse);
  88188. assert( v!=0 );
  88189. sqlite3BeginWriteOperation(pParse, 1, iDb);
  88190. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88191. if( IsVirtual(pTab) ){
  88192. sqlite3VdbeAddOp0(v, OP_VBegin);
  88193. }
  88194. #endif
  88195. /* Drop all triggers associated with the table being dropped. Code
  88196. ** is generated to remove entries from sqlite_master and/or
  88197. ** sqlite_temp_master if required.
  88198. */
  88199. pTrigger = sqlite3TriggerList(pParse, pTab);
  88200. while( pTrigger ){
  88201. assert( pTrigger->pSchema==pTab->pSchema ||
  88202. pTrigger->pSchema==db->aDb[1].pSchema );
  88203. sqlite3DropTriggerPtr(pParse, pTrigger);
  88204. pTrigger = pTrigger->pNext;
  88205. }
  88206. #ifndef SQLITE_OMIT_AUTOINCREMENT
  88207. /* Remove any entries of the sqlite_sequence table associated with
  88208. ** the table being dropped. This is done before the table is dropped
  88209. ** at the btree level, in case the sqlite_sequence table needs to
  88210. ** move as a result of the drop (can happen in auto-vacuum mode).
  88211. */
  88212. if( pTab->tabFlags & TF_Autoincrement ){
  88213. sqlite3NestedParse(pParse,
  88214. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  88215. pDb->zName, pTab->zName
  88216. );
  88217. }
  88218. #endif
  88219. /* Drop all SQLITE_MASTER table and index entries that refer to the
  88220. ** table. The program name loops through the master table and deletes
  88221. ** every row that refers to a table of the same name as the one being
  88222. ** dropped. Triggers are handled separately because a trigger can be
  88223. ** created in the temp database that refers to a table in another
  88224. ** database.
  88225. */
  88226. sqlite3NestedParse(pParse,
  88227. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  88228. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  88229. if( !isView && !IsVirtual(pTab) ){
  88230. destroyTable(pParse, pTab);
  88231. }
  88232. /* Remove the table entry from SQLite's internal schema and modify
  88233. ** the schema cookie.
  88234. */
  88235. if( IsVirtual(pTab) ){
  88236. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  88237. }
  88238. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  88239. sqlite3ChangeCookie(pParse, iDb);
  88240. sqliteViewResetAll(db, iDb);
  88241. }
  88242. /*
  88243. ** This routine is called to do the work of a DROP TABLE statement.
  88244. ** pName is the name of the table to be dropped.
  88245. */
  88246. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  88247. Table *pTab;
  88248. Vdbe *v;
  88249. sqlite3 *db = pParse->db;
  88250. int iDb;
  88251. if( db->mallocFailed ){
  88252. goto exit_drop_table;
  88253. }
  88254. assert( pParse->nErr==0 );
  88255. assert( pName->nSrc==1 );
  88256. if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
  88257. if( noErr ) db->suppressErr++;
  88258. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  88259. if( noErr ) db->suppressErr--;
  88260. if( pTab==0 ){
  88261. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  88262. goto exit_drop_table;
  88263. }
  88264. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  88265. assert( iDb>=0 && iDb<db->nDb );
  88266. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  88267. ** it is initialized.
  88268. */
  88269. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  88270. goto exit_drop_table;
  88271. }
  88272. #ifndef SQLITE_OMIT_AUTHORIZATION
  88273. {
  88274. int code;
  88275. const char *zTab = SCHEMA_TABLE(iDb);
  88276. const char *zDb = db->aDb[iDb].zName;
  88277. const char *zArg2 = 0;
  88278. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  88279. goto exit_drop_table;
  88280. }
  88281. if( isView ){
  88282. if( !OMIT_TEMPDB && iDb==1 ){
  88283. code = SQLITE_DROP_TEMP_VIEW;
  88284. }else{
  88285. code = SQLITE_DROP_VIEW;
  88286. }
  88287. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88288. }else if( IsVirtual(pTab) ){
  88289. code = SQLITE_DROP_VTABLE;
  88290. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  88291. #endif
  88292. }else{
  88293. if( !OMIT_TEMPDB && iDb==1 ){
  88294. code = SQLITE_DROP_TEMP_TABLE;
  88295. }else{
  88296. code = SQLITE_DROP_TABLE;
  88297. }
  88298. }
  88299. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  88300. goto exit_drop_table;
  88301. }
  88302. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  88303. goto exit_drop_table;
  88304. }
  88305. }
  88306. #endif
  88307. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  88308. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  88309. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  88310. goto exit_drop_table;
  88311. }
  88312. #ifndef SQLITE_OMIT_VIEW
  88313. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  88314. ** on a table.
  88315. */
  88316. if( isView && pTab->pSelect==0 ){
  88317. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  88318. goto exit_drop_table;
  88319. }
  88320. if( !isView && pTab->pSelect ){
  88321. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  88322. goto exit_drop_table;
  88323. }
  88324. #endif
  88325. /* Generate code to remove the table from the master table
  88326. ** on disk.
  88327. */
  88328. v = sqlite3GetVdbe(pParse);
  88329. if( v ){
  88330. sqlite3BeginWriteOperation(pParse, 1, iDb);
  88331. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  88332. sqlite3FkDropTable(pParse, pName, pTab);
  88333. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  88334. }
  88335. exit_drop_table:
  88336. sqlite3SrcListDelete(db, pName);
  88337. }
  88338. /*
  88339. ** This routine is called to create a new foreign key on the table
  88340. ** currently under construction. pFromCol determines which columns
  88341. ** in the current table point to the foreign key. If pFromCol==0 then
  88342. ** connect the key to the last column inserted. pTo is the name of
  88343. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  88344. ** of tables in the parent pTo table. flags contains all
  88345. ** information about the conflict resolution algorithms specified
  88346. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  88347. **
  88348. ** An FKey structure is created and added to the table currently
  88349. ** under construction in the pParse->pNewTable field.
  88350. **
  88351. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  88352. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  88353. */
  88354. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  88355. Parse *pParse, /* Parsing context */
  88356. ExprList *pFromCol, /* Columns in this table that point to other table */
  88357. Token *pTo, /* Name of the other table */
  88358. ExprList *pToCol, /* Columns in the other table */
  88359. int flags /* Conflict resolution algorithms. */
  88360. ){
  88361. sqlite3 *db = pParse->db;
  88362. #ifndef SQLITE_OMIT_FOREIGN_KEY
  88363. FKey *pFKey = 0;
  88364. FKey *pNextTo;
  88365. Table *p = pParse->pNewTable;
  88366. int nByte;
  88367. int i;
  88368. int nCol;
  88369. char *z;
  88370. assert( pTo!=0 );
  88371. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  88372. if( pFromCol==0 ){
  88373. int iCol = p->nCol-1;
  88374. if( NEVER(iCol<0) ) goto fk_end;
  88375. if( pToCol && pToCol->nExpr!=1 ){
  88376. sqlite3ErrorMsg(pParse, "foreign key on %s"
  88377. " should reference only one column of table %T",
  88378. p->aCol[iCol].zName, pTo);
  88379. goto fk_end;
  88380. }
  88381. nCol = 1;
  88382. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  88383. sqlite3ErrorMsg(pParse,
  88384. "number of columns in foreign key does not match the number of "
  88385. "columns in the referenced table");
  88386. goto fk_end;
  88387. }else{
  88388. nCol = pFromCol->nExpr;
  88389. }
  88390. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  88391. if( pToCol ){
  88392. for(i=0; i<pToCol->nExpr; i++){
  88393. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  88394. }
  88395. }
  88396. pFKey = sqlite3DbMallocZero(db, nByte );
  88397. if( pFKey==0 ){
  88398. goto fk_end;
  88399. }
  88400. pFKey->pFrom = p;
  88401. pFKey->pNextFrom = p->pFKey;
  88402. z = (char*)&pFKey->aCol[nCol];
  88403. pFKey->zTo = z;
  88404. memcpy(z, pTo->z, pTo->n);
  88405. z[pTo->n] = 0;
  88406. sqlite3Dequote(z);
  88407. z += pTo->n+1;
  88408. pFKey->nCol = nCol;
  88409. if( pFromCol==0 ){
  88410. pFKey->aCol[0].iFrom = p->nCol-1;
  88411. }else{
  88412. for(i=0; i<nCol; i++){
  88413. int j;
  88414. for(j=0; j<p->nCol; j++){
  88415. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  88416. pFKey->aCol[i].iFrom = j;
  88417. break;
  88418. }
  88419. }
  88420. if( j>=p->nCol ){
  88421. sqlite3ErrorMsg(pParse,
  88422. "unknown column \"%s\" in foreign key definition",
  88423. pFromCol->a[i].zName);
  88424. goto fk_end;
  88425. }
  88426. }
  88427. }
  88428. if( pToCol ){
  88429. for(i=0; i<nCol; i++){
  88430. int n = sqlite3Strlen30(pToCol->a[i].zName);
  88431. pFKey->aCol[i].zCol = z;
  88432. memcpy(z, pToCol->a[i].zName, n);
  88433. z[n] = 0;
  88434. z += n+1;
  88435. }
  88436. }
  88437. pFKey->isDeferred = 0;
  88438. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  88439. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  88440. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  88441. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  88442. pFKey->zTo, (void *)pFKey
  88443. );
  88444. if( pNextTo==pFKey ){
  88445. db->mallocFailed = 1;
  88446. goto fk_end;
  88447. }
  88448. if( pNextTo ){
  88449. assert( pNextTo->pPrevTo==0 );
  88450. pFKey->pNextTo = pNextTo;
  88451. pNextTo->pPrevTo = pFKey;
  88452. }
  88453. /* Link the foreign key to the table as the last step.
  88454. */
  88455. p->pFKey = pFKey;
  88456. pFKey = 0;
  88457. fk_end:
  88458. sqlite3DbFree(db, pFKey);
  88459. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  88460. sqlite3ExprListDelete(db, pFromCol);
  88461. sqlite3ExprListDelete(db, pToCol);
  88462. }
  88463. /*
  88464. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  88465. ** clause is seen as part of a foreign key definition. The isDeferred
  88466. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  88467. ** The behavior of the most recently created foreign key is adjusted
  88468. ** accordingly.
  88469. */
  88470. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  88471. #ifndef SQLITE_OMIT_FOREIGN_KEY
  88472. Table *pTab;
  88473. FKey *pFKey;
  88474. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  88475. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  88476. pFKey->isDeferred = (u8)isDeferred;
  88477. #endif
  88478. }
  88479. /*
  88480. ** Generate code that will erase and refill index *pIdx. This is
  88481. ** used to initialize a newly created index or to recompute the
  88482. ** content of an index in response to a REINDEX command.
  88483. **
  88484. ** if memRootPage is not negative, it means that the index is newly
  88485. ** created. The register specified by memRootPage contains the
  88486. ** root page number of the index. If memRootPage is negative, then
  88487. ** the index already exists and must be cleared before being refilled and
  88488. ** the root page number of the index is taken from pIndex->tnum.
  88489. */
  88490. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  88491. Table *pTab = pIndex->pTable; /* The table that is indexed */
  88492. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  88493. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  88494. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  88495. int addr1; /* Address of top of loop */
  88496. int addr2; /* Address to jump to for next iteration */
  88497. int tnum; /* Root page of index */
  88498. int iPartIdxLabel; /* Jump to this label to skip a row */
  88499. Vdbe *v; /* Generate code into this virtual machine */
  88500. KeyInfo *pKey; /* KeyInfo for index */
  88501. int regRecord; /* Register holding assembled index record */
  88502. sqlite3 *db = pParse->db; /* The database connection */
  88503. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  88504. #ifndef SQLITE_OMIT_AUTHORIZATION
  88505. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  88506. db->aDb[iDb].zName ) ){
  88507. return;
  88508. }
  88509. #endif
  88510. /* Require a write-lock on the table to perform this operation */
  88511. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  88512. v = sqlite3GetVdbe(pParse);
  88513. if( v==0 ) return;
  88514. if( memRootPage>=0 ){
  88515. tnum = memRootPage;
  88516. }else{
  88517. tnum = pIndex->tnum;
  88518. }
  88519. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  88520. /* Open the sorter cursor if we are to use one. */
  88521. iSorter = pParse->nTab++;
  88522. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  88523. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  88524. /* Open the table. Loop through all rows of the table, inserting index
  88525. ** records into the sorter. */
  88526. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  88527. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  88528. regRecord = sqlite3GetTempReg(pParse);
  88529. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  88530. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  88531. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  88532. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  88533. sqlite3VdbeJumpHere(v, addr1);
  88534. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  88535. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  88536. (char *)pKey, P4_KEYINFO);
  88537. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  88538. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  88539. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  88540. if( IsUniqueIndex(pIndex) && pKey!=0 ){
  88541. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  88542. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  88543. addr2 = sqlite3VdbeCurrentAddr(v);
  88544. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  88545. pIndex->nKeyCol); VdbeCoverage(v);
  88546. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  88547. }else{
  88548. addr2 = sqlite3VdbeCurrentAddr(v);
  88549. }
  88550. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  88551. sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
  88552. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
  88553. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  88554. sqlite3ReleaseTempReg(pParse, regRecord);
  88555. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  88556. sqlite3VdbeJumpHere(v, addr1);
  88557. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  88558. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  88559. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  88560. }
  88561. /*
  88562. ** Allocate heap space to hold an Index object with nCol columns.
  88563. **
  88564. ** Increase the allocation size to provide an extra nExtra bytes
  88565. ** of 8-byte aligned space after the Index object and return a
  88566. ** pointer to this extra space in *ppExtra.
  88567. */
  88568. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  88569. sqlite3 *db, /* Database connection */
  88570. i16 nCol, /* Total number of columns in the index */
  88571. int nExtra, /* Number of bytes of extra space to alloc */
  88572. char **ppExtra /* Pointer to the "extra" space */
  88573. ){
  88574. Index *p; /* Allocated index object */
  88575. int nByte; /* Bytes of space for Index object + arrays */
  88576. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  88577. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  88578. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  88579. sizeof(i16)*nCol + /* Index.aiColumn */
  88580. sizeof(u8)*nCol); /* Index.aSortOrder */
  88581. p = sqlite3DbMallocZero(db, nByte + nExtra);
  88582. if( p ){
  88583. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  88584. p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  88585. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  88586. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  88587. p->aSortOrder = (u8*)pExtra;
  88588. p->nColumn = nCol;
  88589. p->nKeyCol = nCol - 1;
  88590. *ppExtra = ((char*)p) + nByte;
  88591. }
  88592. return p;
  88593. }
  88594. /*
  88595. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  88596. ** and pTblList is the name of the table that is to be indexed. Both will
  88597. ** be NULL for a primary key or an index that is created to satisfy a
  88598. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  88599. ** as the table to be indexed. pParse->pNewTable is a table that is
  88600. ** currently being constructed by a CREATE TABLE statement.
  88601. **
  88602. ** pList is a list of columns to be indexed. pList will be NULL if this
  88603. ** is a primary key or unique-constraint on the most recent column added
  88604. ** to the table currently under construction.
  88605. **
  88606. ** If the index is created successfully, return a pointer to the new Index
  88607. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  88608. ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  88609. */
  88610. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  88611. Parse *pParse, /* All information about this parse */
  88612. Token *pName1, /* First part of index name. May be NULL */
  88613. Token *pName2, /* Second part of index name. May be NULL */
  88614. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  88615. ExprList *pList, /* A list of columns to be indexed */
  88616. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  88617. Token *pStart, /* The CREATE token that begins this statement */
  88618. Expr *pPIWhere, /* WHERE clause for partial indices */
  88619. int sortOrder, /* Sort order of primary key when pList==NULL */
  88620. int ifNotExist /* Omit error if index already exists */
  88621. ){
  88622. Index *pRet = 0; /* Pointer to return */
  88623. Table *pTab = 0; /* Table to be indexed */
  88624. Index *pIndex = 0; /* The index to be created */
  88625. char *zName = 0; /* Name of the index */
  88626. int nName; /* Number of characters in zName */
  88627. int i, j;
  88628. DbFixer sFix; /* For assigning database names to pTable */
  88629. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  88630. sqlite3 *db = pParse->db;
  88631. Db *pDb; /* The specific table containing the indexed database */
  88632. int iDb; /* Index of the database that is being written */
  88633. Token *pName = 0; /* Unqualified name of the index to create */
  88634. struct ExprList_item *pListItem; /* For looping over pList */
  88635. const Column *pTabCol; /* A column in the table */
  88636. int nExtra = 0; /* Space allocated for zExtra[] */
  88637. int nExtraCol; /* Number of extra columns needed */
  88638. char *zExtra = 0; /* Extra space after the Index object */
  88639. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  88640. if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
  88641. goto exit_create_index;
  88642. }
  88643. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  88644. goto exit_create_index;
  88645. }
  88646. /*
  88647. ** Find the table that is to be indexed. Return early if not found.
  88648. */
  88649. if( pTblName!=0 ){
  88650. /* Use the two-part index name to determine the database
  88651. ** to search for the table. 'Fix' the table name to this db
  88652. ** before looking up the table.
  88653. */
  88654. assert( pName1 && pName2 );
  88655. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  88656. if( iDb<0 ) goto exit_create_index;
  88657. assert( pName && pName->z );
  88658. #ifndef SQLITE_OMIT_TEMPDB
  88659. /* If the index name was unqualified, check if the table
  88660. ** is a temp table. If so, set the database to 1. Do not do this
  88661. ** if initialising a database schema.
  88662. */
  88663. if( !db->init.busy ){
  88664. pTab = sqlite3SrcListLookup(pParse, pTblName);
  88665. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  88666. iDb = 1;
  88667. }
  88668. }
  88669. #endif
  88670. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  88671. if( sqlite3FixSrcList(&sFix, pTblName) ){
  88672. /* Because the parser constructs pTblName from a single identifier,
  88673. ** sqlite3FixSrcList can never fail. */
  88674. assert(0);
  88675. }
  88676. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  88677. assert( db->mallocFailed==0 || pTab==0 );
  88678. if( pTab==0 ) goto exit_create_index;
  88679. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  88680. sqlite3ErrorMsg(pParse,
  88681. "cannot create a TEMP index on non-TEMP table \"%s\"",
  88682. pTab->zName);
  88683. goto exit_create_index;
  88684. }
  88685. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  88686. }else{
  88687. assert( pName==0 );
  88688. assert( pStart==0 );
  88689. pTab = pParse->pNewTable;
  88690. if( !pTab ) goto exit_create_index;
  88691. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  88692. }
  88693. pDb = &db->aDb[iDb];
  88694. assert( pTab!=0 );
  88695. assert( pParse->nErr==0 );
  88696. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  88697. && db->init.busy==0
  88698. #if SQLITE_USER_AUTHENTICATION
  88699. && sqlite3UserAuthTable(pTab->zName)==0
  88700. #endif
  88701. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  88702. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  88703. goto exit_create_index;
  88704. }
  88705. #ifndef SQLITE_OMIT_VIEW
  88706. if( pTab->pSelect ){
  88707. sqlite3ErrorMsg(pParse, "views may not be indexed");
  88708. goto exit_create_index;
  88709. }
  88710. #endif
  88711. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88712. if( IsVirtual(pTab) ){
  88713. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  88714. goto exit_create_index;
  88715. }
  88716. #endif
  88717. /*
  88718. ** Find the name of the index. Make sure there is not already another
  88719. ** index or table with the same name.
  88720. **
  88721. ** Exception: If we are reading the names of permanent indices from the
  88722. ** sqlite_master table (because some other process changed the schema) and
  88723. ** one of the index names collides with the name of a temporary table or
  88724. ** index, then we will continue to process this index.
  88725. **
  88726. ** If pName==0 it means that we are
  88727. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  88728. ** own name.
  88729. */
  88730. if( pName ){
  88731. zName = sqlite3NameFromToken(db, pName);
  88732. if( zName==0 ) goto exit_create_index;
  88733. assert( pName->z!=0 );
  88734. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  88735. goto exit_create_index;
  88736. }
  88737. if( !db->init.busy ){
  88738. if( sqlite3FindTable(db, zName, 0)!=0 ){
  88739. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  88740. goto exit_create_index;
  88741. }
  88742. }
  88743. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  88744. if( !ifNotExist ){
  88745. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  88746. }else{
  88747. assert( !db->init.busy );
  88748. sqlite3CodeVerifySchema(pParse, iDb);
  88749. }
  88750. goto exit_create_index;
  88751. }
  88752. }else{
  88753. int n;
  88754. Index *pLoop;
  88755. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  88756. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  88757. if( zName==0 ){
  88758. goto exit_create_index;
  88759. }
  88760. }
  88761. /* Check for authorization to create an index.
  88762. */
  88763. #ifndef SQLITE_OMIT_AUTHORIZATION
  88764. {
  88765. const char *zDb = pDb->zName;
  88766. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  88767. goto exit_create_index;
  88768. }
  88769. i = SQLITE_CREATE_INDEX;
  88770. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  88771. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  88772. goto exit_create_index;
  88773. }
  88774. }
  88775. #endif
  88776. /* If pList==0, it means this routine was called to make a primary
  88777. ** key out of the last column added to the table under construction.
  88778. ** So create a fake list to simulate this.
  88779. */
  88780. if( pList==0 ){
  88781. pList = sqlite3ExprListAppend(pParse, 0, 0);
  88782. if( pList==0 ) goto exit_create_index;
  88783. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  88784. pTab->aCol[pTab->nCol-1].zName);
  88785. pList->a[0].sortOrder = (u8)sortOrder;
  88786. }
  88787. /* Figure out how many bytes of space are required to store explicitly
  88788. ** specified collation sequence names.
  88789. */
  88790. for(i=0; i<pList->nExpr; i++){
  88791. Expr *pExpr = pList->a[i].pExpr;
  88792. if( pExpr ){
  88793. assert( pExpr->op==TK_COLLATE );
  88794. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  88795. }
  88796. }
  88797. /*
  88798. ** Allocate the index structure.
  88799. */
  88800. nName = sqlite3Strlen30(zName);
  88801. nExtraCol = pPk ? pPk->nKeyCol : 1;
  88802. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  88803. nName + nExtra + 1, &zExtra);
  88804. if( db->mallocFailed ){
  88805. goto exit_create_index;
  88806. }
  88807. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  88808. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  88809. pIndex->zName = zExtra;
  88810. zExtra += nName + 1;
  88811. memcpy(pIndex->zName, zName, nName+1);
  88812. pIndex->pTable = pTab;
  88813. pIndex->onError = (u8)onError;
  88814. pIndex->uniqNotNull = onError!=OE_None;
  88815. pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  88816. pIndex->pSchema = db->aDb[iDb].pSchema;
  88817. pIndex->nKeyCol = pList->nExpr;
  88818. if( pPIWhere ){
  88819. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  88820. pIndex->pPartIdxWhere = pPIWhere;
  88821. pPIWhere = 0;
  88822. }
  88823. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  88824. /* Check to see if we should honor DESC requests on index columns
  88825. */
  88826. if( pDb->pSchema->file_format>=4 ){
  88827. sortOrderMask = -1; /* Honor DESC */
  88828. }else{
  88829. sortOrderMask = 0; /* Ignore DESC */
  88830. }
  88831. /* Scan the names of the columns of the table to be indexed and
  88832. ** load the column indices into the Index structure. Report an error
  88833. ** if any column is not found.
  88834. **
  88835. ** TODO: Add a test to make sure that the same column is not named
  88836. ** more than once within the same index. Only the first instance of
  88837. ** the column will ever be used by the optimizer. Note that using the
  88838. ** same column more than once cannot be an error because that would
  88839. ** break backwards compatibility - it needs to be a warning.
  88840. */
  88841. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  88842. const char *zColName = pListItem->zName;
  88843. int requestedSortOrder;
  88844. char *zColl; /* Collation sequence name */
  88845. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  88846. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  88847. }
  88848. if( j>=pTab->nCol ){
  88849. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  88850. pTab->zName, zColName);
  88851. pParse->checkSchema = 1;
  88852. goto exit_create_index;
  88853. }
  88854. assert( j<=0x7fff );
  88855. pIndex->aiColumn[i] = (i16)j;
  88856. if( pListItem->pExpr ){
  88857. int nColl;
  88858. assert( pListItem->pExpr->op==TK_COLLATE );
  88859. zColl = pListItem->pExpr->u.zToken;
  88860. nColl = sqlite3Strlen30(zColl) + 1;
  88861. assert( nExtra>=nColl );
  88862. memcpy(zExtra, zColl, nColl);
  88863. zColl = zExtra;
  88864. zExtra += nColl;
  88865. nExtra -= nColl;
  88866. }else{
  88867. zColl = pTab->aCol[j].zColl;
  88868. if( !zColl ) zColl = "BINARY";
  88869. }
  88870. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  88871. goto exit_create_index;
  88872. }
  88873. pIndex->azColl[i] = zColl;
  88874. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  88875. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  88876. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  88877. }
  88878. if( pPk ){
  88879. for(j=0; j<pPk->nKeyCol; j++){
  88880. int x = pPk->aiColumn[j];
  88881. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  88882. pIndex->nColumn--;
  88883. }else{
  88884. pIndex->aiColumn[i] = x;
  88885. pIndex->azColl[i] = pPk->azColl[j];
  88886. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  88887. i++;
  88888. }
  88889. }
  88890. assert( i==pIndex->nColumn );
  88891. }else{
  88892. pIndex->aiColumn[i] = -1;
  88893. pIndex->azColl[i] = "BINARY";
  88894. }
  88895. sqlite3DefaultRowEst(pIndex);
  88896. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  88897. if( pTab==pParse->pNewTable ){
  88898. /* This routine has been called to create an automatic index as a
  88899. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  88900. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  88901. ** i.e. one of:
  88902. **
  88903. ** CREATE TABLE t(x PRIMARY KEY, y);
  88904. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  88905. **
  88906. ** Either way, check to see if the table already has such an index. If
  88907. ** so, don't bother creating this one. This only applies to
  88908. ** automatically created indices. Users can do as they wish with
  88909. ** explicit indices.
  88910. **
  88911. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  88912. ** (and thus suppressing the second one) even if they have different
  88913. ** sort orders.
  88914. **
  88915. ** If there are different collating sequences or if the columns of
  88916. ** the constraint occur in different orders, then the constraints are
  88917. ** considered distinct and both result in separate indices.
  88918. */
  88919. Index *pIdx;
  88920. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  88921. int k;
  88922. assert( IsUniqueIndex(pIdx) );
  88923. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  88924. assert( IsUniqueIndex(pIndex) );
  88925. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  88926. for(k=0; k<pIdx->nKeyCol; k++){
  88927. const char *z1;
  88928. const char *z2;
  88929. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  88930. z1 = pIdx->azColl[k];
  88931. z2 = pIndex->azColl[k];
  88932. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  88933. }
  88934. if( k==pIdx->nKeyCol ){
  88935. if( pIdx->onError!=pIndex->onError ){
  88936. /* This constraint creates the same index as a previous
  88937. ** constraint specified somewhere in the CREATE TABLE statement.
  88938. ** However the ON CONFLICT clauses are different. If both this
  88939. ** constraint and the previous equivalent constraint have explicit
  88940. ** ON CONFLICT clauses this is an error. Otherwise, use the
  88941. ** explicitly specified behavior for the index.
  88942. */
  88943. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  88944. sqlite3ErrorMsg(pParse,
  88945. "conflicting ON CONFLICT clauses specified", 0);
  88946. }
  88947. if( pIdx->onError==OE_Default ){
  88948. pIdx->onError = pIndex->onError;
  88949. }
  88950. }
  88951. pRet = pIdx;
  88952. goto exit_create_index;
  88953. }
  88954. }
  88955. }
  88956. /* Link the new Index structure to its table and to the other
  88957. ** in-memory database structures.
  88958. */
  88959. if( db->init.busy ){
  88960. Index *p;
  88961. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  88962. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  88963. pIndex->zName, pIndex);
  88964. if( p ){
  88965. assert( p==pIndex ); /* Malloc must have failed */
  88966. db->mallocFailed = 1;
  88967. goto exit_create_index;
  88968. }
  88969. db->flags |= SQLITE_InternChanges;
  88970. if( pTblName!=0 ){
  88971. pIndex->tnum = db->init.newTnum;
  88972. }
  88973. }
  88974. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  88975. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  88976. ** emit code to allocate the index rootpage on disk and make an entry for
  88977. ** the index in the sqlite_master table and populate the index with
  88978. ** content. But, do not do this if we are simply reading the sqlite_master
  88979. ** table to parse the schema, or if this index is the PRIMARY KEY index
  88980. ** of a WITHOUT ROWID table.
  88981. **
  88982. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  88983. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  88984. ** has just been created, it contains no data and the index initialization
  88985. ** step can be skipped.
  88986. */
  88987. else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
  88988. Vdbe *v;
  88989. char *zStmt;
  88990. int iMem = ++pParse->nMem;
  88991. v = sqlite3GetVdbe(pParse);
  88992. if( v==0 ) goto exit_create_index;
  88993. sqlite3BeginWriteOperation(pParse, 1, iDb);
  88994. /* Create the rootpage for the index using CreateIndex. But before
  88995. ** doing so, code a Noop instruction and store its address in
  88996. ** Index.tnum. This is required in case this index is actually a
  88997. ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
  88998. ** that case the convertToWithoutRowidTable() routine will replace
  88999. ** the Noop with a Goto to jump over the VDBE code generated below. */
  89000. pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
  89001. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  89002. /* Gather the complete text of the CREATE INDEX statement into
  89003. ** the zStmt variable
  89004. */
  89005. if( pStart ){
  89006. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  89007. if( pName->z[n-1]==';' ) n--;
  89008. /* A named index with an explicit CREATE INDEX statement */
  89009. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  89010. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  89011. }else{
  89012. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  89013. /* zStmt = sqlite3MPrintf(""); */
  89014. zStmt = 0;
  89015. }
  89016. /* Add an entry in sqlite_master for this index
  89017. */
  89018. sqlite3NestedParse(pParse,
  89019. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  89020. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  89021. pIndex->zName,
  89022. pTab->zName,
  89023. iMem,
  89024. zStmt
  89025. );
  89026. sqlite3DbFree(db, zStmt);
  89027. /* Fill the index with data and reparse the schema. Code an OP_Expire
  89028. ** to invalidate all pre-compiled statements.
  89029. */
  89030. if( pTblName ){
  89031. sqlite3RefillIndex(pParse, pIndex, iMem);
  89032. sqlite3ChangeCookie(pParse, iDb);
  89033. sqlite3VdbeAddParseSchemaOp(v, iDb,
  89034. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  89035. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  89036. }
  89037. sqlite3VdbeJumpHere(v, pIndex->tnum);
  89038. }
  89039. /* When adding an index to the list of indices for a table, make
  89040. ** sure all indices labeled OE_Replace come after all those labeled
  89041. ** OE_Ignore. This is necessary for the correct constraint check
  89042. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  89043. ** UPDATE and INSERT statements.
  89044. */
  89045. if( db->init.busy || pTblName==0 ){
  89046. if( onError!=OE_Replace || pTab->pIndex==0
  89047. || pTab->pIndex->onError==OE_Replace){
  89048. pIndex->pNext = pTab->pIndex;
  89049. pTab->pIndex = pIndex;
  89050. }else{
  89051. Index *pOther = pTab->pIndex;
  89052. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  89053. pOther = pOther->pNext;
  89054. }
  89055. pIndex->pNext = pOther->pNext;
  89056. pOther->pNext = pIndex;
  89057. }
  89058. pRet = pIndex;
  89059. pIndex = 0;
  89060. }
  89061. /* Clean up before exiting */
  89062. exit_create_index:
  89063. if( pIndex ) freeIndex(db, pIndex);
  89064. sqlite3ExprDelete(db, pPIWhere);
  89065. sqlite3ExprListDelete(db, pList);
  89066. sqlite3SrcListDelete(db, pTblName);
  89067. sqlite3DbFree(db, zName);
  89068. return pRet;
  89069. }
  89070. /*
  89071. ** Fill the Index.aiRowEst[] array with default information - information
  89072. ** to be used when we have not run the ANALYZE command.
  89073. **
  89074. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  89075. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  89076. ** number of rows in the table that match any particular value of the
  89077. ** first column of the index. aiRowEst[2] is an estimate of the number
  89078. ** of rows that match any particular combination of the first 2 columns
  89079. ** of the index. And so forth. It must always be the case that
  89080. *
  89081. ** aiRowEst[N]<=aiRowEst[N-1]
  89082. ** aiRowEst[N]>=1
  89083. **
  89084. ** Apart from that, we have little to go on besides intuition as to
  89085. ** how aiRowEst[] should be initialized. The numbers generated here
  89086. ** are based on typical values found in actual indices.
  89087. */
  89088. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  89089. /* 10, 9, 8, 7, 6 */
  89090. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  89091. LogEst *a = pIdx->aiRowLogEst;
  89092. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  89093. int i;
  89094. /* Set the first entry (number of rows in the index) to the estimated
  89095. ** number of rows in the table. Or 10, if the estimated number of rows
  89096. ** in the table is less than that. */
  89097. a[0] = pIdx->pTable->nRowLogEst;
  89098. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  89099. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  89100. ** 6 and each subsequent value (if any) is 5. */
  89101. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  89102. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  89103. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  89104. }
  89105. assert( 0==sqlite3LogEst(1) );
  89106. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  89107. }
  89108. /*
  89109. ** This routine will drop an existing named index. This routine
  89110. ** implements the DROP INDEX statement.
  89111. */
  89112. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  89113. Index *pIndex;
  89114. Vdbe *v;
  89115. sqlite3 *db = pParse->db;
  89116. int iDb;
  89117. assert( pParse->nErr==0 ); /* Never called with prior errors */
  89118. if( db->mallocFailed ){
  89119. goto exit_drop_index;
  89120. }
  89121. assert( pName->nSrc==1 );
  89122. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  89123. goto exit_drop_index;
  89124. }
  89125. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  89126. if( pIndex==0 ){
  89127. if( !ifExists ){
  89128. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  89129. }else{
  89130. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  89131. }
  89132. pParse->checkSchema = 1;
  89133. goto exit_drop_index;
  89134. }
  89135. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  89136. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  89137. "or PRIMARY KEY constraint cannot be dropped", 0);
  89138. goto exit_drop_index;
  89139. }
  89140. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  89141. #ifndef SQLITE_OMIT_AUTHORIZATION
  89142. {
  89143. int code = SQLITE_DROP_INDEX;
  89144. Table *pTab = pIndex->pTable;
  89145. const char *zDb = db->aDb[iDb].zName;
  89146. const char *zTab = SCHEMA_TABLE(iDb);
  89147. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  89148. goto exit_drop_index;
  89149. }
  89150. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  89151. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  89152. goto exit_drop_index;
  89153. }
  89154. }
  89155. #endif
  89156. /* Generate code to remove the index and from the master table */
  89157. v = sqlite3GetVdbe(pParse);
  89158. if( v ){
  89159. sqlite3BeginWriteOperation(pParse, 1, iDb);
  89160. sqlite3NestedParse(pParse,
  89161. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  89162. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  89163. );
  89164. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  89165. sqlite3ChangeCookie(pParse, iDb);
  89166. destroyRootPage(pParse, pIndex->tnum, iDb);
  89167. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  89168. }
  89169. exit_drop_index:
  89170. sqlite3SrcListDelete(db, pName);
  89171. }
  89172. /*
  89173. ** pArray is a pointer to an array of objects. Each object in the
  89174. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  89175. ** to extend the array so that there is space for a new object at the end.
  89176. **
  89177. ** When this function is called, *pnEntry contains the current size of
  89178. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  89179. ** in total).
  89180. **
  89181. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  89182. ** space allocated for the new object is zeroed, *pnEntry updated to
  89183. ** reflect the new size of the array and a pointer to the new allocation
  89184. ** returned. *pIdx is set to the index of the new array entry in this case.
  89185. **
  89186. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  89187. ** unchanged and a copy of pArray returned.
  89188. */
  89189. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  89190. sqlite3 *db, /* Connection to notify of malloc failures */
  89191. void *pArray, /* Array of objects. Might be reallocated */
  89192. int szEntry, /* Size of each object in the array */
  89193. int *pnEntry, /* Number of objects currently in use */
  89194. int *pIdx /* Write the index of a new slot here */
  89195. ){
  89196. char *z;
  89197. int n = *pnEntry;
  89198. if( (n & (n-1))==0 ){
  89199. int sz = (n==0) ? 1 : 2*n;
  89200. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  89201. if( pNew==0 ){
  89202. *pIdx = -1;
  89203. return pArray;
  89204. }
  89205. pArray = pNew;
  89206. }
  89207. z = (char*)pArray;
  89208. memset(&z[n * szEntry], 0, szEntry);
  89209. *pIdx = n;
  89210. ++*pnEntry;
  89211. return pArray;
  89212. }
  89213. /*
  89214. ** Append a new element to the given IdList. Create a new IdList if
  89215. ** need be.
  89216. **
  89217. ** A new IdList is returned, or NULL if malloc() fails.
  89218. */
  89219. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  89220. int i;
  89221. if( pList==0 ){
  89222. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  89223. if( pList==0 ) return 0;
  89224. }
  89225. pList->a = sqlite3ArrayAllocate(
  89226. db,
  89227. pList->a,
  89228. sizeof(pList->a[0]),
  89229. &pList->nId,
  89230. &i
  89231. );
  89232. if( i<0 ){
  89233. sqlite3IdListDelete(db, pList);
  89234. return 0;
  89235. }
  89236. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  89237. return pList;
  89238. }
  89239. /*
  89240. ** Delete an IdList.
  89241. */
  89242. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  89243. int i;
  89244. if( pList==0 ) return;
  89245. for(i=0; i<pList->nId; i++){
  89246. sqlite3DbFree(db, pList->a[i].zName);
  89247. }
  89248. sqlite3DbFree(db, pList->a);
  89249. sqlite3DbFree(db, pList);
  89250. }
  89251. /*
  89252. ** Return the index in pList of the identifier named zId. Return -1
  89253. ** if not found.
  89254. */
  89255. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  89256. int i;
  89257. if( pList==0 ) return -1;
  89258. for(i=0; i<pList->nId; i++){
  89259. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  89260. }
  89261. return -1;
  89262. }
  89263. /*
  89264. ** Expand the space allocated for the given SrcList object by
  89265. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  89266. ** New slots are zeroed.
  89267. **
  89268. ** For example, suppose a SrcList initially contains two entries: A,B.
  89269. ** To append 3 new entries onto the end, do this:
  89270. **
  89271. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  89272. **
  89273. ** After the call above it would contain: A, B, nil, nil, nil.
  89274. ** If the iStart argument had been 1 instead of 2, then the result
  89275. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  89276. ** the iStart value would be 0. The result then would
  89277. ** be: nil, nil, nil, A, B.
  89278. **
  89279. ** If a memory allocation fails the SrcList is unchanged. The
  89280. ** db->mallocFailed flag will be set to true.
  89281. */
  89282. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  89283. sqlite3 *db, /* Database connection to notify of OOM errors */
  89284. SrcList *pSrc, /* The SrcList to be enlarged */
  89285. int nExtra, /* Number of new slots to add to pSrc->a[] */
  89286. int iStart /* Index in pSrc->a[] of first new slot */
  89287. ){
  89288. int i;
  89289. /* Sanity checking on calling parameters */
  89290. assert( iStart>=0 );
  89291. assert( nExtra>=1 );
  89292. assert( pSrc!=0 );
  89293. assert( iStart<=pSrc->nSrc );
  89294. /* Allocate additional space if needed */
  89295. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  89296. SrcList *pNew;
  89297. int nAlloc = pSrc->nSrc+nExtra;
  89298. int nGot;
  89299. pNew = sqlite3DbRealloc(db, pSrc,
  89300. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  89301. if( pNew==0 ){
  89302. assert( db->mallocFailed );
  89303. return pSrc;
  89304. }
  89305. pSrc = pNew;
  89306. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  89307. pSrc->nAlloc = nGot;
  89308. }
  89309. /* Move existing slots that come after the newly inserted slots
  89310. ** out of the way */
  89311. for(i=pSrc->nSrc-1; i>=iStart; i--){
  89312. pSrc->a[i+nExtra] = pSrc->a[i];
  89313. }
  89314. pSrc->nSrc += nExtra;
  89315. /* Zero the newly allocated slots */
  89316. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  89317. for(i=iStart; i<iStart+nExtra; i++){
  89318. pSrc->a[i].iCursor = -1;
  89319. }
  89320. /* Return a pointer to the enlarged SrcList */
  89321. return pSrc;
  89322. }
  89323. /*
  89324. ** Append a new table name to the given SrcList. Create a new SrcList if
  89325. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  89326. **
  89327. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  89328. ** SrcList might be the same as the SrcList that was input or it might be
  89329. ** a new one. If an OOM error does occurs, then the prior value of pList
  89330. ** that is input to this routine is automatically freed.
  89331. **
  89332. ** If pDatabase is not null, it means that the table has an optional
  89333. ** database name prefix. Like this: "database.table". The pDatabase
  89334. ** points to the table name and the pTable points to the database name.
  89335. ** The SrcList.a[].zName field is filled with the table name which might
  89336. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  89337. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  89338. ** or with NULL if no database is specified.
  89339. **
  89340. ** In other words, if call like this:
  89341. **
  89342. ** sqlite3SrcListAppend(D,A,B,0);
  89343. **
  89344. ** Then B is a table name and the database name is unspecified. If called
  89345. ** like this:
  89346. **
  89347. ** sqlite3SrcListAppend(D,A,B,C);
  89348. **
  89349. ** Then C is the table name and B is the database name. If C is defined
  89350. ** then so is B. In other words, we never have a case where:
  89351. **
  89352. ** sqlite3SrcListAppend(D,A,0,C);
  89353. **
  89354. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  89355. ** before being added to the SrcList.
  89356. */
  89357. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  89358. sqlite3 *db, /* Connection to notify of malloc failures */
  89359. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  89360. Token *pTable, /* Table to append */
  89361. Token *pDatabase /* Database of the table */
  89362. ){
  89363. struct SrcList_item *pItem;
  89364. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  89365. if( pList==0 ){
  89366. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  89367. if( pList==0 ) return 0;
  89368. pList->nAlloc = 1;
  89369. }
  89370. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  89371. if( db->mallocFailed ){
  89372. sqlite3SrcListDelete(db, pList);
  89373. return 0;
  89374. }
  89375. pItem = &pList->a[pList->nSrc-1];
  89376. if( pDatabase && pDatabase->z==0 ){
  89377. pDatabase = 0;
  89378. }
  89379. if( pDatabase ){
  89380. Token *pTemp = pDatabase;
  89381. pDatabase = pTable;
  89382. pTable = pTemp;
  89383. }
  89384. pItem->zName = sqlite3NameFromToken(db, pTable);
  89385. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  89386. return pList;
  89387. }
  89388. /*
  89389. ** Assign VdbeCursor index numbers to all tables in a SrcList
  89390. */
  89391. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  89392. int i;
  89393. struct SrcList_item *pItem;
  89394. assert(pList || pParse->db->mallocFailed );
  89395. if( pList ){
  89396. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  89397. if( pItem->iCursor>=0 ) break;
  89398. pItem->iCursor = pParse->nTab++;
  89399. if( pItem->pSelect ){
  89400. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  89401. }
  89402. }
  89403. }
  89404. }
  89405. /*
  89406. ** Delete an entire SrcList including all its substructure.
  89407. */
  89408. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  89409. int i;
  89410. struct SrcList_item *pItem;
  89411. if( pList==0 ) return;
  89412. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  89413. sqlite3DbFree(db, pItem->zDatabase);
  89414. sqlite3DbFree(db, pItem->zName);
  89415. sqlite3DbFree(db, pItem->zAlias);
  89416. sqlite3DbFree(db, pItem->zIndexedBy);
  89417. sqlite3DeleteTable(db, pItem->pTab);
  89418. sqlite3SelectDelete(db, pItem->pSelect);
  89419. sqlite3ExprDelete(db, pItem->pOn);
  89420. sqlite3IdListDelete(db, pItem->pUsing);
  89421. }
  89422. sqlite3DbFree(db, pList);
  89423. }
  89424. /*
  89425. ** This routine is called by the parser to add a new term to the
  89426. ** end of a growing FROM clause. The "p" parameter is the part of
  89427. ** the FROM clause that has already been constructed. "p" is NULL
  89428. ** if this is the first term of the FROM clause. pTable and pDatabase
  89429. ** are the name of the table and database named in the FROM clause term.
  89430. ** pDatabase is NULL if the database name qualifier is missing - the
  89431. ** usual case. If the term has an alias, then pAlias points to the
  89432. ** alias token. If the term is a subquery, then pSubquery is the
  89433. ** SELECT statement that the subquery encodes. The pTable and
  89434. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  89435. ** parameters are the content of the ON and USING clauses.
  89436. **
  89437. ** Return a new SrcList which encodes is the FROM with the new
  89438. ** term added.
  89439. */
  89440. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  89441. Parse *pParse, /* Parsing context */
  89442. SrcList *p, /* The left part of the FROM clause already seen */
  89443. Token *pTable, /* Name of the table to add to the FROM clause */
  89444. Token *pDatabase, /* Name of the database containing pTable */
  89445. Token *pAlias, /* The right-hand side of the AS subexpression */
  89446. Select *pSubquery, /* A subquery used in place of a table name */
  89447. Expr *pOn, /* The ON clause of a join */
  89448. IdList *pUsing /* The USING clause of a join */
  89449. ){
  89450. struct SrcList_item *pItem;
  89451. sqlite3 *db = pParse->db;
  89452. if( !p && (pOn || pUsing) ){
  89453. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  89454. (pOn ? "ON" : "USING")
  89455. );
  89456. goto append_from_error;
  89457. }
  89458. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  89459. if( p==0 || NEVER(p->nSrc==0) ){
  89460. goto append_from_error;
  89461. }
  89462. pItem = &p->a[p->nSrc-1];
  89463. assert( pAlias!=0 );
  89464. if( pAlias->n ){
  89465. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  89466. }
  89467. pItem->pSelect = pSubquery;
  89468. pItem->pOn = pOn;
  89469. pItem->pUsing = pUsing;
  89470. return p;
  89471. append_from_error:
  89472. assert( p==0 );
  89473. sqlite3ExprDelete(db, pOn);
  89474. sqlite3IdListDelete(db, pUsing);
  89475. sqlite3SelectDelete(db, pSubquery);
  89476. return 0;
  89477. }
  89478. /*
  89479. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  89480. ** element of the source-list passed as the second argument.
  89481. */
  89482. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  89483. assert( pIndexedBy!=0 );
  89484. if( p && ALWAYS(p->nSrc>0) ){
  89485. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  89486. assert( pItem->notIndexed==0 && pItem->zIndexedBy==0 );
  89487. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  89488. /* A "NOT INDEXED" clause was supplied. See parse.y
  89489. ** construct "indexed_opt" for details. */
  89490. pItem->notIndexed = 1;
  89491. }else{
  89492. pItem->zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
  89493. }
  89494. }
  89495. }
  89496. /*
  89497. ** When building up a FROM clause in the parser, the join operator
  89498. ** is initially attached to the left operand. But the code generator
  89499. ** expects the join operator to be on the right operand. This routine
  89500. ** Shifts all join operators from left to right for an entire FROM
  89501. ** clause.
  89502. **
  89503. ** Example: Suppose the join is like this:
  89504. **
  89505. ** A natural cross join B
  89506. **
  89507. ** The operator is "natural cross join". The A and B operands are stored
  89508. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  89509. ** operator with A. This routine shifts that operator over to B.
  89510. */
  89511. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  89512. if( p ){
  89513. int i;
  89514. for(i=p->nSrc-1; i>0; i--){
  89515. p->a[i].jointype = p->a[i-1].jointype;
  89516. }
  89517. p->a[0].jointype = 0;
  89518. }
  89519. }
  89520. /*
  89521. ** Begin a transaction
  89522. */
  89523. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  89524. sqlite3 *db;
  89525. Vdbe *v;
  89526. int i;
  89527. assert( pParse!=0 );
  89528. db = pParse->db;
  89529. assert( db!=0 );
  89530. /* if( db->aDb[0].pBt==0 ) return; */
  89531. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  89532. return;
  89533. }
  89534. v = sqlite3GetVdbe(pParse);
  89535. if( !v ) return;
  89536. if( type!=TK_DEFERRED ){
  89537. for(i=0; i<db->nDb; i++){
  89538. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  89539. sqlite3VdbeUsesBtree(v, i);
  89540. }
  89541. }
  89542. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  89543. }
  89544. /*
  89545. ** Commit a transaction
  89546. */
  89547. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  89548. Vdbe *v;
  89549. assert( pParse!=0 );
  89550. assert( pParse->db!=0 );
  89551. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  89552. return;
  89553. }
  89554. v = sqlite3GetVdbe(pParse);
  89555. if( v ){
  89556. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  89557. }
  89558. }
  89559. /*
  89560. ** Rollback a transaction
  89561. */
  89562. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  89563. Vdbe *v;
  89564. assert( pParse!=0 );
  89565. assert( pParse->db!=0 );
  89566. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  89567. return;
  89568. }
  89569. v = sqlite3GetVdbe(pParse);
  89570. if( v ){
  89571. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  89572. }
  89573. }
  89574. /*
  89575. ** This function is called by the parser when it parses a command to create,
  89576. ** release or rollback an SQL savepoint.
  89577. */
  89578. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  89579. char *zName = sqlite3NameFromToken(pParse->db, pName);
  89580. if( zName ){
  89581. Vdbe *v = sqlite3GetVdbe(pParse);
  89582. #ifndef SQLITE_OMIT_AUTHORIZATION
  89583. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  89584. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  89585. #endif
  89586. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  89587. sqlite3DbFree(pParse->db, zName);
  89588. return;
  89589. }
  89590. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  89591. }
  89592. }
  89593. /*
  89594. ** Make sure the TEMP database is open and available for use. Return
  89595. ** the number of errors. Leave any error messages in the pParse structure.
  89596. */
  89597. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  89598. sqlite3 *db = pParse->db;
  89599. if( db->aDb[1].pBt==0 && !pParse->explain ){
  89600. int rc;
  89601. Btree *pBt;
  89602. static const int flags =
  89603. SQLITE_OPEN_READWRITE |
  89604. SQLITE_OPEN_CREATE |
  89605. SQLITE_OPEN_EXCLUSIVE |
  89606. SQLITE_OPEN_DELETEONCLOSE |
  89607. SQLITE_OPEN_TEMP_DB;
  89608. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  89609. if( rc!=SQLITE_OK ){
  89610. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  89611. "file for storing temporary tables");
  89612. pParse->rc = rc;
  89613. return 1;
  89614. }
  89615. db->aDb[1].pBt = pBt;
  89616. assert( db->aDb[1].pSchema );
  89617. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  89618. db->mallocFailed = 1;
  89619. return 1;
  89620. }
  89621. }
  89622. return 0;
  89623. }
  89624. /*
  89625. ** Record the fact that the schema cookie will need to be verified
  89626. ** for database iDb. The code to actually verify the schema cookie
  89627. ** will occur at the end of the top-level VDBE and will be generated
  89628. ** later, by sqlite3FinishCoding().
  89629. */
  89630. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  89631. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  89632. sqlite3 *db = pToplevel->db;
  89633. assert( iDb>=0 && iDb<db->nDb );
  89634. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  89635. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  89636. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  89637. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  89638. DbMaskSet(pToplevel->cookieMask, iDb);
  89639. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  89640. if( !OMIT_TEMPDB && iDb==1 ){
  89641. sqlite3OpenTempDatabase(pToplevel);
  89642. }
  89643. }
  89644. }
  89645. /*
  89646. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  89647. ** attached database. Otherwise, invoke it for the database named zDb only.
  89648. */
  89649. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  89650. sqlite3 *db = pParse->db;
  89651. int i;
  89652. for(i=0; i<db->nDb; i++){
  89653. Db *pDb = &db->aDb[i];
  89654. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  89655. sqlite3CodeVerifySchema(pParse, i);
  89656. }
  89657. }
  89658. }
  89659. /*
  89660. ** Generate VDBE code that prepares for doing an operation that
  89661. ** might change the database.
  89662. **
  89663. ** This routine starts a new transaction if we are not already within
  89664. ** a transaction. If we are already within a transaction, then a checkpoint
  89665. ** is set if the setStatement parameter is true. A checkpoint should
  89666. ** be set for operations that might fail (due to a constraint) part of
  89667. ** the way through and which will need to undo some writes without having to
  89668. ** rollback the whole transaction. For operations where all constraints
  89669. ** can be checked before any changes are made to the database, it is never
  89670. ** necessary to undo a write and the checkpoint should not be set.
  89671. */
  89672. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  89673. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  89674. sqlite3CodeVerifySchema(pParse, iDb);
  89675. DbMaskSet(pToplevel->writeMask, iDb);
  89676. pToplevel->isMultiWrite |= setStatement;
  89677. }
  89678. /*
  89679. ** Indicate that the statement currently under construction might write
  89680. ** more than one entry (example: deleting one row then inserting another,
  89681. ** inserting multiple rows in a table, or inserting a row and index entries.)
  89682. ** If an abort occurs after some of these writes have completed, then it will
  89683. ** be necessary to undo the completed writes.
  89684. */
  89685. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  89686. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  89687. pToplevel->isMultiWrite = 1;
  89688. }
  89689. /*
  89690. ** The code generator calls this routine if is discovers that it is
  89691. ** possible to abort a statement prior to completion. In order to
  89692. ** perform this abort without corrupting the database, we need to make
  89693. ** sure that the statement is protected by a statement transaction.
  89694. **
  89695. ** Technically, we only need to set the mayAbort flag if the
  89696. ** isMultiWrite flag was previously set. There is a time dependency
  89697. ** such that the abort must occur after the multiwrite. This makes
  89698. ** some statements involving the REPLACE conflict resolution algorithm
  89699. ** go a little faster. But taking advantage of this time dependency
  89700. ** makes it more difficult to prove that the code is correct (in
  89701. ** particular, it prevents us from writing an effective
  89702. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  89703. ** to take the safe route and skip the optimization.
  89704. */
  89705. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  89706. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  89707. pToplevel->mayAbort = 1;
  89708. }
  89709. /*
  89710. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  89711. ** error. The onError parameter determines which (if any) of the statement
  89712. ** and/or current transaction is rolled back.
  89713. */
  89714. SQLITE_PRIVATE void sqlite3HaltConstraint(
  89715. Parse *pParse, /* Parsing context */
  89716. int errCode, /* extended error code */
  89717. int onError, /* Constraint type */
  89718. char *p4, /* Error message */
  89719. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  89720. u8 p5Errmsg /* P5_ErrMsg type */
  89721. ){
  89722. Vdbe *v = sqlite3GetVdbe(pParse);
  89723. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  89724. if( onError==OE_Abort ){
  89725. sqlite3MayAbort(pParse);
  89726. }
  89727. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  89728. if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
  89729. }
  89730. /*
  89731. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  89732. */
  89733. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  89734. Parse *pParse, /* Parsing context */
  89735. int onError, /* Constraint type */
  89736. Index *pIdx /* The index that triggers the constraint */
  89737. ){
  89738. char *zErr;
  89739. int j;
  89740. StrAccum errMsg;
  89741. Table *pTab = pIdx->pTable;
  89742. sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
  89743. for(j=0; j<pIdx->nKeyCol; j++){
  89744. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  89745. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  89746. sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
  89747. sqlite3StrAccumAppend(&errMsg, ".", 1);
  89748. sqlite3StrAccumAppendAll(&errMsg, zCol);
  89749. }
  89750. zErr = sqlite3StrAccumFinish(&errMsg);
  89751. sqlite3HaltConstraint(pParse,
  89752. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  89753. : SQLITE_CONSTRAINT_UNIQUE,
  89754. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  89755. }
  89756. /*
  89757. ** Code an OP_Halt due to non-unique rowid.
  89758. */
  89759. SQLITE_PRIVATE void sqlite3RowidConstraint(
  89760. Parse *pParse, /* Parsing context */
  89761. int onError, /* Conflict resolution algorithm */
  89762. Table *pTab /* The table with the non-unique rowid */
  89763. ){
  89764. char *zMsg;
  89765. int rc;
  89766. if( pTab->iPKey>=0 ){
  89767. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  89768. pTab->aCol[pTab->iPKey].zName);
  89769. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  89770. }else{
  89771. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  89772. rc = SQLITE_CONSTRAINT_ROWID;
  89773. }
  89774. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  89775. P5_ConstraintUnique);
  89776. }
  89777. /*
  89778. ** Check to see if pIndex uses the collating sequence pColl. Return
  89779. ** true if it does and false if it does not.
  89780. */
  89781. #ifndef SQLITE_OMIT_REINDEX
  89782. static int collationMatch(const char *zColl, Index *pIndex){
  89783. int i;
  89784. assert( zColl!=0 );
  89785. for(i=0; i<pIndex->nColumn; i++){
  89786. const char *z = pIndex->azColl[i];
  89787. assert( z!=0 || pIndex->aiColumn[i]<0 );
  89788. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  89789. return 1;
  89790. }
  89791. }
  89792. return 0;
  89793. }
  89794. #endif
  89795. /*
  89796. ** Recompute all indices of pTab that use the collating sequence pColl.
  89797. ** If pColl==0 then recompute all indices of pTab.
  89798. */
  89799. #ifndef SQLITE_OMIT_REINDEX
  89800. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  89801. Index *pIndex; /* An index associated with pTab */
  89802. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  89803. if( zColl==0 || collationMatch(zColl, pIndex) ){
  89804. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  89805. sqlite3BeginWriteOperation(pParse, 0, iDb);
  89806. sqlite3RefillIndex(pParse, pIndex, -1);
  89807. }
  89808. }
  89809. }
  89810. #endif
  89811. /*
  89812. ** Recompute all indices of all tables in all databases where the
  89813. ** indices use the collating sequence pColl. If pColl==0 then recompute
  89814. ** all indices everywhere.
  89815. */
  89816. #ifndef SQLITE_OMIT_REINDEX
  89817. static void reindexDatabases(Parse *pParse, char const *zColl){
  89818. Db *pDb; /* A single database */
  89819. int iDb; /* The database index number */
  89820. sqlite3 *db = pParse->db; /* The database connection */
  89821. HashElem *k; /* For looping over tables in pDb */
  89822. Table *pTab; /* A table in the database */
  89823. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  89824. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  89825. assert( pDb!=0 );
  89826. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  89827. pTab = (Table*)sqliteHashData(k);
  89828. reindexTable(pParse, pTab, zColl);
  89829. }
  89830. }
  89831. }
  89832. #endif
  89833. /*
  89834. ** Generate code for the REINDEX command.
  89835. **
  89836. ** REINDEX -- 1
  89837. ** REINDEX <collation> -- 2
  89838. ** REINDEX ?<database>.?<tablename> -- 3
  89839. ** REINDEX ?<database>.?<indexname> -- 4
  89840. **
  89841. ** Form 1 causes all indices in all attached databases to be rebuilt.
  89842. ** Form 2 rebuilds all indices in all databases that use the named
  89843. ** collating function. Forms 3 and 4 rebuild the named index or all
  89844. ** indices associated with the named table.
  89845. */
  89846. #ifndef SQLITE_OMIT_REINDEX
  89847. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  89848. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  89849. char *z; /* Name of a table or index */
  89850. const char *zDb; /* Name of the database */
  89851. Table *pTab; /* A table in the database */
  89852. Index *pIndex; /* An index associated with pTab */
  89853. int iDb; /* The database index number */
  89854. sqlite3 *db = pParse->db; /* The database connection */
  89855. Token *pObjName; /* Name of the table or index to be reindexed */
  89856. /* Read the database schema. If an error occurs, leave an error message
  89857. ** and code in pParse and return NULL. */
  89858. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  89859. return;
  89860. }
  89861. if( pName1==0 ){
  89862. reindexDatabases(pParse, 0);
  89863. return;
  89864. }else if( NEVER(pName2==0) || pName2->z==0 ){
  89865. char *zColl;
  89866. assert( pName1->z );
  89867. zColl = sqlite3NameFromToken(pParse->db, pName1);
  89868. if( !zColl ) return;
  89869. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  89870. if( pColl ){
  89871. reindexDatabases(pParse, zColl);
  89872. sqlite3DbFree(db, zColl);
  89873. return;
  89874. }
  89875. sqlite3DbFree(db, zColl);
  89876. }
  89877. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  89878. if( iDb<0 ) return;
  89879. z = sqlite3NameFromToken(db, pObjName);
  89880. if( z==0 ) return;
  89881. zDb = db->aDb[iDb].zName;
  89882. pTab = sqlite3FindTable(db, z, zDb);
  89883. if( pTab ){
  89884. reindexTable(pParse, pTab, 0);
  89885. sqlite3DbFree(db, z);
  89886. return;
  89887. }
  89888. pIndex = sqlite3FindIndex(db, z, zDb);
  89889. sqlite3DbFree(db, z);
  89890. if( pIndex ){
  89891. sqlite3BeginWriteOperation(pParse, 0, iDb);
  89892. sqlite3RefillIndex(pParse, pIndex, -1);
  89893. return;
  89894. }
  89895. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  89896. }
  89897. #endif
  89898. /*
  89899. ** Return a KeyInfo structure that is appropriate for the given Index.
  89900. **
  89901. ** The KeyInfo structure for an index is cached in the Index object.
  89902. ** So there might be multiple references to the returned pointer. The
  89903. ** caller should not try to modify the KeyInfo object.
  89904. **
  89905. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  89906. ** when it has finished using it.
  89907. */
  89908. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  89909. int i;
  89910. int nCol = pIdx->nColumn;
  89911. int nKey = pIdx->nKeyCol;
  89912. KeyInfo *pKey;
  89913. if( pParse->nErr ) return 0;
  89914. if( pIdx->uniqNotNull ){
  89915. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  89916. }else{
  89917. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  89918. }
  89919. if( pKey ){
  89920. assert( sqlite3KeyInfoIsWriteable(pKey) );
  89921. for(i=0; i<nCol; i++){
  89922. char *zColl = pIdx->azColl[i];
  89923. assert( zColl!=0 );
  89924. pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
  89925. sqlite3LocateCollSeq(pParse, zColl);
  89926. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  89927. }
  89928. if( pParse->nErr ){
  89929. sqlite3KeyInfoUnref(pKey);
  89930. pKey = 0;
  89931. }
  89932. }
  89933. return pKey;
  89934. }
  89935. #ifndef SQLITE_OMIT_CTE
  89936. /*
  89937. ** This routine is invoked once per CTE by the parser while parsing a
  89938. ** WITH clause.
  89939. */
  89940. SQLITE_PRIVATE With *sqlite3WithAdd(
  89941. Parse *pParse, /* Parsing context */
  89942. With *pWith, /* Existing WITH clause, or NULL */
  89943. Token *pName, /* Name of the common-table */
  89944. ExprList *pArglist, /* Optional column name list for the table */
  89945. Select *pQuery /* Query used to initialize the table */
  89946. ){
  89947. sqlite3 *db = pParse->db;
  89948. With *pNew;
  89949. char *zName;
  89950. /* Check that the CTE name is unique within this WITH clause. If
  89951. ** not, store an error in the Parse structure. */
  89952. zName = sqlite3NameFromToken(pParse->db, pName);
  89953. if( zName && pWith ){
  89954. int i;
  89955. for(i=0; i<pWith->nCte; i++){
  89956. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  89957. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  89958. }
  89959. }
  89960. }
  89961. if( pWith ){
  89962. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  89963. pNew = sqlite3DbRealloc(db, pWith, nByte);
  89964. }else{
  89965. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  89966. }
  89967. assert( zName!=0 || pNew==0 );
  89968. assert( db->mallocFailed==0 || pNew==0 );
  89969. if( pNew==0 ){
  89970. sqlite3ExprListDelete(db, pArglist);
  89971. sqlite3SelectDelete(db, pQuery);
  89972. sqlite3DbFree(db, zName);
  89973. pNew = pWith;
  89974. }else{
  89975. pNew->a[pNew->nCte].pSelect = pQuery;
  89976. pNew->a[pNew->nCte].pCols = pArglist;
  89977. pNew->a[pNew->nCte].zName = zName;
  89978. pNew->a[pNew->nCte].zErr = 0;
  89979. pNew->nCte++;
  89980. }
  89981. return pNew;
  89982. }
  89983. /*
  89984. ** Free the contents of the With object passed as the second argument.
  89985. */
  89986. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  89987. if( pWith ){
  89988. int i;
  89989. for(i=0; i<pWith->nCte; i++){
  89990. struct Cte *pCte = &pWith->a[i];
  89991. sqlite3ExprListDelete(db, pCte->pCols);
  89992. sqlite3SelectDelete(db, pCte->pSelect);
  89993. sqlite3DbFree(db, pCte->zName);
  89994. }
  89995. sqlite3DbFree(db, pWith);
  89996. }
  89997. }
  89998. #endif /* !defined(SQLITE_OMIT_CTE) */
  89999. /************** End of build.c ***********************************************/
  90000. /************** Begin file callback.c ****************************************/
  90001. /*
  90002. ** 2005 May 23
  90003. **
  90004. ** The author disclaims copyright to this source code. In place of
  90005. ** a legal notice, here is a blessing:
  90006. **
  90007. ** May you do good and not evil.
  90008. ** May you find forgiveness for yourself and forgive others.
  90009. ** May you share freely, never taking more than you give.
  90010. **
  90011. *************************************************************************
  90012. **
  90013. ** This file contains functions used to access the internal hash tables
  90014. ** of user defined functions and collation sequences.
  90015. */
  90016. /* #include "sqliteInt.h" */
  90017. /*
  90018. ** Invoke the 'collation needed' callback to request a collation sequence
  90019. ** in the encoding enc of name zName, length nName.
  90020. */
  90021. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  90022. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  90023. if( db->xCollNeeded ){
  90024. char *zExternal = sqlite3DbStrDup(db, zName);
  90025. if( !zExternal ) return;
  90026. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  90027. sqlite3DbFree(db, zExternal);
  90028. }
  90029. #ifndef SQLITE_OMIT_UTF16
  90030. if( db->xCollNeeded16 ){
  90031. char const *zExternal;
  90032. sqlite3_value *pTmp = sqlite3ValueNew(db);
  90033. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  90034. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  90035. if( zExternal ){
  90036. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  90037. }
  90038. sqlite3ValueFree(pTmp);
  90039. }
  90040. #endif
  90041. }
  90042. /*
  90043. ** This routine is called if the collation factory fails to deliver a
  90044. ** collation function in the best encoding but there may be other versions
  90045. ** of this collation function (for other text encodings) available. Use one
  90046. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  90047. ** possible.
  90048. */
  90049. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  90050. CollSeq *pColl2;
  90051. char *z = pColl->zName;
  90052. int i;
  90053. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  90054. for(i=0; i<3; i++){
  90055. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  90056. if( pColl2->xCmp!=0 ){
  90057. memcpy(pColl, pColl2, sizeof(CollSeq));
  90058. pColl->xDel = 0; /* Do not copy the destructor */
  90059. return SQLITE_OK;
  90060. }
  90061. }
  90062. return SQLITE_ERROR;
  90063. }
  90064. /*
  90065. ** This function is responsible for invoking the collation factory callback
  90066. ** or substituting a collation sequence of a different encoding when the
  90067. ** requested collation sequence is not available in the desired encoding.
  90068. **
  90069. ** If it is not NULL, then pColl must point to the database native encoding
  90070. ** collation sequence with name zName, length nName.
  90071. **
  90072. ** The return value is either the collation sequence to be used in database
  90073. ** db for collation type name zName, length nName, or NULL, if no collation
  90074. ** sequence can be found. If no collation is found, leave an error message.
  90075. **
  90076. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  90077. */
  90078. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  90079. Parse *pParse, /* Parsing context */
  90080. u8 enc, /* The desired encoding for the collating sequence */
  90081. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  90082. const char *zName /* Collating sequence name */
  90083. ){
  90084. CollSeq *p;
  90085. sqlite3 *db = pParse->db;
  90086. p = pColl;
  90087. if( !p ){
  90088. p = sqlite3FindCollSeq(db, enc, zName, 0);
  90089. }
  90090. if( !p || !p->xCmp ){
  90091. /* No collation sequence of this type for this encoding is registered.
  90092. ** Call the collation factory to see if it can supply us with one.
  90093. */
  90094. callCollNeeded(db, enc, zName);
  90095. p = sqlite3FindCollSeq(db, enc, zName, 0);
  90096. }
  90097. if( p && !p->xCmp && synthCollSeq(db, p) ){
  90098. p = 0;
  90099. }
  90100. assert( !p || p->xCmp );
  90101. if( p==0 ){
  90102. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  90103. }
  90104. return p;
  90105. }
  90106. /*
  90107. ** This routine is called on a collation sequence before it is used to
  90108. ** check that it is defined. An undefined collation sequence exists when
  90109. ** a database is loaded that contains references to collation sequences
  90110. ** that have not been defined by sqlite3_create_collation() etc.
  90111. **
  90112. ** If required, this routine calls the 'collation needed' callback to
  90113. ** request a definition of the collating sequence. If this doesn't work,
  90114. ** an equivalent collating sequence that uses a text encoding different
  90115. ** from the main database is substituted, if one is available.
  90116. */
  90117. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  90118. if( pColl ){
  90119. const char *zName = pColl->zName;
  90120. sqlite3 *db = pParse->db;
  90121. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  90122. if( !p ){
  90123. return SQLITE_ERROR;
  90124. }
  90125. assert( p==pColl );
  90126. }
  90127. return SQLITE_OK;
  90128. }
  90129. /*
  90130. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  90131. ** specified by zName and nName is not found and parameter 'create' is
  90132. ** true, then create a new entry. Otherwise return NULL.
  90133. **
  90134. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  90135. ** array of three CollSeq structures. The first is the collation sequence
  90136. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  90137. **
  90138. ** Stored immediately after the three collation sequences is a copy of
  90139. ** the collation sequence name. A pointer to this string is stored in
  90140. ** each collation sequence structure.
  90141. */
  90142. static CollSeq *findCollSeqEntry(
  90143. sqlite3 *db, /* Database connection */
  90144. const char *zName, /* Name of the collating sequence */
  90145. int create /* Create a new entry if true */
  90146. ){
  90147. CollSeq *pColl;
  90148. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  90149. if( 0==pColl && create ){
  90150. int nName = sqlite3Strlen30(zName);
  90151. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  90152. if( pColl ){
  90153. CollSeq *pDel = 0;
  90154. pColl[0].zName = (char*)&pColl[3];
  90155. pColl[0].enc = SQLITE_UTF8;
  90156. pColl[1].zName = (char*)&pColl[3];
  90157. pColl[1].enc = SQLITE_UTF16LE;
  90158. pColl[2].zName = (char*)&pColl[3];
  90159. pColl[2].enc = SQLITE_UTF16BE;
  90160. memcpy(pColl[0].zName, zName, nName);
  90161. pColl[0].zName[nName] = 0;
  90162. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  90163. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  90164. ** return the pColl pointer to be deleted (because it wasn't added
  90165. ** to the hash table).
  90166. */
  90167. assert( pDel==0 || pDel==pColl );
  90168. if( pDel!=0 ){
  90169. db->mallocFailed = 1;
  90170. sqlite3DbFree(db, pDel);
  90171. pColl = 0;
  90172. }
  90173. }
  90174. }
  90175. return pColl;
  90176. }
  90177. /*
  90178. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  90179. ** Return the CollSeq* pointer for the collation sequence named zName
  90180. ** for the encoding 'enc' from the database 'db'.
  90181. **
  90182. ** If the entry specified is not found and 'create' is true, then create a
  90183. ** new entry. Otherwise return NULL.
  90184. **
  90185. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  90186. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  90187. ** if necessary and generates an error message if the collating sequence
  90188. ** cannot be found.
  90189. **
  90190. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  90191. */
  90192. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  90193. sqlite3 *db,
  90194. u8 enc,
  90195. const char *zName,
  90196. int create
  90197. ){
  90198. CollSeq *pColl;
  90199. if( zName ){
  90200. pColl = findCollSeqEntry(db, zName, create);
  90201. }else{
  90202. pColl = db->pDfltColl;
  90203. }
  90204. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  90205. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  90206. if( pColl ) pColl += enc-1;
  90207. return pColl;
  90208. }
  90209. /* During the search for the best function definition, this procedure
  90210. ** is called to test how well the function passed as the first argument
  90211. ** matches the request for a function with nArg arguments in a system
  90212. ** that uses encoding enc. The value returned indicates how well the
  90213. ** request is matched. A higher value indicates a better match.
  90214. **
  90215. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  90216. ** is also -1. In other words, we are searching for a function that
  90217. ** takes a variable number of arguments.
  90218. **
  90219. ** If nArg is -2 that means that we are searching for any function
  90220. ** regardless of the number of arguments it uses, so return a positive
  90221. ** match score for any
  90222. **
  90223. ** The returned value is always between 0 and 6, as follows:
  90224. **
  90225. ** 0: Not a match.
  90226. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  90227. ** 2: UTF16 byte order change required and function takes any number of args.
  90228. ** 3: encoding matches and function takes any number of arguments
  90229. ** 4: UTF8/16 conversion required - argument count matches exactly
  90230. ** 5: UTF16 byte order conversion required - argument count matches exactly
  90231. ** 6: Perfect match: encoding and argument count match exactly.
  90232. **
  90233. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  90234. ** a perfect match and any function with both xStep and xFunc NULL is
  90235. ** a non-match.
  90236. */
  90237. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  90238. static int matchQuality(
  90239. FuncDef *p, /* The function we are evaluating for match quality */
  90240. int nArg, /* Desired number of arguments. (-1)==any */
  90241. u8 enc /* Desired text encoding */
  90242. ){
  90243. int match;
  90244. /* nArg of -2 is a special case */
  90245. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  90246. /* Wrong number of arguments means "no match" */
  90247. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  90248. /* Give a better score to a function with a specific number of arguments
  90249. ** than to function that accepts any number of arguments. */
  90250. if( p->nArg==nArg ){
  90251. match = 4;
  90252. }else{
  90253. match = 1;
  90254. }
  90255. /* Bonus points if the text encoding matches */
  90256. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  90257. match += 2; /* Exact encoding match */
  90258. }else if( (enc & p->funcFlags & 2)!=0 ){
  90259. match += 1; /* Both are UTF16, but with different byte orders */
  90260. }
  90261. return match;
  90262. }
  90263. /*
  90264. ** Search a FuncDefHash for a function with the given name. Return
  90265. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  90266. */
  90267. static FuncDef *functionSearch(
  90268. FuncDefHash *pHash, /* Hash table to search */
  90269. int h, /* Hash of the name */
  90270. const char *zFunc, /* Name of function */
  90271. int nFunc /* Number of bytes in zFunc */
  90272. ){
  90273. FuncDef *p;
  90274. for(p=pHash->a[h]; p; p=p->pHash){
  90275. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  90276. return p;
  90277. }
  90278. }
  90279. return 0;
  90280. }
  90281. /*
  90282. ** Insert a new FuncDef into a FuncDefHash hash table.
  90283. */
  90284. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  90285. FuncDefHash *pHash, /* The hash table into which to insert */
  90286. FuncDef *pDef /* The function definition to insert */
  90287. ){
  90288. FuncDef *pOther;
  90289. int nName = sqlite3Strlen30(pDef->zName);
  90290. u8 c1 = (u8)pDef->zName[0];
  90291. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  90292. pOther = functionSearch(pHash, h, pDef->zName, nName);
  90293. if( pOther ){
  90294. assert( pOther!=pDef && pOther->pNext!=pDef );
  90295. pDef->pNext = pOther->pNext;
  90296. pOther->pNext = pDef;
  90297. }else{
  90298. pDef->pNext = 0;
  90299. pDef->pHash = pHash->a[h];
  90300. pHash->a[h] = pDef;
  90301. }
  90302. }
  90303. /*
  90304. ** Locate a user function given a name, a number of arguments and a flag
  90305. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  90306. ** pointer to the FuncDef structure that defines that function, or return
  90307. ** NULL if the function does not exist.
  90308. **
  90309. ** If the createFlag argument is true, then a new (blank) FuncDef
  90310. ** structure is created and liked into the "db" structure if a
  90311. ** no matching function previously existed.
  90312. **
  90313. ** If nArg is -2, then the first valid function found is returned. A
  90314. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  90315. ** case is used to see if zName is a valid function name for some number
  90316. ** of arguments. If nArg is -2, then createFlag must be 0.
  90317. **
  90318. ** If createFlag is false, then a function with the required name and
  90319. ** number of arguments may be returned even if the eTextRep flag does not
  90320. ** match that requested.
  90321. */
  90322. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  90323. sqlite3 *db, /* An open database */
  90324. const char *zName, /* Name of the function. Not null-terminated */
  90325. int nName, /* Number of characters in the name */
  90326. int nArg, /* Number of arguments. -1 means any number */
  90327. u8 enc, /* Preferred text encoding */
  90328. u8 createFlag /* Create new entry if true and does not otherwise exist */
  90329. ){
  90330. FuncDef *p; /* Iterator variable */
  90331. FuncDef *pBest = 0; /* Best match found so far */
  90332. int bestScore = 0; /* Score of best match */
  90333. int h; /* Hash value */
  90334. assert( nArg>=(-2) );
  90335. assert( nArg>=(-1) || createFlag==0 );
  90336. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  90337. /* First search for a match amongst the application-defined functions.
  90338. */
  90339. p = functionSearch(&db->aFunc, h, zName, nName);
  90340. while( p ){
  90341. int score = matchQuality(p, nArg, enc);
  90342. if( score>bestScore ){
  90343. pBest = p;
  90344. bestScore = score;
  90345. }
  90346. p = p->pNext;
  90347. }
  90348. /* If no match is found, search the built-in functions.
  90349. **
  90350. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  90351. ** functions even if a prior app-defined function was found. And give
  90352. ** priority to built-in functions.
  90353. **
  90354. ** Except, if createFlag is true, that means that we are trying to
  90355. ** install a new function. Whatever FuncDef structure is returned it will
  90356. ** have fields overwritten with new information appropriate for the
  90357. ** new function. But the FuncDefs for built-in functions are read-only.
  90358. ** So we must not search for built-ins when creating a new function.
  90359. */
  90360. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  90361. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  90362. bestScore = 0;
  90363. p = functionSearch(pHash, h, zName, nName);
  90364. while( p ){
  90365. int score = matchQuality(p, nArg, enc);
  90366. if( score>bestScore ){
  90367. pBest = p;
  90368. bestScore = score;
  90369. }
  90370. p = p->pNext;
  90371. }
  90372. }
  90373. /* If the createFlag parameter is true and the search did not reveal an
  90374. ** exact match for the name, number of arguments and encoding, then add a
  90375. ** new entry to the hash table and return it.
  90376. */
  90377. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  90378. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  90379. pBest->zName = (char *)&pBest[1];
  90380. pBest->nArg = (u16)nArg;
  90381. pBest->funcFlags = enc;
  90382. memcpy(pBest->zName, zName, nName);
  90383. pBest->zName[nName] = 0;
  90384. sqlite3FuncDefInsert(&db->aFunc, pBest);
  90385. }
  90386. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  90387. return pBest;
  90388. }
  90389. return 0;
  90390. }
  90391. /*
  90392. ** Free all resources held by the schema structure. The void* argument points
  90393. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  90394. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  90395. ** of the schema hash tables).
  90396. **
  90397. ** The Schema.cache_size variable is not cleared.
  90398. */
  90399. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  90400. Hash temp1;
  90401. Hash temp2;
  90402. HashElem *pElem;
  90403. Schema *pSchema = (Schema *)p;
  90404. temp1 = pSchema->tblHash;
  90405. temp2 = pSchema->trigHash;
  90406. sqlite3HashInit(&pSchema->trigHash);
  90407. sqlite3HashClear(&pSchema->idxHash);
  90408. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  90409. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  90410. }
  90411. sqlite3HashClear(&temp2);
  90412. sqlite3HashInit(&pSchema->tblHash);
  90413. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  90414. Table *pTab = sqliteHashData(pElem);
  90415. sqlite3DeleteTable(0, pTab);
  90416. }
  90417. sqlite3HashClear(&temp1);
  90418. sqlite3HashClear(&pSchema->fkeyHash);
  90419. pSchema->pSeqTab = 0;
  90420. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  90421. pSchema->iGeneration++;
  90422. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  90423. }
  90424. }
  90425. /*
  90426. ** Find and return the schema associated with a BTree. Create
  90427. ** a new one if necessary.
  90428. */
  90429. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  90430. Schema * p;
  90431. if( pBt ){
  90432. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  90433. }else{
  90434. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  90435. }
  90436. if( !p ){
  90437. db->mallocFailed = 1;
  90438. }else if ( 0==p->file_format ){
  90439. sqlite3HashInit(&p->tblHash);
  90440. sqlite3HashInit(&p->idxHash);
  90441. sqlite3HashInit(&p->trigHash);
  90442. sqlite3HashInit(&p->fkeyHash);
  90443. p->enc = SQLITE_UTF8;
  90444. }
  90445. return p;
  90446. }
  90447. /************** End of callback.c ********************************************/
  90448. /************** Begin file delete.c ******************************************/
  90449. /*
  90450. ** 2001 September 15
  90451. **
  90452. ** The author disclaims copyright to this source code. In place of
  90453. ** a legal notice, here is a blessing:
  90454. **
  90455. ** May you do good and not evil.
  90456. ** May you find forgiveness for yourself and forgive others.
  90457. ** May you share freely, never taking more than you give.
  90458. **
  90459. *************************************************************************
  90460. ** This file contains C code routines that are called by the parser
  90461. ** in order to generate code for DELETE FROM statements.
  90462. */
  90463. /* #include "sqliteInt.h" */
  90464. /*
  90465. ** While a SrcList can in general represent multiple tables and subqueries
  90466. ** (as in the FROM clause of a SELECT statement) in this case it contains
  90467. ** the name of a single table, as one might find in an INSERT, DELETE,
  90468. ** or UPDATE statement. Look up that table in the symbol table and
  90469. ** return a pointer. Set an error message and return NULL if the table
  90470. ** name is not found or if any other error occurs.
  90471. **
  90472. ** The following fields are initialized appropriate in pSrc:
  90473. **
  90474. ** pSrc->a[0].pTab Pointer to the Table object
  90475. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  90476. **
  90477. */
  90478. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  90479. struct SrcList_item *pItem = pSrc->a;
  90480. Table *pTab;
  90481. assert( pItem && pSrc->nSrc==1 );
  90482. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  90483. sqlite3DeleteTable(pParse->db, pItem->pTab);
  90484. pItem->pTab = pTab;
  90485. if( pTab ){
  90486. pTab->nRef++;
  90487. }
  90488. if( sqlite3IndexedByLookup(pParse, pItem) ){
  90489. pTab = 0;
  90490. }
  90491. return pTab;
  90492. }
  90493. /*
  90494. ** Check to make sure the given table is writable. If it is not
  90495. ** writable, generate an error message and return 1. If it is
  90496. ** writable return 0;
  90497. */
  90498. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  90499. /* A table is not writable under the following circumstances:
  90500. **
  90501. ** 1) It is a virtual table and no implementation of the xUpdate method
  90502. ** has been provided, or
  90503. ** 2) It is a system table (i.e. sqlite_master), this call is not
  90504. ** part of a nested parse and writable_schema pragma has not
  90505. ** been specified.
  90506. **
  90507. ** In either case leave an error message in pParse and return non-zero.
  90508. */
  90509. if( ( IsVirtual(pTab)
  90510. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  90511. || ( (pTab->tabFlags & TF_Readonly)!=0
  90512. && (pParse->db->flags & SQLITE_WriteSchema)==0
  90513. && pParse->nested==0 )
  90514. ){
  90515. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  90516. return 1;
  90517. }
  90518. #ifndef SQLITE_OMIT_VIEW
  90519. if( !viewOk && pTab->pSelect ){
  90520. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  90521. return 1;
  90522. }
  90523. #endif
  90524. return 0;
  90525. }
  90526. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  90527. /*
  90528. ** Evaluate a view and store its result in an ephemeral table. The
  90529. ** pWhere argument is an optional WHERE clause that restricts the
  90530. ** set of rows in the view that are to be added to the ephemeral table.
  90531. */
  90532. SQLITE_PRIVATE void sqlite3MaterializeView(
  90533. Parse *pParse, /* Parsing context */
  90534. Table *pView, /* View definition */
  90535. Expr *pWhere, /* Optional WHERE clause to be added */
  90536. int iCur /* Cursor number for ephemeral table */
  90537. ){
  90538. SelectDest dest;
  90539. Select *pSel;
  90540. SrcList *pFrom;
  90541. sqlite3 *db = pParse->db;
  90542. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  90543. pWhere = sqlite3ExprDup(db, pWhere, 0);
  90544. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  90545. if( pFrom ){
  90546. assert( pFrom->nSrc==1 );
  90547. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  90548. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  90549. assert( pFrom->a[0].pOn==0 );
  90550. assert( pFrom->a[0].pUsing==0 );
  90551. }
  90552. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  90553. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  90554. sqlite3Select(pParse, pSel, &dest);
  90555. sqlite3SelectDelete(db, pSel);
  90556. }
  90557. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  90558. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  90559. /*
  90560. ** Generate an expression tree to implement the WHERE, ORDER BY,
  90561. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  90562. **
  90563. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  90564. ** \__________________________/
  90565. ** pLimitWhere (pInClause)
  90566. */
  90567. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  90568. Parse *pParse, /* The parser context */
  90569. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  90570. Expr *pWhere, /* The WHERE clause. May be null */
  90571. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  90572. Expr *pLimit, /* The LIMIT clause. May be null */
  90573. Expr *pOffset, /* The OFFSET clause. May be null */
  90574. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  90575. ){
  90576. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  90577. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  90578. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  90579. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  90580. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  90581. Select *pSelect = NULL; /* Complete SELECT tree */
  90582. /* Check that there isn't an ORDER BY without a LIMIT clause.
  90583. */
  90584. if( pOrderBy && (pLimit == 0) ) {
  90585. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  90586. goto limit_where_cleanup_2;
  90587. }
  90588. /* We only need to generate a select expression if there
  90589. ** is a limit/offset term to enforce.
  90590. */
  90591. if( pLimit == 0 ) {
  90592. /* if pLimit is null, pOffset will always be null as well. */
  90593. assert( pOffset == 0 );
  90594. return pWhere;
  90595. }
  90596. /* Generate a select expression tree to enforce the limit/offset
  90597. ** term for the DELETE or UPDATE statement. For example:
  90598. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  90599. ** becomes:
  90600. ** DELETE FROM table_a WHERE rowid IN (
  90601. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  90602. ** );
  90603. */
  90604. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  90605. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  90606. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  90607. if( pEList == 0 ) goto limit_where_cleanup_2;
  90608. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  90609. ** and the SELECT subtree. */
  90610. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  90611. if( pSelectSrc == 0 ) {
  90612. sqlite3ExprListDelete(pParse->db, pEList);
  90613. goto limit_where_cleanup_2;
  90614. }
  90615. /* generate the SELECT expression tree. */
  90616. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  90617. pOrderBy,0,pLimit,pOffset);
  90618. if( pSelect == 0 ) return 0;
  90619. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  90620. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  90621. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  90622. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  90623. if( pInClause == 0 ) goto limit_where_cleanup_1;
  90624. pInClause->x.pSelect = pSelect;
  90625. pInClause->flags |= EP_xIsSelect;
  90626. sqlite3ExprSetHeightAndFlags(pParse, pInClause);
  90627. return pInClause;
  90628. /* something went wrong. clean up anything allocated. */
  90629. limit_where_cleanup_1:
  90630. sqlite3SelectDelete(pParse->db, pSelect);
  90631. return 0;
  90632. limit_where_cleanup_2:
  90633. sqlite3ExprDelete(pParse->db, pWhere);
  90634. sqlite3ExprListDelete(pParse->db, pOrderBy);
  90635. sqlite3ExprDelete(pParse->db, pLimit);
  90636. sqlite3ExprDelete(pParse->db, pOffset);
  90637. return 0;
  90638. }
  90639. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  90640. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  90641. /*
  90642. ** Generate code for a DELETE FROM statement.
  90643. **
  90644. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  90645. ** \________/ \________________/
  90646. ** pTabList pWhere
  90647. */
  90648. SQLITE_PRIVATE void sqlite3DeleteFrom(
  90649. Parse *pParse, /* The parser context */
  90650. SrcList *pTabList, /* The table from which we should delete things */
  90651. Expr *pWhere /* The WHERE clause. May be null */
  90652. ){
  90653. Vdbe *v; /* The virtual database engine */
  90654. Table *pTab; /* The table from which records will be deleted */
  90655. const char *zDb; /* Name of database holding pTab */
  90656. int i; /* Loop counter */
  90657. WhereInfo *pWInfo; /* Information about the WHERE clause */
  90658. Index *pIdx; /* For looping over indices of the table */
  90659. int iTabCur; /* Cursor number for the table */
  90660. int iDataCur = 0; /* VDBE cursor for the canonical data source */
  90661. int iIdxCur = 0; /* Cursor number of the first index */
  90662. int nIdx; /* Number of indices */
  90663. sqlite3 *db; /* Main database structure */
  90664. AuthContext sContext; /* Authorization context */
  90665. NameContext sNC; /* Name context to resolve expressions in */
  90666. int iDb; /* Database number */
  90667. int memCnt = -1; /* Memory cell used for change counting */
  90668. int rcauth; /* Value returned by authorization callback */
  90669. int okOnePass; /* True for one-pass algorithm without the FIFO */
  90670. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  90671. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  90672. Index *pPk; /* The PRIMARY KEY index on the table */
  90673. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  90674. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  90675. int iKey; /* Memory cell holding key of row to be deleted */
  90676. i16 nKey; /* Number of memory cells in the row key */
  90677. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  90678. int iRowSet = 0; /* Register for rowset of rows to delete */
  90679. int addrBypass = 0; /* Address of jump over the delete logic */
  90680. int addrLoop = 0; /* Top of the delete loop */
  90681. int addrDelete = 0; /* Jump directly to the delete logic */
  90682. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  90683. #ifndef SQLITE_OMIT_TRIGGER
  90684. int isView; /* True if attempting to delete from a view */
  90685. Trigger *pTrigger; /* List of table triggers, if required */
  90686. #endif
  90687. memset(&sContext, 0, sizeof(sContext));
  90688. db = pParse->db;
  90689. if( pParse->nErr || db->mallocFailed ){
  90690. goto delete_from_cleanup;
  90691. }
  90692. assert( pTabList->nSrc==1 );
  90693. /* Locate the table which we want to delete. This table has to be
  90694. ** put in an SrcList structure because some of the subroutines we
  90695. ** will be calling are designed to work with multiple tables and expect
  90696. ** an SrcList* parameter instead of just a Table* parameter.
  90697. */
  90698. pTab = sqlite3SrcListLookup(pParse, pTabList);
  90699. if( pTab==0 ) goto delete_from_cleanup;
  90700. /* Figure out if we have any triggers and if the table being
  90701. ** deleted from is a view
  90702. */
  90703. #ifndef SQLITE_OMIT_TRIGGER
  90704. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  90705. isView = pTab->pSelect!=0;
  90706. #else
  90707. # define pTrigger 0
  90708. # define isView 0
  90709. #endif
  90710. #ifdef SQLITE_OMIT_VIEW
  90711. # undef isView
  90712. # define isView 0
  90713. #endif
  90714. /* If pTab is really a view, make sure it has been initialized.
  90715. */
  90716. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  90717. goto delete_from_cleanup;
  90718. }
  90719. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  90720. goto delete_from_cleanup;
  90721. }
  90722. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90723. assert( iDb<db->nDb );
  90724. zDb = db->aDb[iDb].zName;
  90725. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  90726. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  90727. if( rcauth==SQLITE_DENY ){
  90728. goto delete_from_cleanup;
  90729. }
  90730. assert(!isView || pTrigger);
  90731. /* Assign cursor numbers to the table and all its indices.
  90732. */
  90733. assert( pTabList->nSrc==1 );
  90734. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  90735. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  90736. pParse->nTab++;
  90737. }
  90738. /* Start the view context
  90739. */
  90740. if( isView ){
  90741. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  90742. }
  90743. /* Begin generating code.
  90744. */
  90745. v = sqlite3GetVdbe(pParse);
  90746. if( v==0 ){
  90747. goto delete_from_cleanup;
  90748. }
  90749. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  90750. sqlite3BeginWriteOperation(pParse, 1, iDb);
  90751. /* If we are trying to delete from a view, realize that view into
  90752. ** an ephemeral table.
  90753. */
  90754. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  90755. if( isView ){
  90756. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  90757. iDataCur = iIdxCur = iTabCur;
  90758. }
  90759. #endif
  90760. /* Resolve the column names in the WHERE clause.
  90761. */
  90762. memset(&sNC, 0, sizeof(sNC));
  90763. sNC.pParse = pParse;
  90764. sNC.pSrcList = pTabList;
  90765. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  90766. goto delete_from_cleanup;
  90767. }
  90768. /* Initialize the counter of the number of rows deleted, if
  90769. ** we are counting rows.
  90770. */
  90771. if( db->flags & SQLITE_CountRows ){
  90772. memCnt = ++pParse->nMem;
  90773. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  90774. }
  90775. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  90776. /* Special case: A DELETE without a WHERE clause deletes everything.
  90777. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  90778. ** this optimization caused the row change count (the value returned by
  90779. ** API function sqlite3_count_changes) to be set incorrectly. */
  90780. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  90781. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  90782. ){
  90783. assert( !isView );
  90784. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  90785. if( HasRowid(pTab) ){
  90786. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  90787. pTab->zName, P4_STATIC);
  90788. }
  90789. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  90790. assert( pIdx->pSchema==pTab->pSchema );
  90791. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  90792. }
  90793. }else
  90794. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  90795. {
  90796. if( HasRowid(pTab) ){
  90797. /* For a rowid table, initialize the RowSet to an empty set */
  90798. pPk = 0;
  90799. nPk = 1;
  90800. iRowSet = ++pParse->nMem;
  90801. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  90802. }else{
  90803. /* For a WITHOUT ROWID table, create an ephemeral table used to
  90804. ** hold all primary keys for rows to be deleted. */
  90805. pPk = sqlite3PrimaryKeyIndex(pTab);
  90806. assert( pPk!=0 );
  90807. nPk = pPk->nKeyCol;
  90808. iPk = pParse->nMem+1;
  90809. pParse->nMem += nPk;
  90810. iEphCur = pParse->nTab++;
  90811. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  90812. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  90813. }
  90814. /* Construct a query to find the rowid or primary key for every row
  90815. ** to be deleted, based on the WHERE clause.
  90816. */
  90817. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  90818. WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
  90819. iTabCur+1);
  90820. if( pWInfo==0 ) goto delete_from_cleanup;
  90821. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  90822. /* Keep track of the number of rows to be deleted */
  90823. if( db->flags & SQLITE_CountRows ){
  90824. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  90825. }
  90826. /* Extract the rowid or primary key for the current row */
  90827. if( pPk ){
  90828. for(i=0; i<nPk; i++){
  90829. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  90830. pPk->aiColumn[i], iPk+i);
  90831. }
  90832. iKey = iPk;
  90833. }else{
  90834. iKey = pParse->nMem + 1;
  90835. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  90836. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  90837. }
  90838. if( okOnePass ){
  90839. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  90840. ** one, so just keep it in its register(s) and fall through to the
  90841. ** delete code.
  90842. */
  90843. nKey = nPk; /* OP_Found will use an unpacked key */
  90844. aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
  90845. if( aToOpen==0 ){
  90846. sqlite3WhereEnd(pWInfo);
  90847. goto delete_from_cleanup;
  90848. }
  90849. memset(aToOpen, 1, nIdx+1);
  90850. aToOpen[nIdx+1] = 0;
  90851. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  90852. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  90853. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  90854. addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
  90855. }else if( pPk ){
  90856. /* Construct a composite key for the row to be deleted and remember it */
  90857. iKey = ++pParse->nMem;
  90858. nKey = 0; /* Zero tells OP_Found to use a composite key */
  90859. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  90860. sqlite3IndexAffinityStr(v, pPk), nPk);
  90861. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
  90862. }else{
  90863. /* Get the rowid of the row to be deleted and remember it in the RowSet */
  90864. nKey = 1; /* OP_Seek always uses a single rowid */
  90865. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  90866. }
  90867. /* End of the WHERE loop */
  90868. sqlite3WhereEnd(pWInfo);
  90869. if( okOnePass ){
  90870. /* Bypass the delete logic below if the WHERE loop found zero rows */
  90871. addrBypass = sqlite3VdbeMakeLabel(v);
  90872. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
  90873. sqlite3VdbeJumpHere(v, addrDelete);
  90874. }
  90875. /* Unless this is a view, open cursors for the table we are
  90876. ** deleting from and all its indices. If this is a view, then the
  90877. ** only effect this statement has is to fire the INSTEAD OF
  90878. ** triggers.
  90879. */
  90880. if( !isView ){
  90881. testcase( IsVirtual(pTab) );
  90882. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
  90883. &iDataCur, &iIdxCur);
  90884. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  90885. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  90886. }
  90887. /* Set up a loop over the rowids/primary-keys that were found in the
  90888. ** where-clause loop above.
  90889. */
  90890. if( okOnePass ){
  90891. /* Just one row. Hence the top-of-loop is a no-op */
  90892. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  90893. assert( !IsVirtual(pTab) );
  90894. if( aToOpen[iDataCur-iTabCur] ){
  90895. assert( pPk!=0 || pTab->pSelect!=0 );
  90896. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  90897. VdbeCoverage(v);
  90898. }
  90899. }else if( pPk ){
  90900. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  90901. sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
  90902. assert( nKey==0 ); /* OP_Found will use a composite key */
  90903. }else{
  90904. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  90905. VdbeCoverage(v);
  90906. assert( nKey==1 );
  90907. }
  90908. /* Delete the row */
  90909. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90910. if( IsVirtual(pTab) ){
  90911. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  90912. sqlite3VtabMakeWritable(pParse, pTab);
  90913. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  90914. sqlite3VdbeChangeP5(v, OE_Abort);
  90915. sqlite3MayAbort(pParse);
  90916. }else
  90917. #endif
  90918. {
  90919. int count = (pParse->nested==0); /* True to count changes */
  90920. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  90921. iKey, nKey, count, OE_Default, okOnePass);
  90922. }
  90923. /* End of the loop over all rowids/primary-keys. */
  90924. if( okOnePass ){
  90925. sqlite3VdbeResolveLabel(v, addrBypass);
  90926. }else if( pPk ){
  90927. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  90928. sqlite3VdbeJumpHere(v, addrLoop);
  90929. }else{
  90930. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
  90931. sqlite3VdbeJumpHere(v, addrLoop);
  90932. }
  90933. /* Close the cursors open on the table and its indexes. */
  90934. if( !isView && !IsVirtual(pTab) ){
  90935. if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  90936. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  90937. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
  90938. }
  90939. }
  90940. } /* End non-truncate path */
  90941. /* Update the sqlite_sequence table by storing the content of the
  90942. ** maximum rowid counter values recorded while inserting into
  90943. ** autoincrement tables.
  90944. */
  90945. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  90946. sqlite3AutoincrementEnd(pParse);
  90947. }
  90948. /* Return the number of rows that were deleted. If this routine is
  90949. ** generating code because of a call to sqlite3NestedParse(), do not
  90950. ** invoke the callback function.
  90951. */
  90952. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  90953. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  90954. sqlite3VdbeSetNumCols(v, 1);
  90955. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  90956. }
  90957. delete_from_cleanup:
  90958. sqlite3AuthContextPop(&sContext);
  90959. sqlite3SrcListDelete(db, pTabList);
  90960. sqlite3ExprDelete(db, pWhere);
  90961. sqlite3DbFree(db, aToOpen);
  90962. return;
  90963. }
  90964. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  90965. ** they may interfere with compilation of other functions in this file
  90966. ** (or in another file, if this file becomes part of the amalgamation). */
  90967. #ifdef isView
  90968. #undef isView
  90969. #endif
  90970. #ifdef pTrigger
  90971. #undef pTrigger
  90972. #endif
  90973. /*
  90974. ** This routine generates VDBE code that causes a single row of a
  90975. ** single table to be deleted. Both the original table entry and
  90976. ** all indices are removed.
  90977. **
  90978. ** Preconditions:
  90979. **
  90980. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  90981. ** store for the table. (This will be either the table itself,
  90982. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  90983. ** of a WITHOUT ROWID table.)
  90984. **
  90985. ** 2. Read/write cursors for all indices of pTab must be open as
  90986. ** cursor number iIdxCur+i for the i-th index.
  90987. **
  90988. ** 3. The primary key for the row to be deleted must be stored in a
  90989. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  90990. ** that a search record formed from OP_MakeRecord is contained in the
  90991. ** single memory location iPk.
  90992. */
  90993. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  90994. Parse *pParse, /* Parsing context */
  90995. Table *pTab, /* Table containing the row to be deleted */
  90996. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  90997. int iDataCur, /* Cursor from which column data is extracted */
  90998. int iIdxCur, /* First index cursor */
  90999. int iPk, /* First memory cell containing the PRIMARY KEY */
  91000. i16 nPk, /* Number of PRIMARY KEY memory cells */
  91001. u8 count, /* If non-zero, increment the row change counter */
  91002. u8 onconf, /* Default ON CONFLICT policy for triggers */
  91003. u8 bNoSeek /* iDataCur is already pointing to the row to delete */
  91004. ){
  91005. Vdbe *v = pParse->pVdbe; /* Vdbe */
  91006. int iOld = 0; /* First register in OLD.* array */
  91007. int iLabel; /* Label resolved to end of generated code */
  91008. u8 opSeek; /* Seek opcode */
  91009. /* Vdbe is guaranteed to have been allocated by this stage. */
  91010. assert( v );
  91011. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  91012. iDataCur, iIdxCur, iPk, (int)nPk));
  91013. /* Seek cursor iCur to the row to delete. If this row no longer exists
  91014. ** (this can happen if a trigger program has already deleted it), do
  91015. ** not attempt to delete it or fire any DELETE triggers. */
  91016. iLabel = sqlite3VdbeMakeLabel(v);
  91017. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  91018. if( !bNoSeek ){
  91019. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  91020. VdbeCoverageIf(v, opSeek==OP_NotExists);
  91021. VdbeCoverageIf(v, opSeek==OP_NotFound);
  91022. }
  91023. /* If there are any triggers to fire, allocate a range of registers to
  91024. ** use for the old.* references in the triggers. */
  91025. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  91026. u32 mask; /* Mask of OLD.* columns in use */
  91027. int iCol; /* Iterator used while populating OLD.* */
  91028. int addrStart; /* Start of BEFORE trigger programs */
  91029. /* TODO: Could use temporary registers here. Also could attempt to
  91030. ** avoid copying the contents of the rowid register. */
  91031. mask = sqlite3TriggerColmask(
  91032. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  91033. );
  91034. mask |= sqlite3FkOldmask(pParse, pTab);
  91035. iOld = pParse->nMem+1;
  91036. pParse->nMem += (1 + pTab->nCol);
  91037. /* Populate the OLD.* pseudo-table register array. These values will be
  91038. ** used by any BEFORE and AFTER triggers that exist. */
  91039. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  91040. for(iCol=0; iCol<pTab->nCol; iCol++){
  91041. testcase( mask!=0xffffffff && iCol==31 );
  91042. testcase( mask!=0xffffffff && iCol==32 );
  91043. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  91044. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  91045. }
  91046. }
  91047. /* Invoke BEFORE DELETE trigger programs. */
  91048. addrStart = sqlite3VdbeCurrentAddr(v);
  91049. sqlite3CodeRowTrigger(pParse, pTrigger,
  91050. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  91051. );
  91052. /* If any BEFORE triggers were coded, then seek the cursor to the
  91053. ** row to be deleted again. It may be that the BEFORE triggers moved
  91054. ** the cursor or of already deleted the row that the cursor was
  91055. ** pointing to.
  91056. */
  91057. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  91058. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  91059. VdbeCoverageIf(v, opSeek==OP_NotExists);
  91060. VdbeCoverageIf(v, opSeek==OP_NotFound);
  91061. }
  91062. /* Do FK processing. This call checks that any FK constraints that
  91063. ** refer to this table (i.e. constraints attached to other tables)
  91064. ** are not violated by deleting this row. */
  91065. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  91066. }
  91067. /* Delete the index and table entries. Skip this step if pTab is really
  91068. ** a view (in which case the only effect of the DELETE statement is to
  91069. ** fire the INSTEAD OF triggers). */
  91070. if( pTab->pSelect==0 ){
  91071. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  91072. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  91073. if( count ){
  91074. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  91075. }
  91076. }
  91077. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  91078. ** handle rows (possibly in other tables) that refer via a foreign key
  91079. ** to the row just deleted. */
  91080. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  91081. /* Invoke AFTER DELETE trigger programs. */
  91082. sqlite3CodeRowTrigger(pParse, pTrigger,
  91083. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  91084. );
  91085. /* Jump here if the row had already been deleted before any BEFORE
  91086. ** trigger programs were invoked. Or if a trigger program throws a
  91087. ** RAISE(IGNORE) exception. */
  91088. sqlite3VdbeResolveLabel(v, iLabel);
  91089. VdbeModuleComment((v, "END: GenRowDel()"));
  91090. }
  91091. /*
  91092. ** This routine generates VDBE code that causes the deletion of all
  91093. ** index entries associated with a single row of a single table, pTab
  91094. **
  91095. ** Preconditions:
  91096. **
  91097. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  91098. ** btree for the table pTab. (This will be either the table itself
  91099. ** for rowid tables or to the primary key index for WITHOUT ROWID
  91100. ** tables.)
  91101. **
  91102. ** 2. Read/write cursors for all indices of pTab must be open as
  91103. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  91104. ** index is the 0-th index.)
  91105. **
  91106. ** 3. The "iDataCur" cursor must be already be positioned on the row
  91107. ** that is to be deleted.
  91108. */
  91109. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  91110. Parse *pParse, /* Parsing and code generating context */
  91111. Table *pTab, /* Table containing the row to be deleted */
  91112. int iDataCur, /* Cursor of table holding data. */
  91113. int iIdxCur, /* First index cursor */
  91114. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  91115. ){
  91116. int i; /* Index loop counter */
  91117. int r1 = -1; /* Register holding an index key */
  91118. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  91119. Index *pIdx; /* Current index */
  91120. Index *pPrior = 0; /* Prior index */
  91121. Vdbe *v; /* The prepared statement under construction */
  91122. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  91123. v = pParse->pVdbe;
  91124. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  91125. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  91126. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  91127. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  91128. if( pIdx==pPk ) continue;
  91129. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  91130. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  91131. &iPartIdxLabel, pPrior, r1);
  91132. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  91133. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  91134. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  91135. pPrior = pIdx;
  91136. }
  91137. }
  91138. /*
  91139. ** Generate code that will assemble an index key and stores it in register
  91140. ** regOut. The key with be for index pIdx which is an index on pTab.
  91141. ** iCur is the index of a cursor open on the pTab table and pointing to
  91142. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  91143. ** iCur must be the cursor of the PRIMARY KEY index.
  91144. **
  91145. ** Return a register number which is the first in a block of
  91146. ** registers that holds the elements of the index key. The
  91147. ** block of registers has already been deallocated by the time
  91148. ** this routine returns.
  91149. **
  91150. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  91151. ** to that label if pIdx is a partial index that should be skipped.
  91152. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  91153. ** A partial index should be skipped if its WHERE clause evaluates
  91154. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  91155. ** will be set to zero which is an empty label that is ignored by
  91156. ** sqlite3ResolvePartIdxLabel().
  91157. **
  91158. ** The pPrior and regPrior parameters are used to implement a cache to
  91159. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  91160. ** a pointer to a different index for which an index key has just been
  91161. ** computed into register regPrior. If the current pIdx index is generating
  91162. ** its key into the same sequence of registers and if pPrior and pIdx share
  91163. ** a column in common, then the register corresponding to that column already
  91164. ** holds the correct value and the loading of that register is skipped.
  91165. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  91166. ** on a table with multiple indices, and especially with the ROWID or
  91167. ** PRIMARY KEY columns of the index.
  91168. */
  91169. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  91170. Parse *pParse, /* Parsing context */
  91171. Index *pIdx, /* The index for which to generate a key */
  91172. int iDataCur, /* Cursor number from which to take column data */
  91173. int regOut, /* Put the new key into this register if not 0 */
  91174. int prefixOnly, /* Compute only a unique prefix of the key */
  91175. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  91176. Index *pPrior, /* Previously generated index key */
  91177. int regPrior /* Register holding previous generated key */
  91178. ){
  91179. Vdbe *v = pParse->pVdbe;
  91180. int j;
  91181. Table *pTab = pIdx->pTable;
  91182. int regBase;
  91183. int nCol;
  91184. if( piPartIdxLabel ){
  91185. if( pIdx->pPartIdxWhere ){
  91186. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  91187. pParse->iPartIdxTab = iDataCur;
  91188. sqlite3ExprCachePush(pParse);
  91189. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  91190. SQLITE_JUMPIFNULL);
  91191. }else{
  91192. *piPartIdxLabel = 0;
  91193. }
  91194. }
  91195. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  91196. regBase = sqlite3GetTempRange(pParse, nCol);
  91197. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  91198. for(j=0; j<nCol; j++){
  91199. if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
  91200. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
  91201. regBase+j);
  91202. /* If the column affinity is REAL but the number is an integer, then it
  91203. ** might be stored in the table as an integer (using a compact
  91204. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  91205. ** But we are getting ready to store this value back into an index, where
  91206. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  91207. ** opcode if it is present */
  91208. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  91209. }
  91210. if( regOut ){
  91211. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  91212. }
  91213. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  91214. return regBase;
  91215. }
  91216. /*
  91217. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  91218. ** because it was a partial index, then this routine should be called to
  91219. ** resolve that label.
  91220. */
  91221. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  91222. if( iLabel ){
  91223. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  91224. sqlite3ExprCachePop(pParse);
  91225. }
  91226. }
  91227. /************** End of delete.c **********************************************/
  91228. /************** Begin file func.c ********************************************/
  91229. /*
  91230. ** 2002 February 23
  91231. **
  91232. ** The author disclaims copyright to this source code. In place of
  91233. ** a legal notice, here is a blessing:
  91234. **
  91235. ** May you do good and not evil.
  91236. ** May you find forgiveness for yourself and forgive others.
  91237. ** May you share freely, never taking more than you give.
  91238. **
  91239. *************************************************************************
  91240. ** This file contains the C-language implementations for many of the SQL
  91241. ** functions of SQLite. (Some function, and in particular the date and
  91242. ** time functions, are implemented separately.)
  91243. */
  91244. /* #include "sqliteInt.h" */
  91245. /* #include <stdlib.h> */
  91246. /* #include <assert.h> */
  91247. /* #include "vdbeInt.h" */
  91248. /*
  91249. ** Return the collating function associated with a function.
  91250. */
  91251. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  91252. VdbeOp *pOp;
  91253. assert( context->pVdbe!=0 );
  91254. pOp = &context->pVdbe->aOp[context->iOp-1];
  91255. assert( pOp->opcode==OP_CollSeq );
  91256. assert( pOp->p4type==P4_COLLSEQ );
  91257. return pOp->p4.pColl;
  91258. }
  91259. /*
  91260. ** Indicate that the accumulator load should be skipped on this
  91261. ** iteration of the aggregate loop.
  91262. */
  91263. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  91264. context->skipFlag = 1;
  91265. }
  91266. /*
  91267. ** Implementation of the non-aggregate min() and max() functions
  91268. */
  91269. static void minmaxFunc(
  91270. sqlite3_context *context,
  91271. int argc,
  91272. sqlite3_value **argv
  91273. ){
  91274. int i;
  91275. int mask; /* 0 for min() or 0xffffffff for max() */
  91276. int iBest;
  91277. CollSeq *pColl;
  91278. assert( argc>1 );
  91279. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  91280. pColl = sqlite3GetFuncCollSeq(context);
  91281. assert( pColl );
  91282. assert( mask==-1 || mask==0 );
  91283. iBest = 0;
  91284. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  91285. for(i=1; i<argc; i++){
  91286. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  91287. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  91288. testcase( mask==0 );
  91289. iBest = i;
  91290. }
  91291. }
  91292. sqlite3_result_value(context, argv[iBest]);
  91293. }
  91294. /*
  91295. ** Return the type of the argument.
  91296. */
  91297. static void typeofFunc(
  91298. sqlite3_context *context,
  91299. int NotUsed,
  91300. sqlite3_value **argv
  91301. ){
  91302. const char *z = 0;
  91303. UNUSED_PARAMETER(NotUsed);
  91304. switch( sqlite3_value_type(argv[0]) ){
  91305. case SQLITE_INTEGER: z = "integer"; break;
  91306. case SQLITE_TEXT: z = "text"; break;
  91307. case SQLITE_FLOAT: z = "real"; break;
  91308. case SQLITE_BLOB: z = "blob"; break;
  91309. default: z = "null"; break;
  91310. }
  91311. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  91312. }
  91313. /*
  91314. ** Implementation of the length() function
  91315. */
  91316. static void lengthFunc(
  91317. sqlite3_context *context,
  91318. int argc,
  91319. sqlite3_value **argv
  91320. ){
  91321. int len;
  91322. assert( argc==1 );
  91323. UNUSED_PARAMETER(argc);
  91324. switch( sqlite3_value_type(argv[0]) ){
  91325. case SQLITE_BLOB:
  91326. case SQLITE_INTEGER:
  91327. case SQLITE_FLOAT: {
  91328. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  91329. break;
  91330. }
  91331. case SQLITE_TEXT: {
  91332. const unsigned char *z = sqlite3_value_text(argv[0]);
  91333. if( z==0 ) return;
  91334. len = 0;
  91335. while( *z ){
  91336. len++;
  91337. SQLITE_SKIP_UTF8(z);
  91338. }
  91339. sqlite3_result_int(context, len);
  91340. break;
  91341. }
  91342. default: {
  91343. sqlite3_result_null(context);
  91344. break;
  91345. }
  91346. }
  91347. }
  91348. /*
  91349. ** Implementation of the abs() function.
  91350. **
  91351. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  91352. ** the numeric argument X.
  91353. */
  91354. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  91355. assert( argc==1 );
  91356. UNUSED_PARAMETER(argc);
  91357. switch( sqlite3_value_type(argv[0]) ){
  91358. case SQLITE_INTEGER: {
  91359. i64 iVal = sqlite3_value_int64(argv[0]);
  91360. if( iVal<0 ){
  91361. if( iVal==SMALLEST_INT64 ){
  91362. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  91363. ** then abs(X) throws an integer overflow error since there is no
  91364. ** equivalent positive 64-bit two complement value. */
  91365. sqlite3_result_error(context, "integer overflow", -1);
  91366. return;
  91367. }
  91368. iVal = -iVal;
  91369. }
  91370. sqlite3_result_int64(context, iVal);
  91371. break;
  91372. }
  91373. case SQLITE_NULL: {
  91374. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  91375. sqlite3_result_null(context);
  91376. break;
  91377. }
  91378. default: {
  91379. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  91380. ** something that can be converted into a number, we have:
  91381. ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
  91382. ** that cannot be converted to a numeric value.
  91383. */
  91384. double rVal = sqlite3_value_double(argv[0]);
  91385. if( rVal<0 ) rVal = -rVal;
  91386. sqlite3_result_double(context, rVal);
  91387. break;
  91388. }
  91389. }
  91390. }
  91391. /*
  91392. ** Implementation of the instr() function.
  91393. **
  91394. ** instr(haystack,needle) finds the first occurrence of needle
  91395. ** in haystack and returns the number of previous characters plus 1,
  91396. ** or 0 if needle does not occur within haystack.
  91397. **
  91398. ** If both haystack and needle are BLOBs, then the result is one more than
  91399. ** the number of bytes in haystack prior to the first occurrence of needle,
  91400. ** or 0 if needle never occurs in haystack.
  91401. */
  91402. static void instrFunc(
  91403. sqlite3_context *context,
  91404. int argc,
  91405. sqlite3_value **argv
  91406. ){
  91407. const unsigned char *zHaystack;
  91408. const unsigned char *zNeedle;
  91409. int nHaystack;
  91410. int nNeedle;
  91411. int typeHaystack, typeNeedle;
  91412. int N = 1;
  91413. int isText;
  91414. UNUSED_PARAMETER(argc);
  91415. typeHaystack = sqlite3_value_type(argv[0]);
  91416. typeNeedle = sqlite3_value_type(argv[1]);
  91417. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  91418. nHaystack = sqlite3_value_bytes(argv[0]);
  91419. nNeedle = sqlite3_value_bytes(argv[1]);
  91420. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  91421. zHaystack = sqlite3_value_blob(argv[0]);
  91422. zNeedle = sqlite3_value_blob(argv[1]);
  91423. isText = 0;
  91424. }else{
  91425. zHaystack = sqlite3_value_text(argv[0]);
  91426. zNeedle = sqlite3_value_text(argv[1]);
  91427. isText = 1;
  91428. }
  91429. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  91430. N++;
  91431. do{
  91432. nHaystack--;
  91433. zHaystack++;
  91434. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  91435. }
  91436. if( nNeedle>nHaystack ) N = 0;
  91437. sqlite3_result_int(context, N);
  91438. }
  91439. /*
  91440. ** Implementation of the printf() function.
  91441. */
  91442. static void printfFunc(
  91443. sqlite3_context *context,
  91444. int argc,
  91445. sqlite3_value **argv
  91446. ){
  91447. PrintfArguments x;
  91448. StrAccum str;
  91449. const char *zFormat;
  91450. int n;
  91451. sqlite3 *db = sqlite3_context_db_handle(context);
  91452. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  91453. x.nArg = argc-1;
  91454. x.nUsed = 0;
  91455. x.apArg = argv+1;
  91456. sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
  91457. sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
  91458. n = str.nChar;
  91459. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  91460. SQLITE_DYNAMIC);
  91461. }
  91462. }
  91463. /*
  91464. ** Implementation of the substr() function.
  91465. **
  91466. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  91467. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  91468. ** of x. If x is text, then we actually count UTF-8 characters.
  91469. ** If x is a blob, then we count bytes.
  91470. **
  91471. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  91472. **
  91473. ** If p2 is negative, return the p2 characters preceding p1.
  91474. */
  91475. static void substrFunc(
  91476. sqlite3_context *context,
  91477. int argc,
  91478. sqlite3_value **argv
  91479. ){
  91480. const unsigned char *z;
  91481. const unsigned char *z2;
  91482. int len;
  91483. int p0type;
  91484. i64 p1, p2;
  91485. int negP2 = 0;
  91486. assert( argc==3 || argc==2 );
  91487. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  91488. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  91489. ){
  91490. return;
  91491. }
  91492. p0type = sqlite3_value_type(argv[0]);
  91493. p1 = sqlite3_value_int(argv[1]);
  91494. if( p0type==SQLITE_BLOB ){
  91495. len = sqlite3_value_bytes(argv[0]);
  91496. z = sqlite3_value_blob(argv[0]);
  91497. if( z==0 ) return;
  91498. assert( len==sqlite3_value_bytes(argv[0]) );
  91499. }else{
  91500. z = sqlite3_value_text(argv[0]);
  91501. if( z==0 ) return;
  91502. len = 0;
  91503. if( p1<0 ){
  91504. for(z2=z; *z2; len++){
  91505. SQLITE_SKIP_UTF8(z2);
  91506. }
  91507. }
  91508. }
  91509. #ifdef SQLITE_SUBSTR_COMPATIBILITY
  91510. /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
  91511. ** as substr(X,1,N) - it returns the first N characters of X. This
  91512. ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
  91513. ** from 2009-02-02 for compatibility of applications that exploited the
  91514. ** old buggy behavior. */
  91515. if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
  91516. #endif
  91517. if( argc==3 ){
  91518. p2 = sqlite3_value_int(argv[2]);
  91519. if( p2<0 ){
  91520. p2 = -p2;
  91521. negP2 = 1;
  91522. }
  91523. }else{
  91524. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  91525. }
  91526. if( p1<0 ){
  91527. p1 += len;
  91528. if( p1<0 ){
  91529. p2 += p1;
  91530. if( p2<0 ) p2 = 0;
  91531. p1 = 0;
  91532. }
  91533. }else if( p1>0 ){
  91534. p1--;
  91535. }else if( p2>0 ){
  91536. p2--;
  91537. }
  91538. if( negP2 ){
  91539. p1 -= p2;
  91540. if( p1<0 ){
  91541. p2 += p1;
  91542. p1 = 0;
  91543. }
  91544. }
  91545. assert( p1>=0 && p2>=0 );
  91546. if( p0type!=SQLITE_BLOB ){
  91547. while( *z && p1 ){
  91548. SQLITE_SKIP_UTF8(z);
  91549. p1--;
  91550. }
  91551. for(z2=z; *z2 && p2; p2--){
  91552. SQLITE_SKIP_UTF8(z2);
  91553. }
  91554. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  91555. SQLITE_UTF8);
  91556. }else{
  91557. if( p1+p2>len ){
  91558. p2 = len-p1;
  91559. if( p2<0 ) p2 = 0;
  91560. }
  91561. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  91562. }
  91563. }
  91564. /*
  91565. ** Implementation of the round() function
  91566. */
  91567. #ifndef SQLITE_OMIT_FLOATING_POINT
  91568. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  91569. int n = 0;
  91570. double r;
  91571. char *zBuf;
  91572. assert( argc==1 || argc==2 );
  91573. if( argc==2 ){
  91574. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  91575. n = sqlite3_value_int(argv[1]);
  91576. if( n>30 ) n = 30;
  91577. if( n<0 ) n = 0;
  91578. }
  91579. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  91580. r = sqlite3_value_double(argv[0]);
  91581. /* If Y==0 and X will fit in a 64-bit int,
  91582. ** handle the rounding directly,
  91583. ** otherwise use printf.
  91584. */
  91585. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  91586. r = (double)((sqlite_int64)(r+0.5));
  91587. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  91588. r = -(double)((sqlite_int64)((-r)+0.5));
  91589. }else{
  91590. zBuf = sqlite3_mprintf("%.*f",n,r);
  91591. if( zBuf==0 ){
  91592. sqlite3_result_error_nomem(context);
  91593. return;
  91594. }
  91595. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  91596. sqlite3_free(zBuf);
  91597. }
  91598. sqlite3_result_double(context, r);
  91599. }
  91600. #endif
  91601. /*
  91602. ** Allocate nByte bytes of space using sqlite3Malloc(). If the
  91603. ** allocation fails, call sqlite3_result_error_nomem() to notify
  91604. ** the database handle that malloc() has failed and return NULL.
  91605. ** If nByte is larger than the maximum string or blob length, then
  91606. ** raise an SQLITE_TOOBIG exception and return NULL.
  91607. */
  91608. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  91609. char *z;
  91610. sqlite3 *db = sqlite3_context_db_handle(context);
  91611. assert( nByte>0 );
  91612. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  91613. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  91614. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  91615. sqlite3_result_error_toobig(context);
  91616. z = 0;
  91617. }else{
  91618. z = sqlite3Malloc(nByte);
  91619. if( !z ){
  91620. sqlite3_result_error_nomem(context);
  91621. }
  91622. }
  91623. return z;
  91624. }
  91625. /*
  91626. ** Implementation of the upper() and lower() SQL functions.
  91627. */
  91628. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  91629. char *z1;
  91630. const char *z2;
  91631. int i, n;
  91632. UNUSED_PARAMETER(argc);
  91633. z2 = (char*)sqlite3_value_text(argv[0]);
  91634. n = sqlite3_value_bytes(argv[0]);
  91635. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  91636. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  91637. if( z2 ){
  91638. z1 = contextMalloc(context, ((i64)n)+1);
  91639. if( z1 ){
  91640. for(i=0; i<n; i++){
  91641. z1[i] = (char)sqlite3Toupper(z2[i]);
  91642. }
  91643. sqlite3_result_text(context, z1, n, sqlite3_free);
  91644. }
  91645. }
  91646. }
  91647. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  91648. char *z1;
  91649. const char *z2;
  91650. int i, n;
  91651. UNUSED_PARAMETER(argc);
  91652. z2 = (char*)sqlite3_value_text(argv[0]);
  91653. n = sqlite3_value_bytes(argv[0]);
  91654. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  91655. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  91656. if( z2 ){
  91657. z1 = contextMalloc(context, ((i64)n)+1);
  91658. if( z1 ){
  91659. for(i=0; i<n; i++){
  91660. z1[i] = sqlite3Tolower(z2[i]);
  91661. }
  91662. sqlite3_result_text(context, z1, n, sqlite3_free);
  91663. }
  91664. }
  91665. }
  91666. /*
  91667. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  91668. ** as VDBE code so that unused argument values do not have to be computed.
  91669. ** However, we still need some kind of function implementation for this
  91670. ** routines in the function table. The noopFunc macro provides this.
  91671. ** noopFunc will never be called so it doesn't matter what the implementation
  91672. ** is. We might as well use the "version()" function as a substitute.
  91673. */
  91674. #define noopFunc versionFunc /* Substitute function - never called */
  91675. /*
  91676. ** Implementation of random(). Return a random integer.
  91677. */
  91678. static void randomFunc(
  91679. sqlite3_context *context,
  91680. int NotUsed,
  91681. sqlite3_value **NotUsed2
  91682. ){
  91683. sqlite_int64 r;
  91684. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  91685. sqlite3_randomness(sizeof(r), &r);
  91686. if( r<0 ){
  91687. /* We need to prevent a random number of 0x8000000000000000
  91688. ** (or -9223372036854775808) since when you do abs() of that
  91689. ** number of you get the same value back again. To do this
  91690. ** in a way that is testable, mask the sign bit off of negative
  91691. ** values, resulting in a positive value. Then take the
  91692. ** 2s complement of that positive value. The end result can
  91693. ** therefore be no less than -9223372036854775807.
  91694. */
  91695. r = -(r & LARGEST_INT64);
  91696. }
  91697. sqlite3_result_int64(context, r);
  91698. }
  91699. /*
  91700. ** Implementation of randomblob(N). Return a random blob
  91701. ** that is N bytes long.
  91702. */
  91703. static void randomBlob(
  91704. sqlite3_context *context,
  91705. int argc,
  91706. sqlite3_value **argv
  91707. ){
  91708. int n;
  91709. unsigned char *p;
  91710. assert( argc==1 );
  91711. UNUSED_PARAMETER(argc);
  91712. n = sqlite3_value_int(argv[0]);
  91713. if( n<1 ){
  91714. n = 1;
  91715. }
  91716. p = contextMalloc(context, n);
  91717. if( p ){
  91718. sqlite3_randomness(n, p);
  91719. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  91720. }
  91721. }
  91722. /*
  91723. ** Implementation of the last_insert_rowid() SQL function. The return
  91724. ** value is the same as the sqlite3_last_insert_rowid() API function.
  91725. */
  91726. static void last_insert_rowid(
  91727. sqlite3_context *context,
  91728. int NotUsed,
  91729. sqlite3_value **NotUsed2
  91730. ){
  91731. sqlite3 *db = sqlite3_context_db_handle(context);
  91732. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  91733. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  91734. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  91735. ** function. */
  91736. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  91737. }
  91738. /*
  91739. ** Implementation of the changes() SQL function.
  91740. **
  91741. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  91742. ** around the sqlite3_changes() C/C++ function and hence follows the same
  91743. ** rules for counting changes.
  91744. */
  91745. static void changes(
  91746. sqlite3_context *context,
  91747. int NotUsed,
  91748. sqlite3_value **NotUsed2
  91749. ){
  91750. sqlite3 *db = sqlite3_context_db_handle(context);
  91751. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  91752. sqlite3_result_int(context, sqlite3_changes(db));
  91753. }
  91754. /*
  91755. ** Implementation of the total_changes() SQL function. The return value is
  91756. ** the same as the sqlite3_total_changes() API function.
  91757. */
  91758. static void total_changes(
  91759. sqlite3_context *context,
  91760. int NotUsed,
  91761. sqlite3_value **NotUsed2
  91762. ){
  91763. sqlite3 *db = sqlite3_context_db_handle(context);
  91764. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  91765. /* IMP: R-52756-41993 This function is a wrapper around the
  91766. ** sqlite3_total_changes() C/C++ interface. */
  91767. sqlite3_result_int(context, sqlite3_total_changes(db));
  91768. }
  91769. /*
  91770. ** A structure defining how to do GLOB-style comparisons.
  91771. */
  91772. struct compareInfo {
  91773. u8 matchAll;
  91774. u8 matchOne;
  91775. u8 matchSet;
  91776. u8 noCase;
  91777. };
  91778. /*
  91779. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  91780. ** character is exactly one byte in size. Also, provde the Utf8Read()
  91781. ** macro for fast reading of the next character in the common case where
  91782. ** the next character is ASCII.
  91783. */
  91784. #if defined(SQLITE_EBCDIC)
  91785. # define sqlite3Utf8Read(A) (*((*A)++))
  91786. # define Utf8Read(A) (*(A++))
  91787. #else
  91788. # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
  91789. #endif
  91790. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  91791. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  91792. ** case. Thus 'a' LIKE 'A' would be true. */
  91793. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  91794. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  91795. ** is case sensitive causing 'a' LIKE 'A' to be false */
  91796. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  91797. /*
  91798. ** Compare two UTF-8 strings for equality where the first string can
  91799. ** potentially be a "glob" or "like" expression. Return true (1) if they
  91800. ** are the same and false (0) if they are different.
  91801. **
  91802. ** Globbing rules:
  91803. **
  91804. ** '*' Matches any sequence of zero or more characters.
  91805. **
  91806. ** '?' Matches exactly one character.
  91807. **
  91808. ** [...] Matches one character from the enclosed list of
  91809. ** characters.
  91810. **
  91811. ** [^...] Matches one character not in the enclosed list.
  91812. **
  91813. ** With the [...] and [^...] matching, a ']' character can be included
  91814. ** in the list by making it the first character after '[' or '^'. A
  91815. ** range of characters can be specified using '-'. Example:
  91816. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  91817. ** it the last character in the list.
  91818. **
  91819. ** Like matching rules:
  91820. **
  91821. ** '%' Matches any sequence of zero or more characters
  91822. **
  91823. *** '_' Matches any one character
  91824. **
  91825. ** Ec Where E is the "esc" character and c is any other
  91826. ** character, including '%', '_', and esc, match exactly c.
  91827. **
  91828. ** The comments within this routine usually assume glob matching.
  91829. **
  91830. ** This routine is usually quick, but can be N**2 in the worst case.
  91831. */
  91832. static int patternCompare(
  91833. const u8 *zPattern, /* The glob pattern */
  91834. const u8 *zString, /* The string to compare against the glob */
  91835. const struct compareInfo *pInfo, /* Information about how to do the compare */
  91836. u32 esc /* The escape character */
  91837. ){
  91838. u32 c, c2; /* Next pattern and input string chars */
  91839. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  91840. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  91841. u32 matchOther; /* "[" or the escape character */
  91842. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  91843. const u8 *zEscaped = 0; /* One past the last escaped input char */
  91844. /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
  91845. ** have the matchSet operator. So we either have to look for one or
  91846. ** the other, never both. Hence the single variable matchOther is used
  91847. ** to store the one we have to look for.
  91848. */
  91849. matchOther = esc ? esc : pInfo->matchSet;
  91850. while( (c = Utf8Read(zPattern))!=0 ){
  91851. if( c==matchAll ){ /* Match "*" */
  91852. /* Skip over multiple "*" characters in the pattern. If there
  91853. ** are also "?" characters, skip those as well, but consume a
  91854. ** single character of the input string for each "?" skipped */
  91855. while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
  91856. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  91857. return 0;
  91858. }
  91859. }
  91860. if( c==0 ){
  91861. return 1; /* "*" at the end of the pattern matches */
  91862. }else if( c==matchOther ){
  91863. if( esc ){
  91864. c = sqlite3Utf8Read(&zPattern);
  91865. if( c==0 ) return 0;
  91866. }else{
  91867. /* "[...]" immediately follows the "*". We have to do a slow
  91868. ** recursive search in this case, but it is an unusual case. */
  91869. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  91870. while( *zString
  91871. && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  91872. SQLITE_SKIP_UTF8(zString);
  91873. }
  91874. return *zString!=0;
  91875. }
  91876. }
  91877. /* At this point variable c contains the first character of the
  91878. ** pattern string past the "*". Search in the input string for the
  91879. ** first matching character and recursively contine the match from
  91880. ** that point.
  91881. **
  91882. ** For a case-insensitive search, set variable cx to be the same as
  91883. ** c but in the other case and search the input string for either
  91884. ** c or cx.
  91885. */
  91886. if( c<=0x80 ){
  91887. u32 cx;
  91888. if( noCase ){
  91889. cx = sqlite3Toupper(c);
  91890. c = sqlite3Tolower(c);
  91891. }else{
  91892. cx = c;
  91893. }
  91894. while( (c2 = *(zString++))!=0 ){
  91895. if( c2!=c && c2!=cx ) continue;
  91896. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  91897. }
  91898. }else{
  91899. while( (c2 = Utf8Read(zString))!=0 ){
  91900. if( c2!=c ) continue;
  91901. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  91902. }
  91903. }
  91904. return 0;
  91905. }
  91906. if( c==matchOther ){
  91907. if( esc ){
  91908. c = sqlite3Utf8Read(&zPattern);
  91909. if( c==0 ) return 0;
  91910. zEscaped = zPattern;
  91911. }else{
  91912. u32 prior_c = 0;
  91913. int seen = 0;
  91914. int invert = 0;
  91915. c = sqlite3Utf8Read(&zString);
  91916. if( c==0 ) return 0;
  91917. c2 = sqlite3Utf8Read(&zPattern);
  91918. if( c2=='^' ){
  91919. invert = 1;
  91920. c2 = sqlite3Utf8Read(&zPattern);
  91921. }
  91922. if( c2==']' ){
  91923. if( c==']' ) seen = 1;
  91924. c2 = sqlite3Utf8Read(&zPattern);
  91925. }
  91926. while( c2 && c2!=']' ){
  91927. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  91928. c2 = sqlite3Utf8Read(&zPattern);
  91929. if( c>=prior_c && c<=c2 ) seen = 1;
  91930. prior_c = 0;
  91931. }else{
  91932. if( c==c2 ){
  91933. seen = 1;
  91934. }
  91935. prior_c = c2;
  91936. }
  91937. c2 = sqlite3Utf8Read(&zPattern);
  91938. }
  91939. if( c2==0 || (seen ^ invert)==0 ){
  91940. return 0;
  91941. }
  91942. continue;
  91943. }
  91944. }
  91945. c2 = Utf8Read(zString);
  91946. if( c==c2 ) continue;
  91947. if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
  91948. continue;
  91949. }
  91950. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  91951. return 0;
  91952. }
  91953. return *zString==0;
  91954. }
  91955. /*
  91956. ** The sqlite3_strglob() interface.
  91957. */
  91958. SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
  91959. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  91960. }
  91961. /*
  91962. ** Count the number of times that the LIKE operator (or GLOB which is
  91963. ** just a variation of LIKE) gets called. This is used for testing
  91964. ** only.
  91965. */
  91966. #ifdef SQLITE_TEST
  91967. SQLITE_API int sqlite3_like_count = 0;
  91968. #endif
  91969. /*
  91970. ** Implementation of the like() SQL function. This function implements
  91971. ** the build-in LIKE operator. The first argument to the function is the
  91972. ** pattern and the second argument is the string. So, the SQL statements:
  91973. **
  91974. ** A LIKE B
  91975. **
  91976. ** is implemented as like(B,A).
  91977. **
  91978. ** This same function (with a different compareInfo structure) computes
  91979. ** the GLOB operator.
  91980. */
  91981. static void likeFunc(
  91982. sqlite3_context *context,
  91983. int argc,
  91984. sqlite3_value **argv
  91985. ){
  91986. const unsigned char *zA, *zB;
  91987. u32 escape = 0;
  91988. int nPat;
  91989. sqlite3 *db = sqlite3_context_db_handle(context);
  91990. zB = sqlite3_value_text(argv[0]);
  91991. zA = sqlite3_value_text(argv[1]);
  91992. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  91993. ** of deep recursion and N*N behavior in patternCompare().
  91994. */
  91995. nPat = sqlite3_value_bytes(argv[0]);
  91996. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  91997. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  91998. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  91999. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  92000. return;
  92001. }
  92002. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  92003. if( argc==3 ){
  92004. /* The escape character string must consist of a single UTF-8 character.
  92005. ** Otherwise, return an error.
  92006. */
  92007. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  92008. if( zEsc==0 ) return;
  92009. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  92010. sqlite3_result_error(context,
  92011. "ESCAPE expression must be a single character", -1);
  92012. return;
  92013. }
  92014. escape = sqlite3Utf8Read(&zEsc);
  92015. }
  92016. if( zA && zB ){
  92017. struct compareInfo *pInfo = sqlite3_user_data(context);
  92018. #ifdef SQLITE_TEST
  92019. sqlite3_like_count++;
  92020. #endif
  92021. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  92022. }
  92023. }
  92024. /*
  92025. ** Implementation of the NULLIF(x,y) function. The result is the first
  92026. ** argument if the arguments are different. The result is NULL if the
  92027. ** arguments are equal to each other.
  92028. */
  92029. static void nullifFunc(
  92030. sqlite3_context *context,
  92031. int NotUsed,
  92032. sqlite3_value **argv
  92033. ){
  92034. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  92035. UNUSED_PARAMETER(NotUsed);
  92036. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  92037. sqlite3_result_value(context, argv[0]);
  92038. }
  92039. }
  92040. /*
  92041. ** Implementation of the sqlite_version() function. The result is the version
  92042. ** of the SQLite library that is running.
  92043. */
  92044. static void versionFunc(
  92045. sqlite3_context *context,
  92046. int NotUsed,
  92047. sqlite3_value **NotUsed2
  92048. ){
  92049. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  92050. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  92051. ** sqlite3_libversion() C-interface. */
  92052. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  92053. }
  92054. /*
  92055. ** Implementation of the sqlite_source_id() function. The result is a string
  92056. ** that identifies the particular version of the source code used to build
  92057. ** SQLite.
  92058. */
  92059. static void sourceidFunc(
  92060. sqlite3_context *context,
  92061. int NotUsed,
  92062. sqlite3_value **NotUsed2
  92063. ){
  92064. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  92065. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  92066. ** sqlite3_sourceid() C interface. */
  92067. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  92068. }
  92069. /*
  92070. ** Implementation of the sqlite_log() function. This is a wrapper around
  92071. ** sqlite3_log(). The return value is NULL. The function exists purely for
  92072. ** its side-effects.
  92073. */
  92074. static void errlogFunc(
  92075. sqlite3_context *context,
  92076. int argc,
  92077. sqlite3_value **argv
  92078. ){
  92079. UNUSED_PARAMETER(argc);
  92080. UNUSED_PARAMETER(context);
  92081. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  92082. }
  92083. /*
  92084. ** Implementation of the sqlite_compileoption_used() function.
  92085. ** The result is an integer that identifies if the compiler option
  92086. ** was used to build SQLite.
  92087. */
  92088. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  92089. static void compileoptionusedFunc(
  92090. sqlite3_context *context,
  92091. int argc,
  92092. sqlite3_value **argv
  92093. ){
  92094. const char *zOptName;
  92095. assert( argc==1 );
  92096. UNUSED_PARAMETER(argc);
  92097. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  92098. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  92099. ** function.
  92100. */
  92101. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  92102. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  92103. }
  92104. }
  92105. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  92106. /*
  92107. ** Implementation of the sqlite_compileoption_get() function.
  92108. ** The result is a string that identifies the compiler options
  92109. ** used to build SQLite.
  92110. */
  92111. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  92112. static void compileoptiongetFunc(
  92113. sqlite3_context *context,
  92114. int argc,
  92115. sqlite3_value **argv
  92116. ){
  92117. int n;
  92118. assert( argc==1 );
  92119. UNUSED_PARAMETER(argc);
  92120. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  92121. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  92122. */
  92123. n = sqlite3_value_int(argv[0]);
  92124. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  92125. }
  92126. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  92127. /* Array for converting from half-bytes (nybbles) into ASCII hex
  92128. ** digits. */
  92129. static const char hexdigits[] = {
  92130. '0', '1', '2', '3', '4', '5', '6', '7',
  92131. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  92132. };
  92133. /*
  92134. ** Implementation of the QUOTE() function. This function takes a single
  92135. ** argument. If the argument is numeric, the return value is the same as
  92136. ** the argument. If the argument is NULL, the return value is the string
  92137. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  92138. ** single-quote escapes.
  92139. */
  92140. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  92141. assert( argc==1 );
  92142. UNUSED_PARAMETER(argc);
  92143. switch( sqlite3_value_type(argv[0]) ){
  92144. case SQLITE_FLOAT: {
  92145. double r1, r2;
  92146. char zBuf[50];
  92147. r1 = sqlite3_value_double(argv[0]);
  92148. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  92149. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  92150. if( r1!=r2 ){
  92151. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  92152. }
  92153. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  92154. break;
  92155. }
  92156. case SQLITE_INTEGER: {
  92157. sqlite3_result_value(context, argv[0]);
  92158. break;
  92159. }
  92160. case SQLITE_BLOB: {
  92161. char *zText = 0;
  92162. char const *zBlob = sqlite3_value_blob(argv[0]);
  92163. int nBlob = sqlite3_value_bytes(argv[0]);
  92164. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  92165. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  92166. if( zText ){
  92167. int i;
  92168. for(i=0; i<nBlob; i++){
  92169. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  92170. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  92171. }
  92172. zText[(nBlob*2)+2] = '\'';
  92173. zText[(nBlob*2)+3] = '\0';
  92174. zText[0] = 'X';
  92175. zText[1] = '\'';
  92176. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  92177. sqlite3_free(zText);
  92178. }
  92179. break;
  92180. }
  92181. case SQLITE_TEXT: {
  92182. int i,j;
  92183. u64 n;
  92184. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  92185. char *z;
  92186. if( zArg==0 ) return;
  92187. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  92188. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  92189. if( z ){
  92190. z[0] = '\'';
  92191. for(i=0, j=1; zArg[i]; i++){
  92192. z[j++] = zArg[i];
  92193. if( zArg[i]=='\'' ){
  92194. z[j++] = '\'';
  92195. }
  92196. }
  92197. z[j++] = '\'';
  92198. z[j] = 0;
  92199. sqlite3_result_text(context, z, j, sqlite3_free);
  92200. }
  92201. break;
  92202. }
  92203. default: {
  92204. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  92205. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  92206. break;
  92207. }
  92208. }
  92209. }
  92210. /*
  92211. ** The unicode() function. Return the integer unicode code-point value
  92212. ** for the first character of the input string.
  92213. */
  92214. static void unicodeFunc(
  92215. sqlite3_context *context,
  92216. int argc,
  92217. sqlite3_value **argv
  92218. ){
  92219. const unsigned char *z = sqlite3_value_text(argv[0]);
  92220. (void)argc;
  92221. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  92222. }
  92223. /*
  92224. ** The char() function takes zero or more arguments, each of which is
  92225. ** an integer. It constructs a string where each character of the string
  92226. ** is the unicode character for the corresponding integer argument.
  92227. */
  92228. static void charFunc(
  92229. sqlite3_context *context,
  92230. int argc,
  92231. sqlite3_value **argv
  92232. ){
  92233. unsigned char *z, *zOut;
  92234. int i;
  92235. zOut = z = sqlite3_malloc64( argc*4+1 );
  92236. if( z==0 ){
  92237. sqlite3_result_error_nomem(context);
  92238. return;
  92239. }
  92240. for(i=0; i<argc; i++){
  92241. sqlite3_int64 x;
  92242. unsigned c;
  92243. x = sqlite3_value_int64(argv[i]);
  92244. if( x<0 || x>0x10ffff ) x = 0xfffd;
  92245. c = (unsigned)(x & 0x1fffff);
  92246. if( c<0x00080 ){
  92247. *zOut++ = (u8)(c&0xFF);
  92248. }else if( c<0x00800 ){
  92249. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  92250. *zOut++ = 0x80 + (u8)(c & 0x3F);
  92251. }else if( c<0x10000 ){
  92252. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  92253. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  92254. *zOut++ = 0x80 + (u8)(c & 0x3F);
  92255. }else{
  92256. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  92257. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  92258. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  92259. *zOut++ = 0x80 + (u8)(c & 0x3F);
  92260. } \
  92261. }
  92262. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  92263. }
  92264. /*
  92265. ** The hex() function. Interpret the argument as a blob. Return
  92266. ** a hexadecimal rendering as text.
  92267. */
  92268. static void hexFunc(
  92269. sqlite3_context *context,
  92270. int argc,
  92271. sqlite3_value **argv
  92272. ){
  92273. int i, n;
  92274. const unsigned char *pBlob;
  92275. char *zHex, *z;
  92276. assert( argc==1 );
  92277. UNUSED_PARAMETER(argc);
  92278. pBlob = sqlite3_value_blob(argv[0]);
  92279. n = sqlite3_value_bytes(argv[0]);
  92280. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  92281. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  92282. if( zHex ){
  92283. for(i=0; i<n; i++, pBlob++){
  92284. unsigned char c = *pBlob;
  92285. *(z++) = hexdigits[(c>>4)&0xf];
  92286. *(z++) = hexdigits[c&0xf];
  92287. }
  92288. *z = 0;
  92289. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  92290. }
  92291. }
  92292. /*
  92293. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  92294. */
  92295. static void zeroblobFunc(
  92296. sqlite3_context *context,
  92297. int argc,
  92298. sqlite3_value **argv
  92299. ){
  92300. i64 n;
  92301. int rc;
  92302. assert( argc==1 );
  92303. UNUSED_PARAMETER(argc);
  92304. n = sqlite3_value_int64(argv[0]);
  92305. if( n<0 ) n = 0;
  92306. rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
  92307. if( rc ){
  92308. sqlite3_result_error_code(context, rc);
  92309. }
  92310. }
  92311. /*
  92312. ** The replace() function. Three arguments are all strings: call
  92313. ** them A, B, and C. The result is also a string which is derived
  92314. ** from A by replacing every occurrence of B with C. The match
  92315. ** must be exact. Collating sequences are not used.
  92316. */
  92317. static void replaceFunc(
  92318. sqlite3_context *context,
  92319. int argc,
  92320. sqlite3_value **argv
  92321. ){
  92322. const unsigned char *zStr; /* The input string A */
  92323. const unsigned char *zPattern; /* The pattern string B */
  92324. const unsigned char *zRep; /* The replacement string C */
  92325. unsigned char *zOut; /* The output */
  92326. int nStr; /* Size of zStr */
  92327. int nPattern; /* Size of zPattern */
  92328. int nRep; /* Size of zRep */
  92329. i64 nOut; /* Maximum size of zOut */
  92330. int loopLimit; /* Last zStr[] that might match zPattern[] */
  92331. int i, j; /* Loop counters */
  92332. assert( argc==3 );
  92333. UNUSED_PARAMETER(argc);
  92334. zStr = sqlite3_value_text(argv[0]);
  92335. if( zStr==0 ) return;
  92336. nStr = sqlite3_value_bytes(argv[0]);
  92337. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  92338. zPattern = sqlite3_value_text(argv[1]);
  92339. if( zPattern==0 ){
  92340. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  92341. || sqlite3_context_db_handle(context)->mallocFailed );
  92342. return;
  92343. }
  92344. if( zPattern[0]==0 ){
  92345. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  92346. sqlite3_result_value(context, argv[0]);
  92347. return;
  92348. }
  92349. nPattern = sqlite3_value_bytes(argv[1]);
  92350. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  92351. zRep = sqlite3_value_text(argv[2]);
  92352. if( zRep==0 ) return;
  92353. nRep = sqlite3_value_bytes(argv[2]);
  92354. assert( zRep==sqlite3_value_text(argv[2]) );
  92355. nOut = nStr + 1;
  92356. assert( nOut<SQLITE_MAX_LENGTH );
  92357. zOut = contextMalloc(context, (i64)nOut);
  92358. if( zOut==0 ){
  92359. return;
  92360. }
  92361. loopLimit = nStr - nPattern;
  92362. for(i=j=0; i<=loopLimit; i++){
  92363. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  92364. zOut[j++] = zStr[i];
  92365. }else{
  92366. u8 *zOld;
  92367. sqlite3 *db = sqlite3_context_db_handle(context);
  92368. nOut += nRep - nPattern;
  92369. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  92370. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  92371. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  92372. sqlite3_result_error_toobig(context);
  92373. sqlite3_free(zOut);
  92374. return;
  92375. }
  92376. zOld = zOut;
  92377. zOut = sqlite3_realloc64(zOut, (int)nOut);
  92378. if( zOut==0 ){
  92379. sqlite3_result_error_nomem(context);
  92380. sqlite3_free(zOld);
  92381. return;
  92382. }
  92383. memcpy(&zOut[j], zRep, nRep);
  92384. j += nRep;
  92385. i += nPattern-1;
  92386. }
  92387. }
  92388. assert( j+nStr-i+1==nOut );
  92389. memcpy(&zOut[j], &zStr[i], nStr-i);
  92390. j += nStr - i;
  92391. assert( j<=nOut );
  92392. zOut[j] = 0;
  92393. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  92394. }
  92395. /*
  92396. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  92397. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  92398. */
  92399. static void trimFunc(
  92400. sqlite3_context *context,
  92401. int argc,
  92402. sqlite3_value **argv
  92403. ){
  92404. const unsigned char *zIn; /* Input string */
  92405. const unsigned char *zCharSet; /* Set of characters to trim */
  92406. int nIn; /* Number of bytes in input */
  92407. int flags; /* 1: trimleft 2: trimright 3: trim */
  92408. int i; /* Loop counter */
  92409. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  92410. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  92411. int nChar; /* Number of characters in zCharSet */
  92412. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  92413. return;
  92414. }
  92415. zIn = sqlite3_value_text(argv[0]);
  92416. if( zIn==0 ) return;
  92417. nIn = sqlite3_value_bytes(argv[0]);
  92418. assert( zIn==sqlite3_value_text(argv[0]) );
  92419. if( argc==1 ){
  92420. static const unsigned char lenOne[] = { 1 };
  92421. static unsigned char * const azOne[] = { (u8*)" " };
  92422. nChar = 1;
  92423. aLen = (u8*)lenOne;
  92424. azChar = (unsigned char **)azOne;
  92425. zCharSet = 0;
  92426. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  92427. return;
  92428. }else{
  92429. const unsigned char *z;
  92430. for(z=zCharSet, nChar=0; *z; nChar++){
  92431. SQLITE_SKIP_UTF8(z);
  92432. }
  92433. if( nChar>0 ){
  92434. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  92435. if( azChar==0 ){
  92436. return;
  92437. }
  92438. aLen = (unsigned char*)&azChar[nChar];
  92439. for(z=zCharSet, nChar=0; *z; nChar++){
  92440. azChar[nChar] = (unsigned char *)z;
  92441. SQLITE_SKIP_UTF8(z);
  92442. aLen[nChar] = (u8)(z - azChar[nChar]);
  92443. }
  92444. }
  92445. }
  92446. if( nChar>0 ){
  92447. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  92448. if( flags & 1 ){
  92449. while( nIn>0 ){
  92450. int len = 0;
  92451. for(i=0; i<nChar; i++){
  92452. len = aLen[i];
  92453. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  92454. }
  92455. if( i>=nChar ) break;
  92456. zIn += len;
  92457. nIn -= len;
  92458. }
  92459. }
  92460. if( flags & 2 ){
  92461. while( nIn>0 ){
  92462. int len = 0;
  92463. for(i=0; i<nChar; i++){
  92464. len = aLen[i];
  92465. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  92466. }
  92467. if( i>=nChar ) break;
  92468. nIn -= len;
  92469. }
  92470. }
  92471. if( zCharSet ){
  92472. sqlite3_free(azChar);
  92473. }
  92474. }
  92475. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  92476. }
  92477. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  92478. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  92479. ** when SQLite is built.
  92480. */
  92481. #ifdef SQLITE_SOUNDEX
  92482. /*
  92483. ** Compute the soundex encoding of a word.
  92484. **
  92485. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  92486. ** soundex encoding of the string X.
  92487. */
  92488. static void soundexFunc(
  92489. sqlite3_context *context,
  92490. int argc,
  92491. sqlite3_value **argv
  92492. ){
  92493. char zResult[8];
  92494. const u8 *zIn;
  92495. int i, j;
  92496. static const unsigned char iCode[] = {
  92497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  92501. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  92502. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  92503. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  92504. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  92505. };
  92506. assert( argc==1 );
  92507. zIn = (u8*)sqlite3_value_text(argv[0]);
  92508. if( zIn==0 ) zIn = (u8*)"";
  92509. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  92510. if( zIn[i] ){
  92511. u8 prevcode = iCode[zIn[i]&0x7f];
  92512. zResult[0] = sqlite3Toupper(zIn[i]);
  92513. for(j=1; j<4 && zIn[i]; i++){
  92514. int code = iCode[zIn[i]&0x7f];
  92515. if( code>0 ){
  92516. if( code!=prevcode ){
  92517. prevcode = code;
  92518. zResult[j++] = code + '0';
  92519. }
  92520. }else{
  92521. prevcode = 0;
  92522. }
  92523. }
  92524. while( j<4 ){
  92525. zResult[j++] = '0';
  92526. }
  92527. zResult[j] = 0;
  92528. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  92529. }else{
  92530. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  92531. ** is NULL or contains no ASCII alphabetic characters. */
  92532. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  92533. }
  92534. }
  92535. #endif /* SQLITE_SOUNDEX */
  92536. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  92537. /*
  92538. ** A function that loads a shared-library extension then returns NULL.
  92539. */
  92540. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  92541. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  92542. const char *zProc;
  92543. sqlite3 *db = sqlite3_context_db_handle(context);
  92544. char *zErrMsg = 0;
  92545. if( argc==2 ){
  92546. zProc = (const char *)sqlite3_value_text(argv[1]);
  92547. }else{
  92548. zProc = 0;
  92549. }
  92550. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  92551. sqlite3_result_error(context, zErrMsg, -1);
  92552. sqlite3_free(zErrMsg);
  92553. }
  92554. }
  92555. #endif
  92556. /*
  92557. ** An instance of the following structure holds the context of a
  92558. ** sum() or avg() aggregate computation.
  92559. */
  92560. typedef struct SumCtx SumCtx;
  92561. struct SumCtx {
  92562. double rSum; /* Floating point sum */
  92563. i64 iSum; /* Integer sum */
  92564. i64 cnt; /* Number of elements summed */
  92565. u8 overflow; /* True if integer overflow seen */
  92566. u8 approx; /* True if non-integer value was input to the sum */
  92567. };
  92568. /*
  92569. ** Routines used to compute the sum, average, and total.
  92570. **
  92571. ** The SUM() function follows the (broken) SQL standard which means
  92572. ** that it returns NULL if it sums over no inputs. TOTAL returns
  92573. ** 0.0 in that case. In addition, TOTAL always returns a float where
  92574. ** SUM might return an integer if it never encounters a floating point
  92575. ** value. TOTAL never fails, but SUM might through an exception if
  92576. ** it overflows an integer.
  92577. */
  92578. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  92579. SumCtx *p;
  92580. int type;
  92581. assert( argc==1 );
  92582. UNUSED_PARAMETER(argc);
  92583. p = sqlite3_aggregate_context(context, sizeof(*p));
  92584. type = sqlite3_value_numeric_type(argv[0]);
  92585. if( p && type!=SQLITE_NULL ){
  92586. p->cnt++;
  92587. if( type==SQLITE_INTEGER ){
  92588. i64 v = sqlite3_value_int64(argv[0]);
  92589. p->rSum += v;
  92590. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  92591. p->overflow = 1;
  92592. }
  92593. }else{
  92594. p->rSum += sqlite3_value_double(argv[0]);
  92595. p->approx = 1;
  92596. }
  92597. }
  92598. }
  92599. static void sumFinalize(sqlite3_context *context){
  92600. SumCtx *p;
  92601. p = sqlite3_aggregate_context(context, 0);
  92602. if( p && p->cnt>0 ){
  92603. if( p->overflow ){
  92604. sqlite3_result_error(context,"integer overflow",-1);
  92605. }else if( p->approx ){
  92606. sqlite3_result_double(context, p->rSum);
  92607. }else{
  92608. sqlite3_result_int64(context, p->iSum);
  92609. }
  92610. }
  92611. }
  92612. static void avgFinalize(sqlite3_context *context){
  92613. SumCtx *p;
  92614. p = sqlite3_aggregate_context(context, 0);
  92615. if( p && p->cnt>0 ){
  92616. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  92617. }
  92618. }
  92619. static void totalFinalize(sqlite3_context *context){
  92620. SumCtx *p;
  92621. p = sqlite3_aggregate_context(context, 0);
  92622. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  92623. sqlite3_result_double(context, p ? p->rSum : (double)0);
  92624. }
  92625. /*
  92626. ** The following structure keeps track of state information for the
  92627. ** count() aggregate function.
  92628. */
  92629. typedef struct CountCtx CountCtx;
  92630. struct CountCtx {
  92631. i64 n;
  92632. };
  92633. /*
  92634. ** Routines to implement the count() aggregate function.
  92635. */
  92636. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  92637. CountCtx *p;
  92638. p = sqlite3_aggregate_context(context, sizeof(*p));
  92639. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  92640. p->n++;
  92641. }
  92642. #ifndef SQLITE_OMIT_DEPRECATED
  92643. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  92644. ** sure it still operates correctly, verify that its count agrees with our
  92645. ** internal count when using count(*) and when the total count can be
  92646. ** expressed as a 32-bit integer. */
  92647. assert( argc==1 || p==0 || p->n>0x7fffffff
  92648. || p->n==sqlite3_aggregate_count(context) );
  92649. #endif
  92650. }
  92651. static void countFinalize(sqlite3_context *context){
  92652. CountCtx *p;
  92653. p = sqlite3_aggregate_context(context, 0);
  92654. sqlite3_result_int64(context, p ? p->n : 0);
  92655. }
  92656. /*
  92657. ** Routines to implement min() and max() aggregate functions.
  92658. */
  92659. static void minmaxStep(
  92660. sqlite3_context *context,
  92661. int NotUsed,
  92662. sqlite3_value **argv
  92663. ){
  92664. Mem *pArg = (Mem *)argv[0];
  92665. Mem *pBest;
  92666. UNUSED_PARAMETER(NotUsed);
  92667. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  92668. if( !pBest ) return;
  92669. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  92670. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  92671. }else if( pBest->flags ){
  92672. int max;
  92673. int cmp;
  92674. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  92675. /* This step function is used for both the min() and max() aggregates,
  92676. ** the only difference between the two being that the sense of the
  92677. ** comparison is inverted. For the max() aggregate, the
  92678. ** sqlite3_user_data() function returns (void *)-1. For min() it
  92679. ** returns (void *)db, where db is the sqlite3* database pointer.
  92680. ** Therefore the next statement sets variable 'max' to 1 for the max()
  92681. ** aggregate, or 0 for min().
  92682. */
  92683. max = sqlite3_user_data(context)!=0;
  92684. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  92685. if( (max && cmp<0) || (!max && cmp>0) ){
  92686. sqlite3VdbeMemCopy(pBest, pArg);
  92687. }else{
  92688. sqlite3SkipAccumulatorLoad(context);
  92689. }
  92690. }else{
  92691. pBest->db = sqlite3_context_db_handle(context);
  92692. sqlite3VdbeMemCopy(pBest, pArg);
  92693. }
  92694. }
  92695. static void minMaxFinalize(sqlite3_context *context){
  92696. sqlite3_value *pRes;
  92697. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  92698. if( pRes ){
  92699. if( pRes->flags ){
  92700. sqlite3_result_value(context, pRes);
  92701. }
  92702. sqlite3VdbeMemRelease(pRes);
  92703. }
  92704. }
  92705. /*
  92706. ** group_concat(EXPR, ?SEPARATOR?)
  92707. */
  92708. static void groupConcatStep(
  92709. sqlite3_context *context,
  92710. int argc,
  92711. sqlite3_value **argv
  92712. ){
  92713. const char *zVal;
  92714. StrAccum *pAccum;
  92715. const char *zSep;
  92716. int nVal, nSep;
  92717. assert( argc==1 || argc==2 );
  92718. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  92719. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  92720. if( pAccum ){
  92721. sqlite3 *db = sqlite3_context_db_handle(context);
  92722. int firstTerm = pAccum->mxAlloc==0;
  92723. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  92724. if( !firstTerm ){
  92725. if( argc==2 ){
  92726. zSep = (char*)sqlite3_value_text(argv[1]);
  92727. nSep = sqlite3_value_bytes(argv[1]);
  92728. }else{
  92729. zSep = ",";
  92730. nSep = 1;
  92731. }
  92732. if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  92733. }
  92734. zVal = (char*)sqlite3_value_text(argv[0]);
  92735. nVal = sqlite3_value_bytes(argv[0]);
  92736. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  92737. }
  92738. }
  92739. static void groupConcatFinalize(sqlite3_context *context){
  92740. StrAccum *pAccum;
  92741. pAccum = sqlite3_aggregate_context(context, 0);
  92742. if( pAccum ){
  92743. if( pAccum->accError==STRACCUM_TOOBIG ){
  92744. sqlite3_result_error_toobig(context);
  92745. }else if( pAccum->accError==STRACCUM_NOMEM ){
  92746. sqlite3_result_error_nomem(context);
  92747. }else{
  92748. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  92749. sqlite3_free);
  92750. }
  92751. }
  92752. }
  92753. /*
  92754. ** This routine does per-connection function registration. Most
  92755. ** of the built-in functions above are part of the global function set.
  92756. ** This routine only deals with those that are not global.
  92757. */
  92758. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  92759. int rc = sqlite3_overload_function(db, "MATCH", 2);
  92760. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  92761. if( rc==SQLITE_NOMEM ){
  92762. db->mallocFailed = 1;
  92763. }
  92764. }
  92765. /*
  92766. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  92767. */
  92768. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  92769. FuncDef *pDef;
  92770. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  92771. 2, SQLITE_UTF8, 0);
  92772. if( ALWAYS(pDef) ){
  92773. pDef->funcFlags |= flagVal;
  92774. }
  92775. }
  92776. /*
  92777. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  92778. ** parameter determines whether or not the LIKE operator is case
  92779. ** sensitive. GLOB is always case sensitive.
  92780. */
  92781. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  92782. struct compareInfo *pInfo;
  92783. if( caseSensitive ){
  92784. pInfo = (struct compareInfo*)&likeInfoAlt;
  92785. }else{
  92786. pInfo = (struct compareInfo*)&likeInfoNorm;
  92787. }
  92788. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  92789. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  92790. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  92791. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  92792. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  92793. setLikeOptFlag(db, "like",
  92794. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  92795. }
  92796. /*
  92797. ** pExpr points to an expression which implements a function. If
  92798. ** it is appropriate to apply the LIKE optimization to that function
  92799. ** then set aWc[0] through aWc[2] to the wildcard characters and
  92800. ** return TRUE. If the function is not a LIKE-style function then
  92801. ** return FALSE.
  92802. **
  92803. ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
  92804. ** the function (default for LIKE). If the function makes the distinction
  92805. ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
  92806. ** false.
  92807. */
  92808. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  92809. FuncDef *pDef;
  92810. if( pExpr->op!=TK_FUNCTION
  92811. || !pExpr->x.pList
  92812. || pExpr->x.pList->nExpr!=2
  92813. ){
  92814. return 0;
  92815. }
  92816. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  92817. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  92818. sqlite3Strlen30(pExpr->u.zToken),
  92819. 2, SQLITE_UTF8, 0);
  92820. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  92821. return 0;
  92822. }
  92823. /* The memcpy() statement assumes that the wildcard characters are
  92824. ** the first three statements in the compareInfo structure. The
  92825. ** asserts() that follow verify that assumption
  92826. */
  92827. memcpy(aWc, pDef->pUserData, 3);
  92828. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  92829. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  92830. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  92831. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  92832. return 1;
  92833. }
  92834. /*
  92835. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  92836. ** to the global function hash table. This occurs at start-time (as
  92837. ** a consequence of calling sqlite3_initialize()).
  92838. **
  92839. ** After this routine runs
  92840. */
  92841. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  92842. /*
  92843. ** The following array holds FuncDef structures for all of the functions
  92844. ** defined in this file.
  92845. **
  92846. ** The array cannot be constant since changes are made to the
  92847. ** FuncDef.pHash elements at start-time. The elements of this array
  92848. ** are read-only after initialization is complete.
  92849. */
  92850. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  92851. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  92852. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  92853. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  92854. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  92855. FUNCTION(trim, 1, 3, 0, trimFunc ),
  92856. FUNCTION(trim, 2, 3, 0, trimFunc ),
  92857. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  92858. FUNCTION(min, 0, 0, 1, 0 ),
  92859. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  92860. SQLITE_FUNC_MINMAX ),
  92861. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  92862. FUNCTION(max, 0, 1, 1, 0 ),
  92863. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  92864. SQLITE_FUNC_MINMAX ),
  92865. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  92866. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  92867. FUNCTION(instr, 2, 0, 0, instrFunc ),
  92868. FUNCTION(substr, 2, 0, 0, substrFunc ),
  92869. FUNCTION(substr, 3, 0, 0, substrFunc ),
  92870. FUNCTION(printf, -1, 0, 0, printfFunc ),
  92871. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  92872. FUNCTION(char, -1, 0, 0, charFunc ),
  92873. FUNCTION(abs, 1, 0, 0, absFunc ),
  92874. #ifndef SQLITE_OMIT_FLOATING_POINT
  92875. FUNCTION(round, 1, 0, 0, roundFunc ),
  92876. FUNCTION(round, 2, 0, 0, roundFunc ),
  92877. #endif
  92878. FUNCTION(upper, 1, 0, 0, upperFunc ),
  92879. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  92880. FUNCTION(coalesce, 1, 0, 0, 0 ),
  92881. FUNCTION(coalesce, 0, 0, 0, 0 ),
  92882. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  92883. FUNCTION(hex, 1, 0, 0, hexFunc ),
  92884. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  92885. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  92886. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  92887. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  92888. VFUNCTION(random, 0, 0, 0, randomFunc ),
  92889. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  92890. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  92891. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  92892. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  92893. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  92894. #if SQLITE_USER_AUTHENTICATION
  92895. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  92896. #endif
  92897. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  92898. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  92899. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  92900. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  92901. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  92902. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  92903. VFUNCTION(changes, 0, 0, 0, changes ),
  92904. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  92905. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  92906. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  92907. #ifdef SQLITE_SOUNDEX
  92908. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  92909. #endif
  92910. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  92911. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  92912. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  92913. #endif
  92914. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  92915. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  92916. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  92917. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  92918. SQLITE_FUNC_COUNT ),
  92919. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  92920. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  92921. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  92922. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  92923. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  92924. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  92925. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  92926. #else
  92927. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  92928. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  92929. #endif
  92930. };
  92931. int i;
  92932. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  92933. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  92934. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  92935. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  92936. }
  92937. sqlite3RegisterDateTimeFunctions();
  92938. #ifndef SQLITE_OMIT_ALTERTABLE
  92939. sqlite3AlterFunctions();
  92940. #endif
  92941. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  92942. sqlite3AnalyzeFunctions();
  92943. #endif
  92944. }
  92945. /************** End of func.c ************************************************/
  92946. /************** Begin file fkey.c ********************************************/
  92947. /*
  92948. **
  92949. ** The author disclaims copyright to this source code. In place of
  92950. ** a legal notice, here is a blessing:
  92951. **
  92952. ** May you do good and not evil.
  92953. ** May you find forgiveness for yourself and forgive others.
  92954. ** May you share freely, never taking more than you give.
  92955. **
  92956. *************************************************************************
  92957. ** This file contains code used by the compiler to add foreign key
  92958. ** support to compiled SQL statements.
  92959. */
  92960. /* #include "sqliteInt.h" */
  92961. #ifndef SQLITE_OMIT_FOREIGN_KEY
  92962. #ifndef SQLITE_OMIT_TRIGGER
  92963. /*
  92964. ** Deferred and Immediate FKs
  92965. ** --------------------------
  92966. **
  92967. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  92968. ** If an immediate foreign key constraint is violated,
  92969. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  92970. ** statement transaction rolled back. If a
  92971. ** deferred foreign key constraint is violated, no action is taken
  92972. ** immediately. However if the application attempts to commit the
  92973. ** transaction before fixing the constraint violation, the attempt fails.
  92974. **
  92975. ** Deferred constraints are implemented using a simple counter associated
  92976. ** with the database handle. The counter is set to zero each time a
  92977. ** database transaction is opened. Each time a statement is executed
  92978. ** that causes a foreign key violation, the counter is incremented. Each
  92979. ** time a statement is executed that removes an existing violation from
  92980. ** the database, the counter is decremented. When the transaction is
  92981. ** committed, the commit fails if the current value of the counter is
  92982. ** greater than zero. This scheme has two big drawbacks:
  92983. **
  92984. ** * When a commit fails due to a deferred foreign key constraint,
  92985. ** there is no way to tell which foreign constraint is not satisfied,
  92986. ** or which row it is not satisfied for.
  92987. **
  92988. ** * If the database contains foreign key violations when the
  92989. ** transaction is opened, this may cause the mechanism to malfunction.
  92990. **
  92991. ** Despite these problems, this approach is adopted as it seems simpler
  92992. ** than the alternatives.
  92993. **
  92994. ** INSERT operations:
  92995. **
  92996. ** I.1) For each FK for which the table is the child table, search
  92997. ** the parent table for a match. If none is found increment the
  92998. ** constraint counter.
  92999. **
  93000. ** I.2) For each FK for which the table is the parent table,
  93001. ** search the child table for rows that correspond to the new
  93002. ** row in the parent table. Decrement the counter for each row
  93003. ** found (as the constraint is now satisfied).
  93004. **
  93005. ** DELETE operations:
  93006. **
  93007. ** D.1) For each FK for which the table is the child table,
  93008. ** search the parent table for a row that corresponds to the
  93009. ** deleted row in the child table. If such a row is not found,
  93010. ** decrement the counter.
  93011. **
  93012. ** D.2) For each FK for which the table is the parent table, search
  93013. ** the child table for rows that correspond to the deleted row
  93014. ** in the parent table. For each found increment the counter.
  93015. **
  93016. ** UPDATE operations:
  93017. **
  93018. ** An UPDATE command requires that all 4 steps above are taken, but only
  93019. ** for FK constraints for which the affected columns are actually
  93020. ** modified (values must be compared at runtime).
  93021. **
  93022. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  93023. ** This simplifies the implementation a bit.
  93024. **
  93025. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  93026. ** resolution is considered to delete rows before the new row is inserted.
  93027. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  93028. ** is thrown, even if the FK constraint would be satisfied after the new
  93029. ** row is inserted.
  93030. **
  93031. ** Immediate constraints are usually handled similarly. The only difference
  93032. ** is that the counter used is stored as part of each individual statement
  93033. ** object (struct Vdbe). If, after the statement has run, its immediate
  93034. ** constraint counter is greater than zero,
  93035. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  93036. ** and the statement transaction is rolled back. An exception is an INSERT
  93037. ** statement that inserts a single row only (no triggers). In this case,
  93038. ** instead of using a counter, an exception is thrown immediately if the
  93039. ** INSERT violates a foreign key constraint. This is necessary as such
  93040. ** an INSERT does not open a statement transaction.
  93041. **
  93042. ** TODO: How should dropping a table be handled? How should renaming a
  93043. ** table be handled?
  93044. **
  93045. **
  93046. ** Query API Notes
  93047. ** ---------------
  93048. **
  93049. ** Before coding an UPDATE or DELETE row operation, the code-generator
  93050. ** for those two operations needs to know whether or not the operation
  93051. ** requires any FK processing and, if so, which columns of the original
  93052. ** row are required by the FK processing VDBE code (i.e. if FKs were
  93053. ** implemented using triggers, which of the old.* columns would be
  93054. ** accessed). No information is required by the code-generator before
  93055. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  93056. ** generation code to query for this information are:
  93057. **
  93058. ** sqlite3FkRequired() - Test to see if FK processing is required.
  93059. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  93060. **
  93061. **
  93062. ** Externally accessible module functions
  93063. ** --------------------------------------
  93064. **
  93065. ** sqlite3FkCheck() - Check for foreign key violations.
  93066. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  93067. ** sqlite3FkDelete() - Delete an FKey structure.
  93068. */
  93069. /*
  93070. ** VDBE Calling Convention
  93071. ** -----------------------
  93072. **
  93073. ** Example:
  93074. **
  93075. ** For the following INSERT statement:
  93076. **
  93077. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  93078. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  93079. **
  93080. ** Register (x): 2 (type integer)
  93081. ** Register (x+1): 1 (type integer)
  93082. ** Register (x+2): NULL (type NULL)
  93083. ** Register (x+3): 3.1 (type real)
  93084. */
  93085. /*
  93086. ** A foreign key constraint requires that the key columns in the parent
  93087. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  93088. ** Given that pParent is the parent table for foreign key constraint pFKey,
  93089. ** search the schema for a unique index on the parent key columns.
  93090. **
  93091. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  93092. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  93093. ** is set to point to the unique index.
  93094. **
  93095. ** If the parent key consists of a single column (the foreign key constraint
  93096. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  93097. ** Otherwise, it is set to point to an allocated array of size N, where
  93098. ** N is the number of columns in the parent key. The first element of the
  93099. ** array is the index of the child table column that is mapped by the FK
  93100. ** constraint to the parent table column stored in the left-most column
  93101. ** of index *ppIdx. The second element of the array is the index of the
  93102. ** child table column that corresponds to the second left-most column of
  93103. ** *ppIdx, and so on.
  93104. **
  93105. ** If the required index cannot be found, either because:
  93106. **
  93107. ** 1) The named parent key columns do not exist, or
  93108. **
  93109. ** 2) The named parent key columns do exist, but are not subject to a
  93110. ** UNIQUE or PRIMARY KEY constraint, or
  93111. **
  93112. ** 3) No parent key columns were provided explicitly as part of the
  93113. ** foreign key definition, and the parent table does not have a
  93114. ** PRIMARY KEY, or
  93115. **
  93116. ** 4) No parent key columns were provided explicitly as part of the
  93117. ** foreign key definition, and the PRIMARY KEY of the parent table
  93118. ** consists of a different number of columns to the child key in
  93119. ** the child table.
  93120. **
  93121. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  93122. ** into pParse. If an OOM error occurs, non-zero is returned and the
  93123. ** pParse->db->mallocFailed flag is set.
  93124. */
  93125. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  93126. Parse *pParse, /* Parse context to store any error in */
  93127. Table *pParent, /* Parent table of FK constraint pFKey */
  93128. FKey *pFKey, /* Foreign key to find index for */
  93129. Index **ppIdx, /* OUT: Unique index on parent table */
  93130. int **paiCol /* OUT: Map of index columns in pFKey */
  93131. ){
  93132. Index *pIdx = 0; /* Value to return via *ppIdx */
  93133. int *aiCol = 0; /* Value to return via *paiCol */
  93134. int nCol = pFKey->nCol; /* Number of columns in parent key */
  93135. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  93136. /* The caller is responsible for zeroing output parameters. */
  93137. assert( ppIdx && *ppIdx==0 );
  93138. assert( !paiCol || *paiCol==0 );
  93139. assert( pParse );
  93140. /* If this is a non-composite (single column) foreign key, check if it
  93141. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  93142. ** and *paiCol set to zero and return early.
  93143. **
  93144. ** Otherwise, for a composite foreign key (more than one column), allocate
  93145. ** space for the aiCol array (returned via output parameter *paiCol).
  93146. ** Non-composite foreign keys do not require the aiCol array.
  93147. */
  93148. if( nCol==1 ){
  93149. /* The FK maps to the IPK if any of the following are true:
  93150. **
  93151. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  93152. ** mapped to the primary key of table pParent, or
  93153. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  93154. ** PRIMARY KEY.
  93155. */
  93156. if( pParent->iPKey>=0 ){
  93157. if( !zKey ) return 0;
  93158. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  93159. }
  93160. }else if( paiCol ){
  93161. assert( nCol>1 );
  93162. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  93163. if( !aiCol ) return 1;
  93164. *paiCol = aiCol;
  93165. }
  93166. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  93167. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
  93168. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  93169. ** of columns. If each indexed column corresponds to a foreign key
  93170. ** column of pFKey, then this index is a winner. */
  93171. if( zKey==0 ){
  93172. /* If zKey is NULL, then this foreign key is implicitly mapped to
  93173. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  93174. ** identified by the test. */
  93175. if( IsPrimaryKeyIndex(pIdx) ){
  93176. if( aiCol ){
  93177. int i;
  93178. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  93179. }
  93180. break;
  93181. }
  93182. }else{
  93183. /* If zKey is non-NULL, then this foreign key was declared to
  93184. ** map to an explicit list of columns in table pParent. Check if this
  93185. ** index matches those columns. Also, check that the index uses
  93186. ** the default collation sequences for each column. */
  93187. int i, j;
  93188. for(i=0; i<nCol; i++){
  93189. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  93190. char *zDfltColl; /* Def. collation for column */
  93191. char *zIdxCol; /* Name of indexed column */
  93192. /* If the index uses a collation sequence that is different from
  93193. ** the default collation sequence for the column, this index is
  93194. ** unusable. Bail out early in this case. */
  93195. zDfltColl = pParent->aCol[iCol].zColl;
  93196. if( !zDfltColl ){
  93197. zDfltColl = "BINARY";
  93198. }
  93199. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  93200. zIdxCol = pParent->aCol[iCol].zName;
  93201. for(j=0; j<nCol; j++){
  93202. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  93203. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  93204. break;
  93205. }
  93206. }
  93207. if( j==nCol ) break;
  93208. }
  93209. if( i==nCol ) break; /* pIdx is usable */
  93210. }
  93211. }
  93212. }
  93213. if( !pIdx ){
  93214. if( !pParse->disableTriggers ){
  93215. sqlite3ErrorMsg(pParse,
  93216. "foreign key mismatch - \"%w\" referencing \"%w\"",
  93217. pFKey->pFrom->zName, pFKey->zTo);
  93218. }
  93219. sqlite3DbFree(pParse->db, aiCol);
  93220. return 1;
  93221. }
  93222. *ppIdx = pIdx;
  93223. return 0;
  93224. }
  93225. /*
  93226. ** This function is called when a row is inserted into or deleted from the
  93227. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  93228. ** on the child table of pFKey, this function is invoked twice for each row
  93229. ** affected - once to "delete" the old row, and then again to "insert" the
  93230. ** new row.
  93231. **
  93232. ** Each time it is called, this function generates VDBE code to locate the
  93233. ** row in the parent table that corresponds to the row being inserted into
  93234. ** or deleted from the child table. If the parent row can be found, no
  93235. ** special action is taken. Otherwise, if the parent row can *not* be
  93236. ** found in the parent table:
  93237. **
  93238. ** Operation | FK type | Action taken
  93239. ** --------------------------------------------------------------------------
  93240. ** INSERT immediate Increment the "immediate constraint counter".
  93241. **
  93242. ** DELETE immediate Decrement the "immediate constraint counter".
  93243. **
  93244. ** INSERT deferred Increment the "deferred constraint counter".
  93245. **
  93246. ** DELETE deferred Decrement the "deferred constraint counter".
  93247. **
  93248. ** These operations are identified in the comment at the top of this file
  93249. ** (fkey.c) as "I.1" and "D.1".
  93250. */
  93251. static void fkLookupParent(
  93252. Parse *pParse, /* Parse context */
  93253. int iDb, /* Index of database housing pTab */
  93254. Table *pTab, /* Parent table of FK pFKey */
  93255. Index *pIdx, /* Unique index on parent key columns in pTab */
  93256. FKey *pFKey, /* Foreign key constraint */
  93257. int *aiCol, /* Map from parent key columns to child table columns */
  93258. int regData, /* Address of array containing child table row */
  93259. int nIncr, /* Increment constraint counter by this */
  93260. int isIgnore /* If true, pretend pTab contains all NULL values */
  93261. ){
  93262. int i; /* Iterator variable */
  93263. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  93264. int iCur = pParse->nTab - 1; /* Cursor number to use */
  93265. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  93266. /* If nIncr is less than zero, then check at runtime if there are any
  93267. ** outstanding constraints to resolve. If there are not, there is no need
  93268. ** to check if deleting this row resolves any outstanding violations.
  93269. **
  93270. ** Check if any of the key columns in the child table row are NULL. If
  93271. ** any are, then the constraint is considered satisfied. No need to
  93272. ** search for a matching row in the parent table. */
  93273. if( nIncr<0 ){
  93274. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  93275. VdbeCoverage(v);
  93276. }
  93277. for(i=0; i<pFKey->nCol; i++){
  93278. int iReg = aiCol[i] + regData + 1;
  93279. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  93280. }
  93281. if( isIgnore==0 ){
  93282. if( pIdx==0 ){
  93283. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  93284. ** column of the parent table (table pTab). */
  93285. int iMustBeInt; /* Address of MustBeInt instruction */
  93286. int regTemp = sqlite3GetTempReg(pParse);
  93287. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  93288. ** apply the affinity of the parent key). If this fails, then there
  93289. ** is no matching parent key. Before using MustBeInt, make a copy of
  93290. ** the value. Otherwise, the value inserted into the child key column
  93291. ** will have INTEGER affinity applied to it, which may not be correct. */
  93292. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  93293. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  93294. VdbeCoverage(v);
  93295. /* If the parent table is the same as the child table, and we are about
  93296. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  93297. ** then check if the row being inserted matches itself. If so, do not
  93298. ** increment the constraint-counter. */
  93299. if( pTab==pFKey->pFrom && nIncr==1 ){
  93300. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  93301. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  93302. }
  93303. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  93304. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  93305. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  93306. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  93307. sqlite3VdbeJumpHere(v, iMustBeInt);
  93308. sqlite3ReleaseTempReg(pParse, regTemp);
  93309. }else{
  93310. int nCol = pFKey->nCol;
  93311. int regTemp = sqlite3GetTempRange(pParse, nCol);
  93312. int regRec = sqlite3GetTempReg(pParse);
  93313. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  93314. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  93315. for(i=0; i<nCol; i++){
  93316. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  93317. }
  93318. /* If the parent table is the same as the child table, and we are about
  93319. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  93320. ** then check if the row being inserted matches itself. If so, do not
  93321. ** increment the constraint-counter.
  93322. **
  93323. ** If any of the parent-key values are NULL, then the row cannot match
  93324. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  93325. ** of the parent-key values are NULL (at this point it is known that
  93326. ** none of the child key values are).
  93327. */
  93328. if( pTab==pFKey->pFrom && nIncr==1 ){
  93329. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  93330. for(i=0; i<nCol; i++){
  93331. int iChild = aiCol[i]+1+regData;
  93332. int iParent = pIdx->aiColumn[i]+1+regData;
  93333. assert( aiCol[i]!=pTab->iPKey );
  93334. if( pIdx->aiColumn[i]==pTab->iPKey ){
  93335. /* The parent key is a composite key that includes the IPK column */
  93336. iParent = regData;
  93337. }
  93338. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  93339. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  93340. }
  93341. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  93342. }
  93343. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  93344. sqlite3IndexAffinityStr(v,pIdx), nCol);
  93345. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  93346. sqlite3ReleaseTempReg(pParse, regRec);
  93347. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  93348. }
  93349. }
  93350. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  93351. && !pParse->pToplevel
  93352. && !pParse->isMultiWrite
  93353. ){
  93354. /* Special case: If this is an INSERT statement that will insert exactly
  93355. ** one row into the table, raise a constraint immediately instead of
  93356. ** incrementing a counter. This is necessary as the VM code is being
  93357. ** generated for will not open a statement transaction. */
  93358. assert( nIncr==1 );
  93359. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  93360. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  93361. }else{
  93362. if( nIncr>0 && pFKey->isDeferred==0 ){
  93363. sqlite3MayAbort(pParse);
  93364. }
  93365. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  93366. }
  93367. sqlite3VdbeResolveLabel(v, iOk);
  93368. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  93369. }
  93370. /*
  93371. ** Return an Expr object that refers to a memory register corresponding
  93372. ** to column iCol of table pTab.
  93373. **
  93374. ** regBase is the first of an array of register that contains the data
  93375. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  93376. ** column. regBase+2 holds the second column, and so forth.
  93377. */
  93378. static Expr *exprTableRegister(
  93379. Parse *pParse, /* Parsing and code generating context */
  93380. Table *pTab, /* The table whose content is at r[regBase]... */
  93381. int regBase, /* Contents of table pTab */
  93382. i16 iCol /* Which column of pTab is desired */
  93383. ){
  93384. Expr *pExpr;
  93385. Column *pCol;
  93386. const char *zColl;
  93387. sqlite3 *db = pParse->db;
  93388. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  93389. if( pExpr ){
  93390. if( iCol>=0 && iCol!=pTab->iPKey ){
  93391. pCol = &pTab->aCol[iCol];
  93392. pExpr->iTable = regBase + iCol + 1;
  93393. pExpr->affinity = pCol->affinity;
  93394. zColl = pCol->zColl;
  93395. if( zColl==0 ) zColl = db->pDfltColl->zName;
  93396. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  93397. }else{
  93398. pExpr->iTable = regBase;
  93399. pExpr->affinity = SQLITE_AFF_INTEGER;
  93400. }
  93401. }
  93402. return pExpr;
  93403. }
  93404. /*
  93405. ** Return an Expr object that refers to column iCol of table pTab which
  93406. ** has cursor iCur.
  93407. */
  93408. static Expr *exprTableColumn(
  93409. sqlite3 *db, /* The database connection */
  93410. Table *pTab, /* The table whose column is desired */
  93411. int iCursor, /* The open cursor on the table */
  93412. i16 iCol /* The column that is wanted */
  93413. ){
  93414. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  93415. if( pExpr ){
  93416. pExpr->pTab = pTab;
  93417. pExpr->iTable = iCursor;
  93418. pExpr->iColumn = iCol;
  93419. }
  93420. return pExpr;
  93421. }
  93422. /*
  93423. ** This function is called to generate code executed when a row is deleted
  93424. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  93425. ** deferred, when a row is inserted into the same table. When generating
  93426. ** code for an SQL UPDATE operation, this function may be called twice -
  93427. ** once to "delete" the old row and once to "insert" the new row.
  93428. **
  93429. ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
  93430. ** the number of FK violations in the db) or +1 when deleting one (as this
  93431. ** may increase the number of FK constraint problems).
  93432. **
  93433. ** The code generated by this function scans through the rows in the child
  93434. ** table that correspond to the parent table row being deleted or inserted.
  93435. ** For each child row found, one of the following actions is taken:
  93436. **
  93437. ** Operation | FK type | Action taken
  93438. ** --------------------------------------------------------------------------
  93439. ** DELETE immediate Increment the "immediate constraint counter".
  93440. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  93441. ** throw a "FOREIGN KEY constraint failed" exception.
  93442. **
  93443. ** INSERT immediate Decrement the "immediate constraint counter".
  93444. **
  93445. ** DELETE deferred Increment the "deferred constraint counter".
  93446. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  93447. ** throw a "FOREIGN KEY constraint failed" exception.
  93448. **
  93449. ** INSERT deferred Decrement the "deferred constraint counter".
  93450. **
  93451. ** These operations are identified in the comment at the top of this file
  93452. ** (fkey.c) as "I.2" and "D.2".
  93453. */
  93454. static void fkScanChildren(
  93455. Parse *pParse, /* Parse context */
  93456. SrcList *pSrc, /* The child table to be scanned */
  93457. Table *pTab, /* The parent table */
  93458. Index *pIdx, /* Index on parent covering the foreign key */
  93459. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  93460. int *aiCol, /* Map from pIdx cols to child table cols */
  93461. int regData, /* Parent row data starts here */
  93462. int nIncr /* Amount to increment deferred counter by */
  93463. ){
  93464. sqlite3 *db = pParse->db; /* Database handle */
  93465. int i; /* Iterator variable */
  93466. Expr *pWhere = 0; /* WHERE clause to scan with */
  93467. NameContext sNameContext; /* Context used to resolve WHERE clause */
  93468. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  93469. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  93470. Vdbe *v = sqlite3GetVdbe(pParse);
  93471. assert( pIdx==0 || pIdx->pTable==pTab );
  93472. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  93473. assert( pIdx!=0 || pFKey->nCol==1 );
  93474. assert( pIdx!=0 || HasRowid(pTab) );
  93475. if( nIncr<0 ){
  93476. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  93477. VdbeCoverage(v);
  93478. }
  93479. /* Create an Expr object representing an SQL expression like:
  93480. **
  93481. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  93482. **
  93483. ** The collation sequence used for the comparison should be that of
  93484. ** the parent key columns. The affinity of the parent key column should
  93485. ** be applied to each child key value before the comparison takes place.
  93486. */
  93487. for(i=0; i<pFKey->nCol; i++){
  93488. Expr *pLeft; /* Value from parent table row */
  93489. Expr *pRight; /* Column ref to child table */
  93490. Expr *pEq; /* Expression (pLeft = pRight) */
  93491. i16 iCol; /* Index of column in child table */
  93492. const char *zCol; /* Name of column in child table */
  93493. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  93494. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  93495. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  93496. assert( iCol>=0 );
  93497. zCol = pFKey->pFrom->aCol[iCol].zName;
  93498. pRight = sqlite3Expr(db, TK_ID, zCol);
  93499. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  93500. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  93501. }
  93502. /* If the child table is the same as the parent table, then add terms
  93503. ** to the WHERE clause that prevent this entry from being scanned.
  93504. ** The added WHERE clause terms are like this:
  93505. **
  93506. ** $current_rowid!=rowid
  93507. ** NOT( $current_a==a AND $current_b==b AND ... )
  93508. **
  93509. ** The first form is used for rowid tables. The second form is used
  93510. ** for WITHOUT ROWID tables. In the second form, the primary key is
  93511. ** (a,b,...)
  93512. */
  93513. if( pTab==pFKey->pFrom && nIncr>0 ){
  93514. Expr *pNe; /* Expression (pLeft != pRight) */
  93515. Expr *pLeft; /* Value from parent table row */
  93516. Expr *pRight; /* Column ref to child table */
  93517. if( HasRowid(pTab) ){
  93518. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  93519. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  93520. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  93521. }else{
  93522. Expr *pEq, *pAll = 0;
  93523. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  93524. assert( pIdx!=0 );
  93525. for(i=0; i<pPk->nKeyCol; i++){
  93526. i16 iCol = pIdx->aiColumn[i];
  93527. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  93528. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  93529. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  93530. pAll = sqlite3ExprAnd(db, pAll, pEq);
  93531. }
  93532. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
  93533. }
  93534. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  93535. }
  93536. /* Resolve the references in the WHERE clause. */
  93537. memset(&sNameContext, 0, sizeof(NameContext));
  93538. sNameContext.pSrcList = pSrc;
  93539. sNameContext.pParse = pParse;
  93540. sqlite3ResolveExprNames(&sNameContext, pWhere);
  93541. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  93542. ** clause. For each row found, increment either the deferred or immediate
  93543. ** foreign key constraint counter. */
  93544. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  93545. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  93546. if( pWInfo ){
  93547. sqlite3WhereEnd(pWInfo);
  93548. }
  93549. /* Clean up the WHERE clause constructed above. */
  93550. sqlite3ExprDelete(db, pWhere);
  93551. if( iFkIfZero ){
  93552. sqlite3VdbeJumpHere(v, iFkIfZero);
  93553. }
  93554. }
  93555. /*
  93556. ** This function returns a linked list of FKey objects (connected by
  93557. ** FKey.pNextTo) holding all children of table pTab. For example,
  93558. ** given the following schema:
  93559. **
  93560. ** CREATE TABLE t1(a PRIMARY KEY);
  93561. ** CREATE TABLE t2(b REFERENCES t1(a);
  93562. **
  93563. ** Calling this function with table "t1" as an argument returns a pointer
  93564. ** to the FKey structure representing the foreign key constraint on table
  93565. ** "t2". Calling this function with "t2" as the argument would return a
  93566. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  93567. ** table).
  93568. */
  93569. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  93570. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  93571. }
  93572. /*
  93573. ** The second argument is a Trigger structure allocated by the
  93574. ** fkActionTrigger() routine. This function deletes the Trigger structure
  93575. ** and all of its sub-components.
  93576. **
  93577. ** The Trigger structure or any of its sub-components may be allocated from
  93578. ** the lookaside buffer belonging to database handle dbMem.
  93579. */
  93580. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  93581. if( p ){
  93582. TriggerStep *pStep = p->step_list;
  93583. sqlite3ExprDelete(dbMem, pStep->pWhere);
  93584. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  93585. sqlite3SelectDelete(dbMem, pStep->pSelect);
  93586. sqlite3ExprDelete(dbMem, p->pWhen);
  93587. sqlite3DbFree(dbMem, p);
  93588. }
  93589. }
  93590. /*
  93591. ** This function is called to generate code that runs when table pTab is
  93592. ** being dropped from the database. The SrcList passed as the second argument
  93593. ** to this function contains a single entry guaranteed to resolve to
  93594. ** table pTab.
  93595. **
  93596. ** Normally, no code is required. However, if either
  93597. **
  93598. ** (a) The table is the parent table of a FK constraint, or
  93599. ** (b) The table is the child table of a deferred FK constraint and it is
  93600. ** determined at runtime that there are outstanding deferred FK
  93601. ** constraint violations in the database,
  93602. **
  93603. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  93604. ** the table from the database. Triggers are disabled while running this
  93605. ** DELETE, but foreign key actions are not.
  93606. */
  93607. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  93608. sqlite3 *db = pParse->db;
  93609. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  93610. int iSkip = 0;
  93611. Vdbe *v = sqlite3GetVdbe(pParse);
  93612. assert( v ); /* VDBE has already been allocated */
  93613. if( sqlite3FkReferences(pTab)==0 ){
  93614. /* Search for a deferred foreign key constraint for which this table
  93615. ** is the child table. If one cannot be found, return without
  93616. ** generating any VDBE code. If one can be found, then jump over
  93617. ** the entire DELETE if there are no outstanding deferred constraints
  93618. ** when this statement is run. */
  93619. FKey *p;
  93620. for(p=pTab->pFKey; p; p=p->pNextFrom){
  93621. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  93622. }
  93623. if( !p ) return;
  93624. iSkip = sqlite3VdbeMakeLabel(v);
  93625. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  93626. }
  93627. pParse->disableTriggers = 1;
  93628. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  93629. pParse->disableTriggers = 0;
  93630. /* If the DELETE has generated immediate foreign key constraint
  93631. ** violations, halt the VDBE and return an error at this point, before
  93632. ** any modifications to the schema are made. This is because statement
  93633. ** transactions are not able to rollback schema changes.
  93634. **
  93635. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  93636. ** the statement transaction will not be rolled back even if FK
  93637. ** constraints are violated.
  93638. */
  93639. if( (db->flags & SQLITE_DeferFKs)==0 ){
  93640. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  93641. VdbeCoverage(v);
  93642. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  93643. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  93644. }
  93645. if( iSkip ){
  93646. sqlite3VdbeResolveLabel(v, iSkip);
  93647. }
  93648. }
  93649. }
  93650. /*
  93651. ** The second argument points to an FKey object representing a foreign key
  93652. ** for which pTab is the child table. An UPDATE statement against pTab
  93653. ** is currently being processed. For each column of the table that is
  93654. ** actually updated, the corresponding element in the aChange[] array
  93655. ** is zero or greater (if a column is unmodified the corresponding element
  93656. ** is set to -1). If the rowid column is modified by the UPDATE statement
  93657. ** the bChngRowid argument is non-zero.
  93658. **
  93659. ** This function returns true if any of the columns that are part of the
  93660. ** child key for FK constraint *p are modified.
  93661. */
  93662. static int fkChildIsModified(
  93663. Table *pTab, /* Table being updated */
  93664. FKey *p, /* Foreign key for which pTab is the child */
  93665. int *aChange, /* Array indicating modified columns */
  93666. int bChngRowid /* True if rowid is modified by this update */
  93667. ){
  93668. int i;
  93669. for(i=0; i<p->nCol; i++){
  93670. int iChildKey = p->aCol[i].iFrom;
  93671. if( aChange[iChildKey]>=0 ) return 1;
  93672. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  93673. }
  93674. return 0;
  93675. }
  93676. /*
  93677. ** The second argument points to an FKey object representing a foreign key
  93678. ** for which pTab is the parent table. An UPDATE statement against pTab
  93679. ** is currently being processed. For each column of the table that is
  93680. ** actually updated, the corresponding element in the aChange[] array
  93681. ** is zero or greater (if a column is unmodified the corresponding element
  93682. ** is set to -1). If the rowid column is modified by the UPDATE statement
  93683. ** the bChngRowid argument is non-zero.
  93684. **
  93685. ** This function returns true if any of the columns that are part of the
  93686. ** parent key for FK constraint *p are modified.
  93687. */
  93688. static int fkParentIsModified(
  93689. Table *pTab,
  93690. FKey *p,
  93691. int *aChange,
  93692. int bChngRowid
  93693. ){
  93694. int i;
  93695. for(i=0; i<p->nCol; i++){
  93696. char *zKey = p->aCol[i].zCol;
  93697. int iKey;
  93698. for(iKey=0; iKey<pTab->nCol; iKey++){
  93699. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  93700. Column *pCol = &pTab->aCol[iKey];
  93701. if( zKey ){
  93702. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  93703. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  93704. return 1;
  93705. }
  93706. }
  93707. }
  93708. }
  93709. return 0;
  93710. }
  93711. /*
  93712. ** Return true if the parser passed as the first argument is being
  93713. ** used to code a trigger that is really a "SET NULL" action belonging
  93714. ** to trigger pFKey.
  93715. */
  93716. static int isSetNullAction(Parse *pParse, FKey *pFKey){
  93717. Parse *pTop = sqlite3ParseToplevel(pParse);
  93718. if( pTop->pTriggerPrg ){
  93719. Trigger *p = pTop->pTriggerPrg->pTrigger;
  93720. if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
  93721. || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
  93722. ){
  93723. return 1;
  93724. }
  93725. }
  93726. return 0;
  93727. }
  93728. /*
  93729. ** This function is called when inserting, deleting or updating a row of
  93730. ** table pTab to generate VDBE code to perform foreign key constraint
  93731. ** processing for the operation.
  93732. **
  93733. ** For a DELETE operation, parameter regOld is passed the index of the
  93734. ** first register in an array of (pTab->nCol+1) registers containing the
  93735. ** rowid of the row being deleted, followed by each of the column values
  93736. ** of the row being deleted, from left to right. Parameter regNew is passed
  93737. ** zero in this case.
  93738. **
  93739. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  93740. ** first register of an array of (pTab->nCol+1) registers containing the new
  93741. ** row data.
  93742. **
  93743. ** For an UPDATE operation, this function is called twice. Once before
  93744. ** the original record is deleted from the table using the calling convention
  93745. ** described for DELETE. Then again after the original record is deleted
  93746. ** but before the new record is inserted using the INSERT convention.
  93747. */
  93748. SQLITE_PRIVATE void sqlite3FkCheck(
  93749. Parse *pParse, /* Parse context */
  93750. Table *pTab, /* Row is being deleted from this table */
  93751. int regOld, /* Previous row data is stored here */
  93752. int regNew, /* New row data is stored here */
  93753. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  93754. int bChngRowid /* True if rowid is UPDATEd */
  93755. ){
  93756. sqlite3 *db = pParse->db; /* Database handle */
  93757. FKey *pFKey; /* Used to iterate through FKs */
  93758. int iDb; /* Index of database containing pTab */
  93759. const char *zDb; /* Name of database containing pTab */
  93760. int isIgnoreErrors = pParse->disableTriggers;
  93761. /* Exactly one of regOld and regNew should be non-zero. */
  93762. assert( (regOld==0)!=(regNew==0) );
  93763. /* If foreign-keys are disabled, this function is a no-op. */
  93764. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  93765. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  93766. zDb = db->aDb[iDb].zName;
  93767. /* Loop through all the foreign key constraints for which pTab is the
  93768. ** child table (the table that the foreign key definition is part of). */
  93769. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  93770. Table *pTo; /* Parent table of foreign key pFKey */
  93771. Index *pIdx = 0; /* Index on key columns in pTo */
  93772. int *aiFree = 0;
  93773. int *aiCol;
  93774. int iCol;
  93775. int i;
  93776. int bIgnore = 0;
  93777. if( aChange
  93778. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  93779. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  93780. ){
  93781. continue;
  93782. }
  93783. /* Find the parent table of this foreign key. Also find a unique index
  93784. ** on the parent key columns in the parent table. If either of these
  93785. ** schema items cannot be located, set an error in pParse and return
  93786. ** early. */
  93787. if( pParse->disableTriggers ){
  93788. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  93789. }else{
  93790. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  93791. }
  93792. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  93793. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  93794. if( !isIgnoreErrors || db->mallocFailed ) return;
  93795. if( pTo==0 ){
  93796. /* If isIgnoreErrors is true, then a table is being dropped. In this
  93797. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  93798. ** before actually dropping it in order to check FK constraints.
  93799. ** If the parent table of an FK constraint on the current table is
  93800. ** missing, behave as if it is empty. i.e. decrement the relevant
  93801. ** FK counter for each row of the current table with non-NULL keys.
  93802. */
  93803. Vdbe *v = sqlite3GetVdbe(pParse);
  93804. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  93805. for(i=0; i<pFKey->nCol; i++){
  93806. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  93807. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  93808. }
  93809. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  93810. }
  93811. continue;
  93812. }
  93813. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  93814. if( aiFree ){
  93815. aiCol = aiFree;
  93816. }else{
  93817. iCol = pFKey->aCol[0].iFrom;
  93818. aiCol = &iCol;
  93819. }
  93820. for(i=0; i<pFKey->nCol; i++){
  93821. if( aiCol[i]==pTab->iPKey ){
  93822. aiCol[i] = -1;
  93823. }
  93824. #ifndef SQLITE_OMIT_AUTHORIZATION
  93825. /* Request permission to read the parent key columns. If the
  93826. ** authorization callback returns SQLITE_IGNORE, behave as if any
  93827. ** values read from the parent table are NULL. */
  93828. if( db->xAuth ){
  93829. int rcauth;
  93830. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  93831. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  93832. bIgnore = (rcauth==SQLITE_IGNORE);
  93833. }
  93834. #endif
  93835. }
  93836. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  93837. ** a cursor to use to search the unique index on the parent key columns
  93838. ** in the parent table. */
  93839. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  93840. pParse->nTab++;
  93841. if( regOld!=0 ){
  93842. /* A row is being removed from the child table. Search for the parent.
  93843. ** If the parent does not exist, removing the child row resolves an
  93844. ** outstanding foreign key constraint violation. */
  93845. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
  93846. }
  93847. if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
  93848. /* A row is being added to the child table. If a parent row cannot
  93849. ** be found, adding the child row has violated the FK constraint.
  93850. **
  93851. ** If this operation is being performed as part of a trigger program
  93852. ** that is actually a "SET NULL" action belonging to this very
  93853. ** foreign key, then omit this scan altogether. As all child key
  93854. ** values are guaranteed to be NULL, it is not possible for adding
  93855. ** this row to cause an FK violation. */
  93856. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
  93857. }
  93858. sqlite3DbFree(db, aiFree);
  93859. }
  93860. /* Loop through all the foreign key constraints that refer to this table.
  93861. ** (the "child" constraints) */
  93862. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  93863. Index *pIdx = 0; /* Foreign key index for pFKey */
  93864. SrcList *pSrc;
  93865. int *aiCol = 0;
  93866. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  93867. continue;
  93868. }
  93869. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  93870. && !pParse->pToplevel && !pParse->isMultiWrite
  93871. ){
  93872. assert( regOld==0 && regNew!=0 );
  93873. /* Inserting a single row into a parent table cannot cause (or fix)
  93874. ** an immediate foreign key violation. So do nothing in this case. */
  93875. continue;
  93876. }
  93877. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  93878. if( !isIgnoreErrors || db->mallocFailed ) return;
  93879. continue;
  93880. }
  93881. assert( aiCol || pFKey->nCol==1 );
  93882. /* Create a SrcList structure containing the child table. We need the
  93883. ** child table as a SrcList for sqlite3WhereBegin() */
  93884. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  93885. if( pSrc ){
  93886. struct SrcList_item *pItem = pSrc->a;
  93887. pItem->pTab = pFKey->pFrom;
  93888. pItem->zName = pFKey->pFrom->zName;
  93889. pItem->pTab->nRef++;
  93890. pItem->iCursor = pParse->nTab++;
  93891. if( regNew!=0 ){
  93892. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  93893. }
  93894. if( regOld!=0 ){
  93895. int eAction = pFKey->aAction[aChange!=0];
  93896. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  93897. /* If this is a deferred FK constraint, or a CASCADE or SET NULL
  93898. ** action applies, then any foreign key violations caused by
  93899. ** removing the parent key will be rectified by the action trigger.
  93900. ** So do not set the "may-abort" flag in this case.
  93901. **
  93902. ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
  93903. ** may-abort flag will eventually be set on this statement anyway
  93904. ** (when this function is called as part of processing the UPDATE
  93905. ** within the action trigger).
  93906. **
  93907. ** Note 2: At first glance it may seem like SQLite could simply omit
  93908. ** all OP_FkCounter related scans when either CASCADE or SET NULL
  93909. ** applies. The trouble starts if the CASCADE or SET NULL action
  93910. ** trigger causes other triggers or action rules attached to the
  93911. ** child table to fire. In these cases the fk constraint counters
  93912. ** might be set incorrectly if any OP_FkCounter related scans are
  93913. ** omitted. */
  93914. if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
  93915. sqlite3MayAbort(pParse);
  93916. }
  93917. }
  93918. pItem->zName = 0;
  93919. sqlite3SrcListDelete(db, pSrc);
  93920. }
  93921. sqlite3DbFree(db, aiCol);
  93922. }
  93923. }
  93924. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  93925. /*
  93926. ** This function is called before generating code to update or delete a
  93927. ** row contained in table pTab.
  93928. */
  93929. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  93930. Parse *pParse, /* Parse context */
  93931. Table *pTab /* Table being modified */
  93932. ){
  93933. u32 mask = 0;
  93934. if( pParse->db->flags&SQLITE_ForeignKeys ){
  93935. FKey *p;
  93936. int i;
  93937. for(p=pTab->pFKey; p; p=p->pNextFrom){
  93938. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  93939. }
  93940. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  93941. Index *pIdx = 0;
  93942. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  93943. if( pIdx ){
  93944. for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  93945. }
  93946. }
  93947. }
  93948. return mask;
  93949. }
  93950. /*
  93951. ** This function is called before generating code to update or delete a
  93952. ** row contained in table pTab. If the operation is a DELETE, then
  93953. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  93954. ** to an array of size N, where N is the number of columns in table pTab.
  93955. ** If the i'th column is not modified by the UPDATE, then the corresponding
  93956. ** entry in the aChange[] array is set to -1. If the column is modified,
  93957. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  93958. ** UPDATE statement modifies the rowid fields of the table.
  93959. **
  93960. ** If any foreign key processing will be required, this function returns
  93961. ** true. If there is no foreign key related processing, this function
  93962. ** returns false.
  93963. */
  93964. SQLITE_PRIVATE int sqlite3FkRequired(
  93965. Parse *pParse, /* Parse context */
  93966. Table *pTab, /* Table being modified */
  93967. int *aChange, /* Non-NULL for UPDATE operations */
  93968. int chngRowid /* True for UPDATE that affects rowid */
  93969. ){
  93970. if( pParse->db->flags&SQLITE_ForeignKeys ){
  93971. if( !aChange ){
  93972. /* A DELETE operation. Foreign key processing is required if the
  93973. ** table in question is either the child or parent table for any
  93974. ** foreign key constraint. */
  93975. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  93976. }else{
  93977. /* This is an UPDATE. Foreign key processing is only required if the
  93978. ** operation modifies one or more child or parent key columns. */
  93979. FKey *p;
  93980. /* Check if any child key columns are being modified. */
  93981. for(p=pTab->pFKey; p; p=p->pNextFrom){
  93982. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  93983. }
  93984. /* Check if any parent key columns are being modified. */
  93985. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  93986. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  93987. }
  93988. }
  93989. }
  93990. return 0;
  93991. }
  93992. /*
  93993. ** This function is called when an UPDATE or DELETE operation is being
  93994. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  93995. ** If the current operation is an UPDATE, then the pChanges parameter is
  93996. ** passed a pointer to the list of columns being modified. If it is a
  93997. ** DELETE, pChanges is passed a NULL pointer.
  93998. **
  93999. ** It returns a pointer to a Trigger structure containing a trigger
  94000. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  94001. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  94002. ** returned (these actions require no special handling by the triggers
  94003. ** sub-system, code for them is created by fkScanChildren()).
  94004. **
  94005. ** For example, if pFKey is the foreign key and pTab is table "p" in
  94006. ** the following schema:
  94007. **
  94008. ** CREATE TABLE p(pk PRIMARY KEY);
  94009. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  94010. **
  94011. ** then the returned trigger structure is equivalent to:
  94012. **
  94013. ** CREATE TRIGGER ... DELETE ON p BEGIN
  94014. ** DELETE FROM c WHERE ck = old.pk;
  94015. ** END;
  94016. **
  94017. ** The returned pointer is cached as part of the foreign key object. It
  94018. ** is eventually freed along with the rest of the foreign key object by
  94019. ** sqlite3FkDelete().
  94020. */
  94021. static Trigger *fkActionTrigger(
  94022. Parse *pParse, /* Parse context */
  94023. Table *pTab, /* Table being updated or deleted from */
  94024. FKey *pFKey, /* Foreign key to get action for */
  94025. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  94026. ){
  94027. sqlite3 *db = pParse->db; /* Database handle */
  94028. int action; /* One of OE_None, OE_Cascade etc. */
  94029. Trigger *pTrigger; /* Trigger definition to return */
  94030. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  94031. action = pFKey->aAction[iAction];
  94032. pTrigger = pFKey->apTrigger[iAction];
  94033. if( action!=OE_None && !pTrigger ){
  94034. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  94035. char const *zFrom; /* Name of child table */
  94036. int nFrom; /* Length in bytes of zFrom */
  94037. Index *pIdx = 0; /* Parent key index for this FK */
  94038. int *aiCol = 0; /* child table cols -> parent key cols */
  94039. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  94040. Expr *pWhere = 0; /* WHERE clause of trigger step */
  94041. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  94042. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  94043. int i; /* Iterator variable */
  94044. Expr *pWhen = 0; /* WHEN clause for the trigger */
  94045. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  94046. assert( aiCol || pFKey->nCol==1 );
  94047. for(i=0; i<pFKey->nCol; i++){
  94048. Token tOld = { "old", 3 }; /* Literal "old" token */
  94049. Token tNew = { "new", 3 }; /* Literal "new" token */
  94050. Token tFromCol; /* Name of column in child table */
  94051. Token tToCol; /* Name of column in parent table */
  94052. int iFromCol; /* Idx of column in child table */
  94053. Expr *pEq; /* tFromCol = OLD.tToCol */
  94054. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  94055. assert( iFromCol>=0 );
  94056. assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
  94057. tToCol.z = pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName;
  94058. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  94059. tToCol.n = sqlite3Strlen30(tToCol.z);
  94060. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  94061. /* Create the expression "OLD.zToCol = zFromCol". It is important
  94062. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  94063. ** that the affinity and collation sequence associated with the
  94064. ** parent table are used for the comparison. */
  94065. pEq = sqlite3PExpr(pParse, TK_EQ,
  94066. sqlite3PExpr(pParse, TK_DOT,
  94067. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  94068. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  94069. , 0),
  94070. sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
  94071. , 0);
  94072. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  94073. /* For ON UPDATE, construct the next term of the WHEN clause.
  94074. ** The final WHEN clause will be like this:
  94075. **
  94076. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  94077. */
  94078. if( pChanges ){
  94079. pEq = sqlite3PExpr(pParse, TK_IS,
  94080. sqlite3PExpr(pParse, TK_DOT,
  94081. sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
  94082. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  94083. 0),
  94084. sqlite3PExpr(pParse, TK_DOT,
  94085. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  94086. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
  94087. 0),
  94088. 0);
  94089. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  94090. }
  94091. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  94092. Expr *pNew;
  94093. if( action==OE_Cascade ){
  94094. pNew = sqlite3PExpr(pParse, TK_DOT,
  94095. sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
  94096. sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
  94097. , 0);
  94098. }else if( action==OE_SetDflt ){
  94099. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  94100. if( pDflt ){
  94101. pNew = sqlite3ExprDup(db, pDflt, 0);
  94102. }else{
  94103. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  94104. }
  94105. }else{
  94106. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  94107. }
  94108. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  94109. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  94110. }
  94111. }
  94112. sqlite3DbFree(db, aiCol);
  94113. zFrom = pFKey->pFrom->zName;
  94114. nFrom = sqlite3Strlen30(zFrom);
  94115. if( action==OE_Restrict ){
  94116. Token tFrom;
  94117. Expr *pRaise;
  94118. tFrom.z = zFrom;
  94119. tFrom.n = nFrom;
  94120. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  94121. if( pRaise ){
  94122. pRaise->affinity = OE_Abort;
  94123. }
  94124. pSelect = sqlite3SelectNew(pParse,
  94125. sqlite3ExprListAppend(pParse, 0, pRaise),
  94126. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  94127. pWhere,
  94128. 0, 0, 0, 0, 0, 0
  94129. );
  94130. pWhere = 0;
  94131. }
  94132. /* Disable lookaside memory allocation */
  94133. enableLookaside = db->lookaside.bEnabled;
  94134. db->lookaside.bEnabled = 0;
  94135. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  94136. sizeof(Trigger) + /* struct Trigger */
  94137. sizeof(TriggerStep) + /* Single step in trigger program */
  94138. nFrom + 1 /* Space for pStep->zTarget */
  94139. );
  94140. if( pTrigger ){
  94141. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  94142. pStep->zTarget = (char *)&pStep[1];
  94143. memcpy((char *)pStep->zTarget, zFrom, nFrom);
  94144. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  94145. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  94146. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  94147. if( pWhen ){
  94148. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  94149. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  94150. }
  94151. }
  94152. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  94153. db->lookaside.bEnabled = enableLookaside;
  94154. sqlite3ExprDelete(db, pWhere);
  94155. sqlite3ExprDelete(db, pWhen);
  94156. sqlite3ExprListDelete(db, pList);
  94157. sqlite3SelectDelete(db, pSelect);
  94158. if( db->mallocFailed==1 ){
  94159. fkTriggerDelete(db, pTrigger);
  94160. return 0;
  94161. }
  94162. assert( pStep!=0 );
  94163. switch( action ){
  94164. case OE_Restrict:
  94165. pStep->op = TK_SELECT;
  94166. break;
  94167. case OE_Cascade:
  94168. if( !pChanges ){
  94169. pStep->op = TK_DELETE;
  94170. break;
  94171. }
  94172. default:
  94173. pStep->op = TK_UPDATE;
  94174. }
  94175. pStep->pTrig = pTrigger;
  94176. pTrigger->pSchema = pTab->pSchema;
  94177. pTrigger->pTabSchema = pTab->pSchema;
  94178. pFKey->apTrigger[iAction] = pTrigger;
  94179. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  94180. }
  94181. return pTrigger;
  94182. }
  94183. /*
  94184. ** This function is called when deleting or updating a row to implement
  94185. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  94186. */
  94187. SQLITE_PRIVATE void sqlite3FkActions(
  94188. Parse *pParse, /* Parse context */
  94189. Table *pTab, /* Table being updated or deleted from */
  94190. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  94191. int regOld, /* Address of array containing old row */
  94192. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  94193. int bChngRowid /* True if rowid is UPDATEd */
  94194. ){
  94195. /* If foreign-key support is enabled, iterate through all FKs that
  94196. ** refer to table pTab. If there is an action associated with the FK
  94197. ** for this operation (either update or delete), invoke the associated
  94198. ** trigger sub-program. */
  94199. if( pParse->db->flags&SQLITE_ForeignKeys ){
  94200. FKey *pFKey; /* Iterator variable */
  94201. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  94202. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  94203. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  94204. if( pAct ){
  94205. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  94206. }
  94207. }
  94208. }
  94209. }
  94210. }
  94211. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  94212. /*
  94213. ** Free all memory associated with foreign key definitions attached to
  94214. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  94215. ** hash table.
  94216. */
  94217. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  94218. FKey *pFKey; /* Iterator variable */
  94219. FKey *pNext; /* Copy of pFKey->pNextFrom */
  94220. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  94221. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  94222. /* Remove the FK from the fkeyHash hash table. */
  94223. if( !db || db->pnBytesFreed==0 ){
  94224. if( pFKey->pPrevTo ){
  94225. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  94226. }else{
  94227. void *p = (void *)pFKey->pNextTo;
  94228. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  94229. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  94230. }
  94231. if( pFKey->pNextTo ){
  94232. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  94233. }
  94234. }
  94235. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  94236. ** classified as either immediate or deferred.
  94237. */
  94238. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  94239. /* Delete any triggers created to implement actions for this FK. */
  94240. #ifndef SQLITE_OMIT_TRIGGER
  94241. fkTriggerDelete(db, pFKey->apTrigger[0]);
  94242. fkTriggerDelete(db, pFKey->apTrigger[1]);
  94243. #endif
  94244. pNext = pFKey->pNextFrom;
  94245. sqlite3DbFree(db, pFKey);
  94246. }
  94247. }
  94248. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  94249. /************** End of fkey.c ************************************************/
  94250. /************** Begin file insert.c ******************************************/
  94251. /*
  94252. ** 2001 September 15
  94253. **
  94254. ** The author disclaims copyright to this source code. In place of
  94255. ** a legal notice, here is a blessing:
  94256. **
  94257. ** May you do good and not evil.
  94258. ** May you find forgiveness for yourself and forgive others.
  94259. ** May you share freely, never taking more than you give.
  94260. **
  94261. *************************************************************************
  94262. ** This file contains C code routines that are called by the parser
  94263. ** to handle INSERT statements in SQLite.
  94264. */
  94265. /* #include "sqliteInt.h" */
  94266. /*
  94267. ** Generate code that will
  94268. **
  94269. ** (1) acquire a lock for table pTab then
  94270. ** (2) open pTab as cursor iCur.
  94271. **
  94272. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  94273. ** for that table that is actually opened.
  94274. */
  94275. SQLITE_PRIVATE void sqlite3OpenTable(
  94276. Parse *pParse, /* Generate code into this VDBE */
  94277. int iCur, /* The cursor number of the table */
  94278. int iDb, /* The database index in sqlite3.aDb[] */
  94279. Table *pTab, /* The table to be opened */
  94280. int opcode /* OP_OpenRead or OP_OpenWrite */
  94281. ){
  94282. Vdbe *v;
  94283. assert( !IsVirtual(pTab) );
  94284. v = sqlite3GetVdbe(pParse);
  94285. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  94286. sqlite3TableLock(pParse, iDb, pTab->tnum,
  94287. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  94288. if( HasRowid(pTab) ){
  94289. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  94290. VdbeComment((v, "%s", pTab->zName));
  94291. }else{
  94292. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  94293. assert( pPk!=0 );
  94294. assert( pPk->tnum==pTab->tnum );
  94295. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  94296. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  94297. VdbeComment((v, "%s", pTab->zName));
  94298. }
  94299. }
  94300. /*
  94301. ** Return a pointer to the column affinity string associated with index
  94302. ** pIdx. A column affinity string has one character for each column in
  94303. ** the table, according to the affinity of the column:
  94304. **
  94305. ** Character Column affinity
  94306. ** ------------------------------
  94307. ** 'A' BLOB
  94308. ** 'B' TEXT
  94309. ** 'C' NUMERIC
  94310. ** 'D' INTEGER
  94311. ** 'F' REAL
  94312. **
  94313. ** An extra 'D' is appended to the end of the string to cover the
  94314. ** rowid that appears as the last column in every index.
  94315. **
  94316. ** Memory for the buffer containing the column index affinity string
  94317. ** is managed along with the rest of the Index structure. It will be
  94318. ** released when sqlite3DeleteIndex() is called.
  94319. */
  94320. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  94321. if( !pIdx->zColAff ){
  94322. /* The first time a column affinity string for a particular index is
  94323. ** required, it is allocated and populated here. It is then stored as
  94324. ** a member of the Index structure for subsequent use.
  94325. **
  94326. ** The column affinity string will eventually be deleted by
  94327. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  94328. ** up.
  94329. */
  94330. int n;
  94331. Table *pTab = pIdx->pTable;
  94332. sqlite3 *db = sqlite3VdbeDb(v);
  94333. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  94334. if( !pIdx->zColAff ){
  94335. db->mallocFailed = 1;
  94336. return 0;
  94337. }
  94338. for(n=0; n<pIdx->nColumn; n++){
  94339. i16 x = pIdx->aiColumn[n];
  94340. pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
  94341. }
  94342. pIdx->zColAff[n] = 0;
  94343. }
  94344. return pIdx->zColAff;
  94345. }
  94346. /*
  94347. ** Compute the affinity string for table pTab, if it has not already been
  94348. ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
  94349. **
  94350. ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
  94351. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  94352. ** for register iReg and following. Or if affinities exists and iReg==0,
  94353. ** then just set the P4 operand of the previous opcode (which should be
  94354. ** an OP_MakeRecord) to the affinity string.
  94355. **
  94356. ** A column affinity string has one character per column:
  94357. **
  94358. ** Character Column affinity
  94359. ** ------------------------------
  94360. ** 'A' BLOB
  94361. ** 'B' TEXT
  94362. ** 'C' NUMERIC
  94363. ** 'D' INTEGER
  94364. ** 'E' REAL
  94365. */
  94366. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  94367. int i;
  94368. char *zColAff = pTab->zColAff;
  94369. if( zColAff==0 ){
  94370. sqlite3 *db = sqlite3VdbeDb(v);
  94371. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  94372. if( !zColAff ){
  94373. db->mallocFailed = 1;
  94374. return;
  94375. }
  94376. for(i=0; i<pTab->nCol; i++){
  94377. zColAff[i] = pTab->aCol[i].affinity;
  94378. }
  94379. do{
  94380. zColAff[i--] = 0;
  94381. }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
  94382. pTab->zColAff = zColAff;
  94383. }
  94384. i = sqlite3Strlen30(zColAff);
  94385. if( i ){
  94386. if( iReg ){
  94387. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  94388. }else{
  94389. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  94390. }
  94391. }
  94392. }
  94393. /*
  94394. ** Return non-zero if the table pTab in database iDb or any of its indices
  94395. ** have been opened at any point in the VDBE program. This is used to see if
  94396. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  94397. ** run without using a temporary table for the results of the SELECT.
  94398. */
  94399. static int readsTable(Parse *p, int iDb, Table *pTab){
  94400. Vdbe *v = sqlite3GetVdbe(p);
  94401. int i;
  94402. int iEnd = sqlite3VdbeCurrentAddr(v);
  94403. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94404. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  94405. #endif
  94406. for(i=1; i<iEnd; i++){
  94407. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  94408. assert( pOp!=0 );
  94409. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  94410. Index *pIndex;
  94411. int tnum = pOp->p2;
  94412. if( tnum==pTab->tnum ){
  94413. return 1;
  94414. }
  94415. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  94416. if( tnum==pIndex->tnum ){
  94417. return 1;
  94418. }
  94419. }
  94420. }
  94421. #ifndef SQLITE_OMIT_VIRTUALTABLE
  94422. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  94423. assert( pOp->p4.pVtab!=0 );
  94424. assert( pOp->p4type==P4_VTAB );
  94425. return 1;
  94426. }
  94427. #endif
  94428. }
  94429. return 0;
  94430. }
  94431. #ifndef SQLITE_OMIT_AUTOINCREMENT
  94432. /*
  94433. ** Locate or create an AutoincInfo structure associated with table pTab
  94434. ** which is in database iDb. Return the register number for the register
  94435. ** that holds the maximum rowid.
  94436. **
  94437. ** There is at most one AutoincInfo structure per table even if the
  94438. ** same table is autoincremented multiple times due to inserts within
  94439. ** triggers. A new AutoincInfo structure is created if this is the
  94440. ** first use of table pTab. On 2nd and subsequent uses, the original
  94441. ** AutoincInfo structure is used.
  94442. **
  94443. ** Three memory locations are allocated:
  94444. **
  94445. ** (1) Register to hold the name of the pTab table.
  94446. ** (2) Register to hold the maximum ROWID of pTab.
  94447. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  94448. **
  94449. ** The 2nd register is the one that is returned. That is all the
  94450. ** insert routine needs to know about.
  94451. */
  94452. static int autoIncBegin(
  94453. Parse *pParse, /* Parsing context */
  94454. int iDb, /* Index of the database holding pTab */
  94455. Table *pTab /* The table we are writing to */
  94456. ){
  94457. int memId = 0; /* Register holding maximum rowid */
  94458. if( pTab->tabFlags & TF_Autoincrement ){
  94459. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  94460. AutoincInfo *pInfo;
  94461. pInfo = pToplevel->pAinc;
  94462. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  94463. if( pInfo==0 ){
  94464. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  94465. if( pInfo==0 ) return 0;
  94466. pInfo->pNext = pToplevel->pAinc;
  94467. pToplevel->pAinc = pInfo;
  94468. pInfo->pTab = pTab;
  94469. pInfo->iDb = iDb;
  94470. pToplevel->nMem++; /* Register to hold name of table */
  94471. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  94472. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  94473. }
  94474. memId = pInfo->regCtr;
  94475. }
  94476. return memId;
  94477. }
  94478. /*
  94479. ** This routine generates code that will initialize all of the
  94480. ** register used by the autoincrement tracker.
  94481. */
  94482. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  94483. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  94484. sqlite3 *db = pParse->db; /* The database connection */
  94485. Db *pDb; /* Database only autoinc table */
  94486. int memId; /* Register holding max rowid */
  94487. int addr; /* A VDBE address */
  94488. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  94489. /* This routine is never called during trigger-generation. It is
  94490. ** only called from the top-level */
  94491. assert( pParse->pTriggerTab==0 );
  94492. assert( pParse==sqlite3ParseToplevel(pParse) );
  94493. assert( v ); /* We failed long ago if this is not so */
  94494. for(p = pParse->pAinc; p; p = p->pNext){
  94495. pDb = &db->aDb[p->iDb];
  94496. memId = p->regCtr;
  94497. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  94498. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  94499. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  94500. addr = sqlite3VdbeCurrentAddr(v);
  94501. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  94502. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
  94503. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  94504. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
  94505. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  94506. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  94507. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  94508. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  94509. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
  94510. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  94511. sqlite3VdbeAddOp0(v, OP_Close);
  94512. }
  94513. }
  94514. /*
  94515. ** Update the maximum rowid for an autoincrement calculation.
  94516. **
  94517. ** This routine should be called when the top of the stack holds a
  94518. ** new rowid that is about to be inserted. If that new rowid is
  94519. ** larger than the maximum rowid in the memId memory cell, then the
  94520. ** memory cell is updated. The stack is unchanged.
  94521. */
  94522. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  94523. if( memId>0 ){
  94524. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  94525. }
  94526. }
  94527. /*
  94528. ** This routine generates the code needed to write autoincrement
  94529. ** maximum rowid values back into the sqlite_sequence register.
  94530. ** Every statement that might do an INSERT into an autoincrement
  94531. ** table (either directly or through triggers) needs to call this
  94532. ** routine just before the "exit" code.
  94533. */
  94534. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  94535. AutoincInfo *p;
  94536. Vdbe *v = pParse->pVdbe;
  94537. sqlite3 *db = pParse->db;
  94538. assert( v );
  94539. for(p = pParse->pAinc; p; p = p->pNext){
  94540. Db *pDb = &db->aDb[p->iDb];
  94541. int j1;
  94542. int iRec;
  94543. int memId = p->regCtr;
  94544. iRec = sqlite3GetTempReg(pParse);
  94545. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  94546. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  94547. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
  94548. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  94549. sqlite3VdbeJumpHere(v, j1);
  94550. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  94551. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  94552. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  94553. sqlite3VdbeAddOp0(v, OP_Close);
  94554. sqlite3ReleaseTempReg(pParse, iRec);
  94555. }
  94556. }
  94557. #else
  94558. /*
  94559. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  94560. ** above are all no-ops
  94561. */
  94562. # define autoIncBegin(A,B,C) (0)
  94563. # define autoIncStep(A,B,C)
  94564. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  94565. /* Forward declaration */
  94566. static int xferOptimization(
  94567. Parse *pParse, /* Parser context */
  94568. Table *pDest, /* The table we are inserting into */
  94569. Select *pSelect, /* A SELECT statement to use as the data source */
  94570. int onError, /* How to handle constraint errors */
  94571. int iDbDest /* The database of pDest */
  94572. );
  94573. /*
  94574. ** This routine is called to handle SQL of the following forms:
  94575. **
  94576. ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
  94577. ** insert into TABLE (IDLIST) select
  94578. ** insert into TABLE (IDLIST) default values
  94579. **
  94580. ** The IDLIST following the table name is always optional. If omitted,
  94581. ** then a list of all (non-hidden) columns for the table is substituted.
  94582. ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
  94583. ** is omitted.
  94584. **
  94585. ** For the pSelect parameter holds the values to be inserted for the
  94586. ** first two forms shown above. A VALUES clause is really just short-hand
  94587. ** for a SELECT statement that omits the FROM clause and everything else
  94588. ** that follows. If the pSelect parameter is NULL, that means that the
  94589. ** DEFAULT VALUES form of the INSERT statement is intended.
  94590. **
  94591. ** The code generated follows one of four templates. For a simple
  94592. ** insert with data coming from a single-row VALUES clause, the code executes
  94593. ** once straight down through. Pseudo-code follows (we call this
  94594. ** the "1st template"):
  94595. **
  94596. ** open write cursor to <table> and its indices
  94597. ** put VALUES clause expressions into registers
  94598. ** write the resulting record into <table>
  94599. ** cleanup
  94600. **
  94601. ** The three remaining templates assume the statement is of the form
  94602. **
  94603. ** INSERT INTO <table> SELECT ...
  94604. **
  94605. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  94606. ** in other words if the SELECT pulls all columns from a single table
  94607. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  94608. ** if <table2> and <table1> are distinct tables but have identical
  94609. ** schemas, including all the same indices, then a special optimization
  94610. ** is invoked that copies raw records from <table2> over to <table1>.
  94611. ** See the xferOptimization() function for the implementation of this
  94612. ** template. This is the 2nd template.
  94613. **
  94614. ** open a write cursor to <table>
  94615. ** open read cursor on <table2>
  94616. ** transfer all records in <table2> over to <table>
  94617. ** close cursors
  94618. ** foreach index on <table>
  94619. ** open a write cursor on the <table> index
  94620. ** open a read cursor on the corresponding <table2> index
  94621. ** transfer all records from the read to the write cursors
  94622. ** close cursors
  94623. ** end foreach
  94624. **
  94625. ** The 3rd template is for when the second template does not apply
  94626. ** and the SELECT clause does not read from <table> at any time.
  94627. ** The generated code follows this template:
  94628. **
  94629. ** X <- A
  94630. ** goto B
  94631. ** A: setup for the SELECT
  94632. ** loop over the rows in the SELECT
  94633. ** load values into registers R..R+n
  94634. ** yield X
  94635. ** end loop
  94636. ** cleanup after the SELECT
  94637. ** end-coroutine X
  94638. ** B: open write cursor to <table> and its indices
  94639. ** C: yield X, at EOF goto D
  94640. ** insert the select result into <table> from R..R+n
  94641. ** goto C
  94642. ** D: cleanup
  94643. **
  94644. ** The 4th template is used if the insert statement takes its
  94645. ** values from a SELECT but the data is being inserted into a table
  94646. ** that is also read as part of the SELECT. In the third form,
  94647. ** we have to use an intermediate table to store the results of
  94648. ** the select. The template is like this:
  94649. **
  94650. ** X <- A
  94651. ** goto B
  94652. ** A: setup for the SELECT
  94653. ** loop over the tables in the SELECT
  94654. ** load value into register R..R+n
  94655. ** yield X
  94656. ** end loop
  94657. ** cleanup after the SELECT
  94658. ** end co-routine R
  94659. ** B: open temp table
  94660. ** L: yield X, at EOF goto M
  94661. ** insert row from R..R+n into temp table
  94662. ** goto L
  94663. ** M: open write cursor to <table> and its indices
  94664. ** rewind temp table
  94665. ** C: loop over rows of intermediate table
  94666. ** transfer values form intermediate table into <table>
  94667. ** end loop
  94668. ** D: cleanup
  94669. */
  94670. SQLITE_PRIVATE void sqlite3Insert(
  94671. Parse *pParse, /* Parser context */
  94672. SrcList *pTabList, /* Name of table into which we are inserting */
  94673. Select *pSelect, /* A SELECT statement to use as the data source */
  94674. IdList *pColumn, /* Column names corresponding to IDLIST. */
  94675. int onError /* How to handle constraint errors */
  94676. ){
  94677. sqlite3 *db; /* The main database structure */
  94678. Table *pTab; /* The table to insert into. aka TABLE */
  94679. char *zTab; /* Name of the table into which we are inserting */
  94680. const char *zDb; /* Name of the database holding this table */
  94681. int i, j, idx; /* Loop counters */
  94682. Vdbe *v; /* Generate code into this virtual machine */
  94683. Index *pIdx; /* For looping over indices of the table */
  94684. int nColumn; /* Number of columns in the data */
  94685. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  94686. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  94687. int iIdxCur = 0; /* First index cursor */
  94688. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  94689. int endOfLoop; /* Label for the end of the insertion loop */
  94690. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  94691. int addrInsTop = 0; /* Jump to label "D" */
  94692. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  94693. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  94694. int iDb; /* Index of database holding TABLE */
  94695. Db *pDb; /* The database containing table being inserted into */
  94696. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  94697. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  94698. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  94699. u8 bIdListInOrder; /* True if IDLIST is in table order */
  94700. ExprList *pList = 0; /* List of VALUES() to be inserted */
  94701. /* Register allocations */
  94702. int regFromSelect = 0;/* Base register for data coming from SELECT */
  94703. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  94704. int regRowCount = 0; /* Memory cell used for the row counter */
  94705. int regIns; /* Block of regs holding rowid+data being inserted */
  94706. int regRowid; /* registers holding insert rowid */
  94707. int regData; /* register holding first column to insert */
  94708. int *aRegIdx = 0; /* One register allocated to each index */
  94709. #ifndef SQLITE_OMIT_TRIGGER
  94710. int isView; /* True if attempting to insert into a view */
  94711. Trigger *pTrigger; /* List of triggers on pTab, if required */
  94712. int tmask; /* Mask of trigger times */
  94713. #endif
  94714. db = pParse->db;
  94715. memset(&dest, 0, sizeof(dest));
  94716. if( pParse->nErr || db->mallocFailed ){
  94717. goto insert_cleanup;
  94718. }
  94719. /* If the Select object is really just a simple VALUES() list with a
  94720. ** single row (the common case) then keep that one row of values
  94721. ** and discard the other (unused) parts of the pSelect object
  94722. */
  94723. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  94724. pList = pSelect->pEList;
  94725. pSelect->pEList = 0;
  94726. sqlite3SelectDelete(db, pSelect);
  94727. pSelect = 0;
  94728. }
  94729. /* Locate the table into which we will be inserting new information.
  94730. */
  94731. assert( pTabList->nSrc==1 );
  94732. zTab = pTabList->a[0].zName;
  94733. if( NEVER(zTab==0) ) goto insert_cleanup;
  94734. pTab = sqlite3SrcListLookup(pParse, pTabList);
  94735. if( pTab==0 ){
  94736. goto insert_cleanup;
  94737. }
  94738. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  94739. assert( iDb<db->nDb );
  94740. pDb = &db->aDb[iDb];
  94741. zDb = pDb->zName;
  94742. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  94743. goto insert_cleanup;
  94744. }
  94745. withoutRowid = !HasRowid(pTab);
  94746. /* Figure out if we have any triggers and if the table being
  94747. ** inserted into is a view
  94748. */
  94749. #ifndef SQLITE_OMIT_TRIGGER
  94750. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  94751. isView = pTab->pSelect!=0;
  94752. #else
  94753. # define pTrigger 0
  94754. # define tmask 0
  94755. # define isView 0
  94756. #endif
  94757. #ifdef SQLITE_OMIT_VIEW
  94758. # undef isView
  94759. # define isView 0
  94760. #endif
  94761. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  94762. /* If pTab is really a view, make sure it has been initialized.
  94763. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  94764. */
  94765. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  94766. goto insert_cleanup;
  94767. }
  94768. /* Cannot insert into a read-only table.
  94769. */
  94770. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  94771. goto insert_cleanup;
  94772. }
  94773. /* Allocate a VDBE
  94774. */
  94775. v = sqlite3GetVdbe(pParse);
  94776. if( v==0 ) goto insert_cleanup;
  94777. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  94778. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  94779. #ifndef SQLITE_OMIT_XFER_OPT
  94780. /* If the statement is of the form
  94781. **
  94782. ** INSERT INTO <table1> SELECT * FROM <table2>;
  94783. **
  94784. ** Then special optimizations can be applied that make the transfer
  94785. ** very fast and which reduce fragmentation of indices.
  94786. **
  94787. ** This is the 2nd template.
  94788. */
  94789. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  94790. assert( !pTrigger );
  94791. assert( pList==0 );
  94792. goto insert_end;
  94793. }
  94794. #endif /* SQLITE_OMIT_XFER_OPT */
  94795. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  94796. ** sqlite_sequence table and store it in memory cell regAutoinc.
  94797. */
  94798. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  94799. /* Allocate registers for holding the rowid of the new row,
  94800. ** the content of the new row, and the assembled row record.
  94801. */
  94802. regRowid = regIns = pParse->nMem+1;
  94803. pParse->nMem += pTab->nCol + 1;
  94804. if( IsVirtual(pTab) ){
  94805. regRowid++;
  94806. pParse->nMem++;
  94807. }
  94808. regData = regRowid+1;
  94809. /* If the INSERT statement included an IDLIST term, then make sure
  94810. ** all elements of the IDLIST really are columns of the table and
  94811. ** remember the column indices.
  94812. **
  94813. ** If the table has an INTEGER PRIMARY KEY column and that column
  94814. ** is named in the IDLIST, then record in the ipkColumn variable
  94815. ** the index into IDLIST of the primary key column. ipkColumn is
  94816. ** the index of the primary key as it appears in IDLIST, not as
  94817. ** is appears in the original table. (The index of the INTEGER
  94818. ** PRIMARY KEY in the original table is pTab->iPKey.)
  94819. */
  94820. bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
  94821. if( pColumn ){
  94822. for(i=0; i<pColumn->nId; i++){
  94823. pColumn->a[i].idx = -1;
  94824. }
  94825. for(i=0; i<pColumn->nId; i++){
  94826. for(j=0; j<pTab->nCol; j++){
  94827. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  94828. pColumn->a[i].idx = j;
  94829. if( i!=j ) bIdListInOrder = 0;
  94830. if( j==pTab->iPKey ){
  94831. ipkColumn = i; assert( !withoutRowid );
  94832. }
  94833. break;
  94834. }
  94835. }
  94836. if( j>=pTab->nCol ){
  94837. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  94838. ipkColumn = i;
  94839. bIdListInOrder = 0;
  94840. }else{
  94841. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  94842. pTabList, 0, pColumn->a[i].zName);
  94843. pParse->checkSchema = 1;
  94844. goto insert_cleanup;
  94845. }
  94846. }
  94847. }
  94848. }
  94849. /* Figure out how many columns of data are supplied. If the data
  94850. ** is coming from a SELECT statement, then generate a co-routine that
  94851. ** produces a single row of the SELECT on each invocation. The
  94852. ** co-routine is the common header to the 3rd and 4th templates.
  94853. */
  94854. if( pSelect ){
  94855. /* Data is coming from a SELECT or from a multi-row VALUES clause.
  94856. ** Generate a co-routine to run the SELECT. */
  94857. int regYield; /* Register holding co-routine entry-point */
  94858. int addrTop; /* Top of the co-routine */
  94859. int rc; /* Result code */
  94860. regYield = ++pParse->nMem;
  94861. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  94862. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  94863. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  94864. dest.iSdst = bIdListInOrder ? regData : 0;
  94865. dest.nSdst = pTab->nCol;
  94866. rc = sqlite3Select(pParse, pSelect, &dest);
  94867. regFromSelect = dest.iSdst;
  94868. if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
  94869. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  94870. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  94871. assert( pSelect->pEList );
  94872. nColumn = pSelect->pEList->nExpr;
  94873. /* Set useTempTable to TRUE if the result of the SELECT statement
  94874. ** should be written into a temporary table (template 4). Set to
  94875. ** FALSE if each output row of the SELECT can be written directly into
  94876. ** the destination table (template 3).
  94877. **
  94878. ** A temp table must be used if the table being updated is also one
  94879. ** of the tables being read by the SELECT statement. Also use a
  94880. ** temp table in the case of row triggers.
  94881. */
  94882. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  94883. useTempTable = 1;
  94884. }
  94885. if( useTempTable ){
  94886. /* Invoke the coroutine to extract information from the SELECT
  94887. ** and add it to a transient table srcTab. The code generated
  94888. ** here is from the 4th template:
  94889. **
  94890. ** B: open temp table
  94891. ** L: yield X, goto M at EOF
  94892. ** insert row from R..R+n into temp table
  94893. ** goto L
  94894. ** M: ...
  94895. */
  94896. int regRec; /* Register to hold packed record */
  94897. int regTempRowid; /* Register to hold temp table ROWID */
  94898. int addrL; /* Label "L" */
  94899. srcTab = pParse->nTab++;
  94900. regRec = sqlite3GetTempReg(pParse);
  94901. regTempRowid = sqlite3GetTempReg(pParse);
  94902. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  94903. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  94904. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  94905. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  94906. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  94907. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
  94908. sqlite3VdbeJumpHere(v, addrL);
  94909. sqlite3ReleaseTempReg(pParse, regRec);
  94910. sqlite3ReleaseTempReg(pParse, regTempRowid);
  94911. }
  94912. }else{
  94913. /* This is the case if the data for the INSERT is coming from a
  94914. ** single-row VALUES clause
  94915. */
  94916. NameContext sNC;
  94917. memset(&sNC, 0, sizeof(sNC));
  94918. sNC.pParse = pParse;
  94919. srcTab = -1;
  94920. assert( useTempTable==0 );
  94921. nColumn = pList ? pList->nExpr : 0;
  94922. for(i=0; i<nColumn; i++){
  94923. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  94924. goto insert_cleanup;
  94925. }
  94926. }
  94927. }
  94928. /* If there is no IDLIST term but the table has an integer primary
  94929. ** key, the set the ipkColumn variable to the integer primary key
  94930. ** column index in the original table definition.
  94931. */
  94932. if( pColumn==0 && nColumn>0 ){
  94933. ipkColumn = pTab->iPKey;
  94934. }
  94935. /* Make sure the number of columns in the source data matches the number
  94936. ** of columns to be inserted into the table.
  94937. */
  94938. if( IsVirtual(pTab) ){
  94939. for(i=0; i<pTab->nCol; i++){
  94940. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  94941. }
  94942. }
  94943. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  94944. sqlite3ErrorMsg(pParse,
  94945. "table %S has %d columns but %d values were supplied",
  94946. pTabList, 0, pTab->nCol-nHidden, nColumn);
  94947. goto insert_cleanup;
  94948. }
  94949. if( pColumn!=0 && nColumn!=pColumn->nId ){
  94950. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  94951. goto insert_cleanup;
  94952. }
  94953. /* Initialize the count of rows to be inserted
  94954. */
  94955. if( db->flags & SQLITE_CountRows ){
  94956. regRowCount = ++pParse->nMem;
  94957. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  94958. }
  94959. /* If this is not a view, open the table and and all indices */
  94960. if( !isView ){
  94961. int nIdx;
  94962. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
  94963. &iDataCur, &iIdxCur);
  94964. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  94965. if( aRegIdx==0 ){
  94966. goto insert_cleanup;
  94967. }
  94968. for(i=0; i<nIdx; i++){
  94969. aRegIdx[i] = ++pParse->nMem;
  94970. }
  94971. }
  94972. /* This is the top of the main insertion loop */
  94973. if( useTempTable ){
  94974. /* This block codes the top of loop only. The complete loop is the
  94975. ** following pseudocode (template 4):
  94976. **
  94977. ** rewind temp table, if empty goto D
  94978. ** C: loop over rows of intermediate table
  94979. ** transfer values form intermediate table into <table>
  94980. ** end loop
  94981. ** D: ...
  94982. */
  94983. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  94984. addrCont = sqlite3VdbeCurrentAddr(v);
  94985. }else if( pSelect ){
  94986. /* This block codes the top of loop only. The complete loop is the
  94987. ** following pseudocode (template 3):
  94988. **
  94989. ** C: yield X, at EOF goto D
  94990. ** insert the select result into <table> from R..R+n
  94991. ** goto C
  94992. ** D: ...
  94993. */
  94994. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  94995. VdbeCoverage(v);
  94996. }
  94997. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  94998. */
  94999. endOfLoop = sqlite3VdbeMakeLabel(v);
  95000. if( tmask & TRIGGER_BEFORE ){
  95001. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  95002. /* build the NEW.* reference row. Note that if there is an INTEGER
  95003. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  95004. ** translated into a unique ID for the row. But on a BEFORE trigger,
  95005. ** we do not know what the unique ID will be (because the insert has
  95006. ** not happened yet) so we substitute a rowid of -1
  95007. */
  95008. if( ipkColumn<0 ){
  95009. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  95010. }else{
  95011. int j1;
  95012. assert( !withoutRowid );
  95013. if( useTempTable ){
  95014. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  95015. }else{
  95016. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  95017. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  95018. }
  95019. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  95020. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  95021. sqlite3VdbeJumpHere(v, j1);
  95022. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  95023. }
  95024. /* Cannot have triggers on a virtual table. If it were possible,
  95025. ** this block would have to account for hidden column.
  95026. */
  95027. assert( !IsVirtual(pTab) );
  95028. /* Create the new column data
  95029. */
  95030. for(i=0; i<pTab->nCol; i++){
  95031. if( pColumn==0 ){
  95032. j = i;
  95033. }else{
  95034. for(j=0; j<pColumn->nId; j++){
  95035. if( pColumn->a[j].idx==i ) break;
  95036. }
  95037. }
  95038. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  95039. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  95040. }else if( useTempTable ){
  95041. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  95042. }else{
  95043. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  95044. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  95045. }
  95046. }
  95047. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  95048. ** do not attempt any conversions before assembling the record.
  95049. ** If this is a real table, attempt conversions as required by the
  95050. ** table column affinities.
  95051. */
  95052. if( !isView ){
  95053. sqlite3TableAffinity(v, pTab, regCols+1);
  95054. }
  95055. /* Fire BEFORE or INSTEAD OF triggers */
  95056. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  95057. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  95058. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  95059. }
  95060. /* Compute the content of the next row to insert into a range of
  95061. ** registers beginning at regIns.
  95062. */
  95063. if( !isView ){
  95064. if( IsVirtual(pTab) ){
  95065. /* The row that the VUpdate opcode will delete: none */
  95066. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  95067. }
  95068. if( ipkColumn>=0 ){
  95069. if( useTempTable ){
  95070. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  95071. }else if( pSelect ){
  95072. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  95073. }else{
  95074. VdbeOp *pOp;
  95075. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  95076. pOp = sqlite3VdbeGetOp(v, -1);
  95077. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  95078. appendFlag = 1;
  95079. pOp->opcode = OP_NewRowid;
  95080. pOp->p1 = iDataCur;
  95081. pOp->p2 = regRowid;
  95082. pOp->p3 = regAutoinc;
  95083. }
  95084. }
  95085. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  95086. ** to generate a unique primary key value.
  95087. */
  95088. if( !appendFlag ){
  95089. int j1;
  95090. if( !IsVirtual(pTab) ){
  95091. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  95092. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  95093. sqlite3VdbeJumpHere(v, j1);
  95094. }else{
  95095. j1 = sqlite3VdbeCurrentAddr(v);
  95096. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
  95097. }
  95098. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  95099. }
  95100. }else if( IsVirtual(pTab) || withoutRowid ){
  95101. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  95102. }else{
  95103. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  95104. appendFlag = 1;
  95105. }
  95106. autoIncStep(pParse, regAutoinc, regRowid);
  95107. /* Compute data for all columns of the new entry, beginning
  95108. ** with the first column.
  95109. */
  95110. nHidden = 0;
  95111. for(i=0; i<pTab->nCol; i++){
  95112. int iRegStore = regRowid+1+i;
  95113. if( i==pTab->iPKey ){
  95114. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  95115. ** Whenever this column is read, the rowid will be substituted
  95116. ** in its place. Hence, fill this column with a NULL to avoid
  95117. ** taking up data space with information that will never be used.
  95118. ** As there may be shallow copies of this value, make it a soft-NULL */
  95119. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  95120. continue;
  95121. }
  95122. if( pColumn==0 ){
  95123. if( IsHiddenColumn(&pTab->aCol[i]) ){
  95124. assert( IsVirtual(pTab) );
  95125. j = -1;
  95126. nHidden++;
  95127. }else{
  95128. j = i - nHidden;
  95129. }
  95130. }else{
  95131. for(j=0; j<pColumn->nId; j++){
  95132. if( pColumn->a[j].idx==i ) break;
  95133. }
  95134. }
  95135. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  95136. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  95137. }else if( useTempTable ){
  95138. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  95139. }else if( pSelect ){
  95140. if( regFromSelect!=regData ){
  95141. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  95142. }
  95143. }else{
  95144. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  95145. }
  95146. }
  95147. /* Generate code to check constraints and generate index keys and
  95148. ** do the insertion.
  95149. */
  95150. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95151. if( IsVirtual(pTab) ){
  95152. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  95153. sqlite3VtabMakeWritable(pParse, pTab);
  95154. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  95155. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  95156. sqlite3MayAbort(pParse);
  95157. }else
  95158. #endif
  95159. {
  95160. int isReplace; /* Set to true if constraints may cause a replace */
  95161. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  95162. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
  95163. );
  95164. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  95165. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  95166. regIns, aRegIdx, 0, appendFlag, isReplace==0);
  95167. }
  95168. }
  95169. /* Update the count of rows that are inserted
  95170. */
  95171. if( (db->flags & SQLITE_CountRows)!=0 ){
  95172. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  95173. }
  95174. if( pTrigger ){
  95175. /* Code AFTER triggers */
  95176. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  95177. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  95178. }
  95179. /* The bottom of the main insertion loop, if the data source
  95180. ** is a SELECT statement.
  95181. */
  95182. sqlite3VdbeResolveLabel(v, endOfLoop);
  95183. if( useTempTable ){
  95184. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  95185. sqlite3VdbeJumpHere(v, addrInsTop);
  95186. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  95187. }else if( pSelect ){
  95188. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  95189. sqlite3VdbeJumpHere(v, addrInsTop);
  95190. }
  95191. if( !IsVirtual(pTab) && !isView ){
  95192. /* Close all tables opened */
  95193. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  95194. for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  95195. sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
  95196. }
  95197. }
  95198. insert_end:
  95199. /* Update the sqlite_sequence table by storing the content of the
  95200. ** maximum rowid counter values recorded while inserting into
  95201. ** autoincrement tables.
  95202. */
  95203. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  95204. sqlite3AutoincrementEnd(pParse);
  95205. }
  95206. /*
  95207. ** Return the number of rows inserted. If this routine is
  95208. ** generating code because of a call to sqlite3NestedParse(), do not
  95209. ** invoke the callback function.
  95210. */
  95211. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  95212. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  95213. sqlite3VdbeSetNumCols(v, 1);
  95214. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  95215. }
  95216. insert_cleanup:
  95217. sqlite3SrcListDelete(db, pTabList);
  95218. sqlite3ExprListDelete(db, pList);
  95219. sqlite3SelectDelete(db, pSelect);
  95220. sqlite3IdListDelete(db, pColumn);
  95221. sqlite3DbFree(db, aRegIdx);
  95222. }
  95223. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  95224. ** they may interfere with compilation of other functions in this file
  95225. ** (or in another file, if this file becomes part of the amalgamation). */
  95226. #ifdef isView
  95227. #undef isView
  95228. #endif
  95229. #ifdef pTrigger
  95230. #undef pTrigger
  95231. #endif
  95232. #ifdef tmask
  95233. #undef tmask
  95234. #endif
  95235. /*
  95236. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  95237. ** on table pTab.
  95238. **
  95239. ** The regNewData parameter is the first register in a range that contains
  95240. ** the data to be inserted or the data after the update. There will be
  95241. ** pTab->nCol+1 registers in this range. The first register (the one
  95242. ** that regNewData points to) will contain the new rowid, or NULL in the
  95243. ** case of a WITHOUT ROWID table. The second register in the range will
  95244. ** contain the content of the first table column. The third register will
  95245. ** contain the content of the second table column. And so forth.
  95246. **
  95247. ** The regOldData parameter is similar to regNewData except that it contains
  95248. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  95249. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  95250. ** checking regOldData for zero.
  95251. **
  95252. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  95253. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  95254. ** might be modified by the UPDATE. If pkChng is false, then the key of
  95255. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  95256. **
  95257. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  95258. ** was explicitly specified as part of the INSERT statement. If pkChng
  95259. ** is zero, it means that the either rowid is computed automatically or
  95260. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  95261. ** pkChng will only be true if the INSERT statement provides an integer
  95262. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  95263. **
  95264. ** The code generated by this routine will store new index entries into
  95265. ** registers identified by aRegIdx[]. No index entry is created for
  95266. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  95267. ** the same as the order of indices on the linked list of indices
  95268. ** at pTab->pIndex.
  95269. **
  95270. ** The caller must have already opened writeable cursors on the main
  95271. ** table and all applicable indices (that is to say, all indices for which
  95272. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  95273. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  95274. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  95275. ** for the first index in the pTab->pIndex list. Cursors for other indices
  95276. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  95277. **
  95278. ** This routine also generates code to check constraints. NOT NULL,
  95279. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  95280. ** then the appropriate action is performed. There are five possible
  95281. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  95282. **
  95283. ** Constraint type Action What Happens
  95284. ** --------------- ---------- ----------------------------------------
  95285. ** any ROLLBACK The current transaction is rolled back and
  95286. ** sqlite3_step() returns immediately with a
  95287. ** return code of SQLITE_CONSTRAINT.
  95288. **
  95289. ** any ABORT Back out changes from the current command
  95290. ** only (do not do a complete rollback) then
  95291. ** cause sqlite3_step() to return immediately
  95292. ** with SQLITE_CONSTRAINT.
  95293. **
  95294. ** any FAIL Sqlite3_step() returns immediately with a
  95295. ** return code of SQLITE_CONSTRAINT. The
  95296. ** transaction is not rolled back and any
  95297. ** changes to prior rows are retained.
  95298. **
  95299. ** any IGNORE The attempt in insert or update the current
  95300. ** row is skipped, without throwing an error.
  95301. ** Processing continues with the next row.
  95302. ** (There is an immediate jump to ignoreDest.)
  95303. **
  95304. ** NOT NULL REPLACE The NULL value is replace by the default
  95305. ** value for that column. If the default value
  95306. ** is NULL, the action is the same as ABORT.
  95307. **
  95308. ** UNIQUE REPLACE The other row that conflicts with the row
  95309. ** being inserted is removed.
  95310. **
  95311. ** CHECK REPLACE Illegal. The results in an exception.
  95312. **
  95313. ** Which action to take is determined by the overrideError parameter.
  95314. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  95315. ** is used. Or if pParse->onError==OE_Default then the onError value
  95316. ** for the constraint is used.
  95317. */
  95318. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  95319. Parse *pParse, /* The parser context */
  95320. Table *pTab, /* The table being inserted or updated */
  95321. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  95322. int iDataCur, /* Canonical data cursor (main table or PK index) */
  95323. int iIdxCur, /* First index cursor */
  95324. int regNewData, /* First register in a range holding values to insert */
  95325. int regOldData, /* Previous content. 0 for INSERTs */
  95326. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  95327. u8 overrideError, /* Override onError to this if not OE_Default */
  95328. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  95329. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  95330. ){
  95331. Vdbe *v; /* VDBE under constrution */
  95332. Index *pIdx; /* Pointer to one of the indices */
  95333. Index *pPk = 0; /* The PRIMARY KEY index */
  95334. sqlite3 *db; /* Database connection */
  95335. int i; /* loop counter */
  95336. int ix; /* Index loop counter */
  95337. int nCol; /* Number of columns */
  95338. int onError; /* Conflict resolution strategy */
  95339. int j1; /* Address of jump instruction */
  95340. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  95341. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  95342. int ipkTop = 0; /* Top of the rowid change constraint check */
  95343. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  95344. u8 isUpdate; /* True if this is an UPDATE operation */
  95345. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  95346. int regRowid = -1; /* Register holding ROWID value */
  95347. isUpdate = regOldData!=0;
  95348. db = pParse->db;
  95349. v = sqlite3GetVdbe(pParse);
  95350. assert( v!=0 );
  95351. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  95352. nCol = pTab->nCol;
  95353. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  95354. ** normal rowid tables. nPkField is the number of key fields in the
  95355. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  95356. ** number of fields in the true primary key of the table. */
  95357. if( HasRowid(pTab) ){
  95358. pPk = 0;
  95359. nPkField = 1;
  95360. }else{
  95361. pPk = sqlite3PrimaryKeyIndex(pTab);
  95362. nPkField = pPk->nKeyCol;
  95363. }
  95364. /* Record that this module has started */
  95365. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  95366. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  95367. /* Test all NOT NULL constraints.
  95368. */
  95369. for(i=0; i<nCol; i++){
  95370. if( i==pTab->iPKey ){
  95371. continue;
  95372. }
  95373. onError = pTab->aCol[i].notNull;
  95374. if( onError==OE_None ) continue;
  95375. if( overrideError!=OE_Default ){
  95376. onError = overrideError;
  95377. }else if( onError==OE_Default ){
  95378. onError = OE_Abort;
  95379. }
  95380. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  95381. onError = OE_Abort;
  95382. }
  95383. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  95384. || onError==OE_Ignore || onError==OE_Replace );
  95385. switch( onError ){
  95386. case OE_Abort:
  95387. sqlite3MayAbort(pParse);
  95388. /* Fall through */
  95389. case OE_Rollback:
  95390. case OE_Fail: {
  95391. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  95392. pTab->aCol[i].zName);
  95393. sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  95394. regNewData+1+i, zMsg, P4_DYNAMIC);
  95395. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  95396. VdbeCoverage(v);
  95397. break;
  95398. }
  95399. case OE_Ignore: {
  95400. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  95401. VdbeCoverage(v);
  95402. break;
  95403. }
  95404. default: {
  95405. assert( onError==OE_Replace );
  95406. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
  95407. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  95408. sqlite3VdbeJumpHere(v, j1);
  95409. break;
  95410. }
  95411. }
  95412. }
  95413. /* Test all CHECK constraints
  95414. */
  95415. #ifndef SQLITE_OMIT_CHECK
  95416. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  95417. ExprList *pCheck = pTab->pCheck;
  95418. pParse->ckBase = regNewData+1;
  95419. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  95420. for(i=0; i<pCheck->nExpr; i++){
  95421. int allOk = sqlite3VdbeMakeLabel(v);
  95422. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  95423. if( onError==OE_Ignore ){
  95424. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  95425. }else{
  95426. char *zName = pCheck->a[i].zName;
  95427. if( zName==0 ) zName = pTab->zName;
  95428. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  95429. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  95430. onError, zName, P4_TRANSIENT,
  95431. P5_ConstraintCheck);
  95432. }
  95433. sqlite3VdbeResolveLabel(v, allOk);
  95434. }
  95435. }
  95436. #endif /* !defined(SQLITE_OMIT_CHECK) */
  95437. /* If rowid is changing, make sure the new rowid does not previously
  95438. ** exist in the table.
  95439. */
  95440. if( pkChng && pPk==0 ){
  95441. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  95442. /* Figure out what action to take in case of a rowid collision */
  95443. onError = pTab->keyConf;
  95444. if( overrideError!=OE_Default ){
  95445. onError = overrideError;
  95446. }else if( onError==OE_Default ){
  95447. onError = OE_Abort;
  95448. }
  95449. if( isUpdate ){
  95450. /* pkChng!=0 does not mean that the rowid has change, only that
  95451. ** it might have changed. Skip the conflict logic below if the rowid
  95452. ** is unchanged. */
  95453. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  95454. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  95455. VdbeCoverage(v);
  95456. }
  95457. /* If the response to a rowid conflict is REPLACE but the response
  95458. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  95459. ** to defer the running of the rowid conflict checking until after
  95460. ** the UNIQUE constraints have run.
  95461. */
  95462. if( onError==OE_Replace && overrideError!=OE_Replace ){
  95463. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95464. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  95465. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  95466. break;
  95467. }
  95468. }
  95469. }
  95470. /* Check to see if the new rowid already exists in the table. Skip
  95471. ** the following conflict logic if it does not. */
  95472. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  95473. VdbeCoverage(v);
  95474. /* Generate code that deals with a rowid collision */
  95475. switch( onError ){
  95476. default: {
  95477. onError = OE_Abort;
  95478. /* Fall thru into the next case */
  95479. }
  95480. case OE_Rollback:
  95481. case OE_Abort:
  95482. case OE_Fail: {
  95483. sqlite3RowidConstraint(pParse, onError, pTab);
  95484. break;
  95485. }
  95486. case OE_Replace: {
  95487. /* If there are DELETE triggers on this table and the
  95488. ** recursive-triggers flag is set, call GenerateRowDelete() to
  95489. ** remove the conflicting row from the table. This will fire
  95490. ** the triggers and remove both the table and index b-tree entries.
  95491. **
  95492. ** Otherwise, if there are no triggers or the recursive-triggers
  95493. ** flag is not set, but the table has one or more indexes, call
  95494. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  95495. ** only. The table b-tree entry will be replaced by the new entry
  95496. ** when it is inserted.
  95497. **
  95498. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  95499. ** also invoke MultiWrite() to indicate that this VDBE may require
  95500. ** statement rollback (if the statement is aborted after the delete
  95501. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  95502. ** but being more selective here allows statements like:
  95503. **
  95504. ** REPLACE INTO t(rowid) VALUES($newrowid)
  95505. **
  95506. ** to run without a statement journal if there are no indexes on the
  95507. ** table.
  95508. */
  95509. Trigger *pTrigger = 0;
  95510. if( db->flags&SQLITE_RecTriggers ){
  95511. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  95512. }
  95513. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  95514. sqlite3MultiWrite(pParse);
  95515. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  95516. regNewData, 1, 0, OE_Replace, 1);
  95517. }else if( pTab->pIndex ){
  95518. sqlite3MultiWrite(pParse);
  95519. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  95520. }
  95521. seenReplace = 1;
  95522. break;
  95523. }
  95524. case OE_Ignore: {
  95525. /*assert( seenReplace==0 );*/
  95526. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  95527. break;
  95528. }
  95529. }
  95530. sqlite3VdbeResolveLabel(v, addrRowidOk);
  95531. if( ipkTop ){
  95532. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  95533. sqlite3VdbeJumpHere(v, ipkTop);
  95534. }
  95535. }
  95536. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  95537. ** index and making sure that duplicate entries do not already exist.
  95538. ** Compute the revised record entries for indices as we go.
  95539. **
  95540. ** This loop also handles the case of the PRIMARY KEY index for a
  95541. ** WITHOUT ROWID table.
  95542. */
  95543. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  95544. int regIdx; /* Range of registers hold conent for pIdx */
  95545. int regR; /* Range of registers holding conflicting PK */
  95546. int iThisCur; /* Cursor for this UNIQUE index */
  95547. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  95548. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  95549. if( bAffinityDone==0 ){
  95550. sqlite3TableAffinity(v, pTab, regNewData+1);
  95551. bAffinityDone = 1;
  95552. }
  95553. iThisCur = iIdxCur+ix;
  95554. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  95555. /* Skip partial indices for which the WHERE clause is not true */
  95556. if( pIdx->pPartIdxWhere ){
  95557. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  95558. pParse->ckBase = regNewData+1;
  95559. sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  95560. SQLITE_JUMPIFNULL);
  95561. pParse->ckBase = 0;
  95562. }
  95563. /* Create a record for this index entry as it should appear after
  95564. ** the insert or update. Store that record in the aRegIdx[ix] register
  95565. */
  95566. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
  95567. for(i=0; i<pIdx->nColumn; i++){
  95568. int iField = pIdx->aiColumn[i];
  95569. int x;
  95570. if( iField<0 || iField==pTab->iPKey ){
  95571. if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
  95572. x = regNewData;
  95573. regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
  95574. }else{
  95575. x = iField + regNewData + 1;
  95576. }
  95577. sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
  95578. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  95579. }
  95580. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  95581. VdbeComment((v, "for %s", pIdx->zName));
  95582. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  95583. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  95584. ** of a WITHOUT ROWID table and there has been no change the
  95585. ** primary key, then no collision is possible. The collision detection
  95586. ** logic below can all be skipped. */
  95587. if( isUpdate && pPk==pIdx && pkChng==0 ){
  95588. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  95589. continue;
  95590. }
  95591. /* Find out what action to take in case there is a uniqueness conflict */
  95592. onError = pIdx->onError;
  95593. if( onError==OE_None ){
  95594. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  95595. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  95596. continue; /* pIdx is not a UNIQUE index */
  95597. }
  95598. if( overrideError!=OE_Default ){
  95599. onError = overrideError;
  95600. }else if( onError==OE_Default ){
  95601. onError = OE_Abort;
  95602. }
  95603. /* Check to see if the new index entry will be unique */
  95604. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  95605. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  95606. /* Generate code to handle collisions */
  95607. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  95608. if( isUpdate || onError==OE_Replace ){
  95609. if( HasRowid(pTab) ){
  95610. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  95611. /* Conflict only if the rowid of the existing index entry
  95612. ** is different from old-rowid */
  95613. if( isUpdate ){
  95614. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  95615. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  95616. VdbeCoverage(v);
  95617. }
  95618. }else{
  95619. int x;
  95620. /* Extract the PRIMARY KEY from the end of the index entry and
  95621. ** store it in registers regR..regR+nPk-1 */
  95622. if( pIdx!=pPk ){
  95623. for(i=0; i<pPk->nKeyCol; i++){
  95624. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  95625. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  95626. VdbeComment((v, "%s.%s", pTab->zName,
  95627. pTab->aCol[pPk->aiColumn[i]].zName));
  95628. }
  95629. }
  95630. if( isUpdate ){
  95631. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  95632. ** table, only conflict if the new PRIMARY KEY values are actually
  95633. ** different from the old.
  95634. **
  95635. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  95636. ** of the matched index row are different from the original PRIMARY
  95637. ** KEY values of this row before the update. */
  95638. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  95639. int op = OP_Ne;
  95640. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  95641. for(i=0; i<pPk->nKeyCol; i++){
  95642. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  95643. x = pPk->aiColumn[i];
  95644. if( i==(pPk->nKeyCol-1) ){
  95645. addrJump = addrUniqueOk;
  95646. op = OP_Eq;
  95647. }
  95648. sqlite3VdbeAddOp4(v, op,
  95649. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  95650. );
  95651. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  95652. VdbeCoverageIf(v, op==OP_Eq);
  95653. VdbeCoverageIf(v, op==OP_Ne);
  95654. }
  95655. }
  95656. }
  95657. }
  95658. /* Generate code that executes if the new index entry is not unique */
  95659. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  95660. || onError==OE_Ignore || onError==OE_Replace );
  95661. switch( onError ){
  95662. case OE_Rollback:
  95663. case OE_Abort:
  95664. case OE_Fail: {
  95665. sqlite3UniqueConstraint(pParse, onError, pIdx);
  95666. break;
  95667. }
  95668. case OE_Ignore: {
  95669. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  95670. break;
  95671. }
  95672. default: {
  95673. Trigger *pTrigger = 0;
  95674. assert( onError==OE_Replace );
  95675. sqlite3MultiWrite(pParse);
  95676. if( db->flags&SQLITE_RecTriggers ){
  95677. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  95678. }
  95679. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  95680. regR, nPkField, 0, OE_Replace, pIdx==pPk);
  95681. seenReplace = 1;
  95682. break;
  95683. }
  95684. }
  95685. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  95686. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  95687. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  95688. }
  95689. if( ipkTop ){
  95690. sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
  95691. sqlite3VdbeJumpHere(v, ipkBottom);
  95692. }
  95693. *pbMayReplace = seenReplace;
  95694. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  95695. }
  95696. /*
  95697. ** This routine generates code to finish the INSERT or UPDATE operation
  95698. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  95699. ** A consecutive range of registers starting at regNewData contains the
  95700. ** rowid and the content to be inserted.
  95701. **
  95702. ** The arguments to this routine should be the same as the first six
  95703. ** arguments to sqlite3GenerateConstraintChecks.
  95704. */
  95705. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  95706. Parse *pParse, /* The parser context */
  95707. Table *pTab, /* the table into which we are inserting */
  95708. int iDataCur, /* Cursor of the canonical data source */
  95709. int iIdxCur, /* First index cursor */
  95710. int regNewData, /* Range of content */
  95711. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  95712. int isUpdate, /* True for UPDATE, False for INSERT */
  95713. int appendBias, /* True if this is likely to be an append */
  95714. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  95715. ){
  95716. Vdbe *v; /* Prepared statements under construction */
  95717. Index *pIdx; /* An index being inserted or updated */
  95718. u8 pik_flags; /* flag values passed to the btree insert */
  95719. int regData; /* Content registers (after the rowid) */
  95720. int regRec; /* Register holding assembled record for the table */
  95721. int i; /* Loop counter */
  95722. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  95723. v = sqlite3GetVdbe(pParse);
  95724. assert( v!=0 );
  95725. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  95726. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  95727. if( aRegIdx[i]==0 ) continue;
  95728. bAffinityDone = 1;
  95729. if( pIdx->pPartIdxWhere ){
  95730. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  95731. VdbeCoverage(v);
  95732. }
  95733. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  95734. pik_flags = 0;
  95735. if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  95736. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  95737. assert( pParse->nested==0 );
  95738. pik_flags |= OPFLAG_NCHANGE;
  95739. }
  95740. if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
  95741. }
  95742. if( !HasRowid(pTab) ) return;
  95743. regData = regNewData + 1;
  95744. regRec = sqlite3GetTempReg(pParse);
  95745. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  95746. if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  95747. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  95748. if( pParse->nested ){
  95749. pik_flags = 0;
  95750. }else{
  95751. pik_flags = OPFLAG_NCHANGE;
  95752. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  95753. }
  95754. if( appendBias ){
  95755. pik_flags |= OPFLAG_APPEND;
  95756. }
  95757. if( useSeekResult ){
  95758. pik_flags |= OPFLAG_USESEEKRESULT;
  95759. }
  95760. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  95761. if( !pParse->nested ){
  95762. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  95763. }
  95764. sqlite3VdbeChangeP5(v, pik_flags);
  95765. }
  95766. /*
  95767. ** Allocate cursors for the pTab table and all its indices and generate
  95768. ** code to open and initialized those cursors.
  95769. **
  95770. ** The cursor for the object that contains the complete data (normally
  95771. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  95772. ** ROWID table) is returned in *piDataCur. The first index cursor is
  95773. ** returned in *piIdxCur. The number of indices is returned.
  95774. **
  95775. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  95776. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  95777. ** If iBase is negative, then allocate the next available cursor.
  95778. **
  95779. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  95780. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  95781. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  95782. ** pTab->pIndex list.
  95783. **
  95784. ** If pTab is a virtual table, then this routine is a no-op and the
  95785. ** *piDataCur and *piIdxCur values are left uninitialized.
  95786. */
  95787. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  95788. Parse *pParse, /* Parsing context */
  95789. Table *pTab, /* Table to be opened */
  95790. int op, /* OP_OpenRead or OP_OpenWrite */
  95791. int iBase, /* Use this for the table cursor, if there is one */
  95792. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  95793. int *piDataCur, /* Write the database source cursor number here */
  95794. int *piIdxCur /* Write the first index cursor number here */
  95795. ){
  95796. int i;
  95797. int iDb;
  95798. int iDataCur;
  95799. Index *pIdx;
  95800. Vdbe *v;
  95801. assert( op==OP_OpenRead || op==OP_OpenWrite );
  95802. if( IsVirtual(pTab) ){
  95803. /* This routine is a no-op for virtual tables. Leave the output
  95804. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  95805. ** can detect if they are used by mistake in the caller. */
  95806. return 0;
  95807. }
  95808. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  95809. v = sqlite3GetVdbe(pParse);
  95810. assert( v!=0 );
  95811. if( iBase<0 ) iBase = pParse->nTab;
  95812. iDataCur = iBase++;
  95813. if( piDataCur ) *piDataCur = iDataCur;
  95814. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  95815. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  95816. }else{
  95817. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  95818. }
  95819. if( piIdxCur ) *piIdxCur = iBase;
  95820. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  95821. int iIdxCur = iBase++;
  95822. assert( pIdx->pSchema==pTab->pSchema );
  95823. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
  95824. *piDataCur = iIdxCur;
  95825. }
  95826. if( aToOpen==0 || aToOpen[i+1] ){
  95827. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  95828. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  95829. VdbeComment((v, "%s", pIdx->zName));
  95830. }
  95831. }
  95832. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  95833. return i;
  95834. }
  95835. #ifdef SQLITE_TEST
  95836. /*
  95837. ** The following global variable is incremented whenever the
  95838. ** transfer optimization is used. This is used for testing
  95839. ** purposes only - to make sure the transfer optimization really
  95840. ** is happening when it is supposed to.
  95841. */
  95842. SQLITE_API int sqlite3_xferopt_count;
  95843. #endif /* SQLITE_TEST */
  95844. #ifndef SQLITE_OMIT_XFER_OPT
  95845. /*
  95846. ** Check to collation names to see if they are compatible.
  95847. */
  95848. static int xferCompatibleCollation(const char *z1, const char *z2){
  95849. if( z1==0 ){
  95850. return z2==0;
  95851. }
  95852. if( z2==0 ){
  95853. return 0;
  95854. }
  95855. return sqlite3StrICmp(z1, z2)==0;
  95856. }
  95857. /*
  95858. ** Check to see if index pSrc is compatible as a source of data
  95859. ** for index pDest in an insert transfer optimization. The rules
  95860. ** for a compatible index:
  95861. **
  95862. ** * The index is over the same set of columns
  95863. ** * The same DESC and ASC markings occurs on all columns
  95864. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  95865. ** * The same collating sequence on each column
  95866. ** * The index has the exact same WHERE clause
  95867. */
  95868. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  95869. int i;
  95870. assert( pDest && pSrc );
  95871. assert( pDest->pTable!=pSrc->pTable );
  95872. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  95873. return 0; /* Different number of columns */
  95874. }
  95875. if( pDest->onError!=pSrc->onError ){
  95876. return 0; /* Different conflict resolution strategies */
  95877. }
  95878. for(i=0; i<pSrc->nKeyCol; i++){
  95879. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  95880. return 0; /* Different columns indexed */
  95881. }
  95882. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  95883. return 0; /* Different sort orders */
  95884. }
  95885. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  95886. return 0; /* Different collating sequences */
  95887. }
  95888. }
  95889. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  95890. return 0; /* Different WHERE clauses */
  95891. }
  95892. /* If no test above fails then the indices must be compatible */
  95893. return 1;
  95894. }
  95895. /*
  95896. ** Attempt the transfer optimization on INSERTs of the form
  95897. **
  95898. ** INSERT INTO tab1 SELECT * FROM tab2;
  95899. **
  95900. ** The xfer optimization transfers raw records from tab2 over to tab1.
  95901. ** Columns are not decoded and reassembled, which greatly improves
  95902. ** performance. Raw index records are transferred in the same way.
  95903. **
  95904. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  95905. ** There are lots of rules for determining compatibility - see comments
  95906. ** embedded in the code for details.
  95907. **
  95908. ** This routine returns TRUE if the optimization is guaranteed to be used.
  95909. ** Sometimes the xfer optimization will only work if the destination table
  95910. ** is empty - a factor that can only be determined at run-time. In that
  95911. ** case, this routine generates code for the xfer optimization but also
  95912. ** does a test to see if the destination table is empty and jumps over the
  95913. ** xfer optimization code if the test fails. In that case, this routine
  95914. ** returns FALSE so that the caller will know to go ahead and generate
  95915. ** an unoptimized transfer. This routine also returns FALSE if there
  95916. ** is no chance that the xfer optimization can be applied.
  95917. **
  95918. ** This optimization is particularly useful at making VACUUM run faster.
  95919. */
  95920. static int xferOptimization(
  95921. Parse *pParse, /* Parser context */
  95922. Table *pDest, /* The table we are inserting into */
  95923. Select *pSelect, /* A SELECT statement to use as the data source */
  95924. int onError, /* How to handle constraint errors */
  95925. int iDbDest /* The database of pDest */
  95926. ){
  95927. sqlite3 *db = pParse->db;
  95928. ExprList *pEList; /* The result set of the SELECT */
  95929. Table *pSrc; /* The table in the FROM clause of SELECT */
  95930. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  95931. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  95932. int i; /* Loop counter */
  95933. int iDbSrc; /* The database of pSrc */
  95934. int iSrc, iDest; /* Cursors from source and destination */
  95935. int addr1, addr2; /* Loop addresses */
  95936. int emptyDestTest = 0; /* Address of test for empty pDest */
  95937. int emptySrcTest = 0; /* Address of test for empty pSrc */
  95938. Vdbe *v; /* The VDBE we are building */
  95939. int regAutoinc; /* Memory register used by AUTOINC */
  95940. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  95941. int regData, regRowid; /* Registers holding data and rowid */
  95942. if( pSelect==0 ){
  95943. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  95944. }
  95945. if( pParse->pWith || pSelect->pWith ){
  95946. /* Do not attempt to process this query if there are an WITH clauses
  95947. ** attached to it. Proceeding may generate a false "no such table: xxx"
  95948. ** error if pSelect reads from a CTE named "xxx". */
  95949. return 0;
  95950. }
  95951. if( sqlite3TriggerList(pParse, pDest) ){
  95952. return 0; /* tab1 must not have triggers */
  95953. }
  95954. #ifndef SQLITE_OMIT_VIRTUALTABLE
  95955. if( pDest->tabFlags & TF_Virtual ){
  95956. return 0; /* tab1 must not be a virtual table */
  95957. }
  95958. #endif
  95959. if( onError==OE_Default ){
  95960. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  95961. if( onError==OE_Default ) onError = OE_Abort;
  95962. }
  95963. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  95964. if( pSelect->pSrc->nSrc!=1 ){
  95965. return 0; /* FROM clause must have exactly one term */
  95966. }
  95967. if( pSelect->pSrc->a[0].pSelect ){
  95968. return 0; /* FROM clause cannot contain a subquery */
  95969. }
  95970. if( pSelect->pWhere ){
  95971. return 0; /* SELECT may not have a WHERE clause */
  95972. }
  95973. if( pSelect->pOrderBy ){
  95974. return 0; /* SELECT may not have an ORDER BY clause */
  95975. }
  95976. /* Do not need to test for a HAVING clause. If HAVING is present but
  95977. ** there is no ORDER BY, we will get an error. */
  95978. if( pSelect->pGroupBy ){
  95979. return 0; /* SELECT may not have a GROUP BY clause */
  95980. }
  95981. if( pSelect->pLimit ){
  95982. return 0; /* SELECT may not have a LIMIT clause */
  95983. }
  95984. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  95985. if( pSelect->pPrior ){
  95986. return 0; /* SELECT may not be a compound query */
  95987. }
  95988. if( pSelect->selFlags & SF_Distinct ){
  95989. return 0; /* SELECT may not be DISTINCT */
  95990. }
  95991. pEList = pSelect->pEList;
  95992. assert( pEList!=0 );
  95993. if( pEList->nExpr!=1 ){
  95994. return 0; /* The result set must have exactly one column */
  95995. }
  95996. assert( pEList->a[0].pExpr );
  95997. if( pEList->a[0].pExpr->op!=TK_ALL ){
  95998. return 0; /* The result set must be the special operator "*" */
  95999. }
  96000. /* At this point we have established that the statement is of the
  96001. ** correct syntactic form to participate in this optimization. Now
  96002. ** we have to check the semantics.
  96003. */
  96004. pItem = pSelect->pSrc->a;
  96005. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  96006. if( pSrc==0 ){
  96007. return 0; /* FROM clause does not contain a real table */
  96008. }
  96009. if( pSrc==pDest ){
  96010. return 0; /* tab1 and tab2 may not be the same table */
  96011. }
  96012. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  96013. return 0; /* source and destination must both be WITHOUT ROWID or not */
  96014. }
  96015. #ifndef SQLITE_OMIT_VIRTUALTABLE
  96016. if( pSrc->tabFlags & TF_Virtual ){
  96017. return 0; /* tab2 must not be a virtual table */
  96018. }
  96019. #endif
  96020. if( pSrc->pSelect ){
  96021. return 0; /* tab2 may not be a view */
  96022. }
  96023. if( pDest->nCol!=pSrc->nCol ){
  96024. return 0; /* Number of columns must be the same in tab1 and tab2 */
  96025. }
  96026. if( pDest->iPKey!=pSrc->iPKey ){
  96027. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  96028. }
  96029. for(i=0; i<pDest->nCol; i++){
  96030. Column *pDestCol = &pDest->aCol[i];
  96031. Column *pSrcCol = &pSrc->aCol[i];
  96032. if( pDestCol->affinity!=pSrcCol->affinity ){
  96033. return 0; /* Affinity must be the same on all columns */
  96034. }
  96035. if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
  96036. return 0; /* Collating sequence must be the same on all columns */
  96037. }
  96038. if( pDestCol->notNull && !pSrcCol->notNull ){
  96039. return 0; /* tab2 must be NOT NULL if tab1 is */
  96040. }
  96041. /* Default values for second and subsequent columns need to match. */
  96042. if( i>0
  96043. && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
  96044. || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
  96045. ){
  96046. return 0; /* Default values must be the same for all columns */
  96047. }
  96048. }
  96049. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  96050. if( IsUniqueIndex(pDestIdx) ){
  96051. destHasUniqueIdx = 1;
  96052. }
  96053. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  96054. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  96055. }
  96056. if( pSrcIdx==0 ){
  96057. return 0; /* pDestIdx has no corresponding index in pSrc */
  96058. }
  96059. }
  96060. #ifndef SQLITE_OMIT_CHECK
  96061. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  96062. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  96063. }
  96064. #endif
  96065. #ifndef SQLITE_OMIT_FOREIGN_KEY
  96066. /* Disallow the transfer optimization if the destination table constains
  96067. ** any foreign key constraints. This is more restrictive than necessary.
  96068. ** But the main beneficiary of the transfer optimization is the VACUUM
  96069. ** command, and the VACUUM command disables foreign key constraints. So
  96070. ** the extra complication to make this rule less restrictive is probably
  96071. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  96072. */
  96073. if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  96074. return 0;
  96075. }
  96076. #endif
  96077. if( (db->flags & SQLITE_CountRows)!=0 ){
  96078. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  96079. }
  96080. /* If we get this far, it means that the xfer optimization is at
  96081. ** least a possibility, though it might only work if the destination
  96082. ** table (tab1) is initially empty.
  96083. */
  96084. #ifdef SQLITE_TEST
  96085. sqlite3_xferopt_count++;
  96086. #endif
  96087. iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
  96088. v = sqlite3GetVdbe(pParse);
  96089. sqlite3CodeVerifySchema(pParse, iDbSrc);
  96090. iSrc = pParse->nTab++;
  96091. iDest = pParse->nTab++;
  96092. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  96093. regData = sqlite3GetTempReg(pParse);
  96094. regRowid = sqlite3GetTempReg(pParse);
  96095. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  96096. assert( HasRowid(pDest) || destHasUniqueIdx );
  96097. if( (db->flags & SQLITE_Vacuum)==0 && (
  96098. (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  96099. || destHasUniqueIdx /* (2) */
  96100. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  96101. )){
  96102. /* In some circumstances, we are able to run the xfer optimization
  96103. ** only if the destination table is initially empty. Unless the
  96104. ** SQLITE_Vacuum flag is set, this block generates code to make
  96105. ** that determination. If SQLITE_Vacuum is set, then the destination
  96106. ** table is always empty.
  96107. **
  96108. ** Conditions under which the destination must be empty:
  96109. **
  96110. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  96111. ** (If the destination is not initially empty, the rowid fields
  96112. ** of index entries might need to change.)
  96113. **
  96114. ** (2) The destination has a unique index. (The xfer optimization
  96115. ** is unable to test uniqueness.)
  96116. **
  96117. ** (3) onError is something other than OE_Abort and OE_Rollback.
  96118. */
  96119. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  96120. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  96121. sqlite3VdbeJumpHere(v, addr1);
  96122. }
  96123. if( HasRowid(pSrc) ){
  96124. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  96125. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  96126. if( pDest->iPKey>=0 ){
  96127. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  96128. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  96129. VdbeCoverage(v);
  96130. sqlite3RowidConstraint(pParse, onError, pDest);
  96131. sqlite3VdbeJumpHere(v, addr2);
  96132. autoIncStep(pParse, regAutoinc, regRowid);
  96133. }else if( pDest->pIndex==0 ){
  96134. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  96135. }else{
  96136. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  96137. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  96138. }
  96139. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  96140. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  96141. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  96142. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  96143. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  96144. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  96145. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  96146. }else{
  96147. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  96148. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  96149. }
  96150. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  96151. u8 idxInsFlags = 0;
  96152. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  96153. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  96154. }
  96155. assert( pSrcIdx );
  96156. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  96157. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  96158. VdbeComment((v, "%s", pSrcIdx->zName));
  96159. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  96160. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  96161. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  96162. VdbeComment((v, "%s", pDestIdx->zName));
  96163. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  96164. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  96165. if( db->flags & SQLITE_Vacuum ){
  96166. /* This INSERT command is part of a VACUUM operation, which guarantees
  96167. ** that the destination table is empty. If all indexed columns use
  96168. ** collation sequence BINARY, then it can also be assumed that the
  96169. ** index will be populated by inserting keys in strictly sorted
  96170. ** order. In this case, instead of seeking within the b-tree as part
  96171. ** of every OP_IdxInsert opcode, an OP_Last is added before the
  96172. ** OP_IdxInsert to seek to the point within the b-tree where each key
  96173. ** should be inserted. This is faster.
  96174. **
  96175. ** If any of the indexed columns use a collation sequence other than
  96176. ** BINARY, this optimization is disabled. This is because the user
  96177. ** might change the definition of a collation sequence and then run
  96178. ** a VACUUM command. In that case keys may not be written in strictly
  96179. ** sorted order. */
  96180. for(i=0; i<pSrcIdx->nColumn; i++){
  96181. char *zColl = pSrcIdx->azColl[i];
  96182. assert( zColl!=0 );
  96183. if( sqlite3_stricmp("BINARY", zColl) ) break;
  96184. }
  96185. if( i==pSrcIdx->nColumn ){
  96186. idxInsFlags = OPFLAG_USESEEKRESULT;
  96187. sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
  96188. }
  96189. }
  96190. if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
  96191. idxInsFlags |= OPFLAG_NCHANGE;
  96192. }
  96193. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  96194. sqlite3VdbeChangeP5(v, idxInsFlags);
  96195. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  96196. sqlite3VdbeJumpHere(v, addr1);
  96197. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  96198. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  96199. }
  96200. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  96201. sqlite3ReleaseTempReg(pParse, regRowid);
  96202. sqlite3ReleaseTempReg(pParse, regData);
  96203. if( emptyDestTest ){
  96204. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  96205. sqlite3VdbeJumpHere(v, emptyDestTest);
  96206. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  96207. return 0;
  96208. }else{
  96209. return 1;
  96210. }
  96211. }
  96212. #endif /* SQLITE_OMIT_XFER_OPT */
  96213. /************** End of insert.c **********************************************/
  96214. /************** Begin file legacy.c ******************************************/
  96215. /*
  96216. ** 2001 September 15
  96217. **
  96218. ** The author disclaims copyright to this source code. In place of
  96219. ** a legal notice, here is a blessing:
  96220. **
  96221. ** May you do good and not evil.
  96222. ** May you find forgiveness for yourself and forgive others.
  96223. ** May you share freely, never taking more than you give.
  96224. **
  96225. *************************************************************************
  96226. ** Main file for the SQLite library. The routines in this file
  96227. ** implement the programmer interface to the library. Routines in
  96228. ** other files are for internal use by SQLite and should not be
  96229. ** accessed by users of the library.
  96230. */
  96231. /* #include "sqliteInt.h" */
  96232. /*
  96233. ** Execute SQL code. Return one of the SQLITE_ success/failure
  96234. ** codes. Also write an error message into memory obtained from
  96235. ** malloc() and make *pzErrMsg point to that message.
  96236. **
  96237. ** If the SQL is a query, then for each row in the query result
  96238. ** the xCallback() function is called. pArg becomes the first
  96239. ** argument to xCallback(). If xCallback=NULL then no callback
  96240. ** is invoked, even for queries.
  96241. */
  96242. SQLITE_API int SQLITE_STDCALL sqlite3_exec(
  96243. sqlite3 *db, /* The database on which the SQL executes */
  96244. const char *zSql, /* The SQL to be executed */
  96245. sqlite3_callback xCallback, /* Invoke this callback routine */
  96246. void *pArg, /* First argument to xCallback() */
  96247. char **pzErrMsg /* Write error messages here */
  96248. ){
  96249. int rc = SQLITE_OK; /* Return code */
  96250. const char *zLeftover; /* Tail of unprocessed SQL */
  96251. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  96252. char **azCols = 0; /* Names of result columns */
  96253. int callbackIsInit; /* True if callback data is initialized */
  96254. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  96255. if( zSql==0 ) zSql = "";
  96256. sqlite3_mutex_enter(db->mutex);
  96257. sqlite3Error(db, SQLITE_OK);
  96258. while( rc==SQLITE_OK && zSql[0] ){
  96259. int nCol;
  96260. char **azVals = 0;
  96261. pStmt = 0;
  96262. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  96263. assert( rc==SQLITE_OK || pStmt==0 );
  96264. if( rc!=SQLITE_OK ){
  96265. continue;
  96266. }
  96267. if( !pStmt ){
  96268. /* this happens for a comment or white-space */
  96269. zSql = zLeftover;
  96270. continue;
  96271. }
  96272. callbackIsInit = 0;
  96273. nCol = sqlite3_column_count(pStmt);
  96274. while( 1 ){
  96275. int i;
  96276. rc = sqlite3_step(pStmt);
  96277. /* Invoke the callback function if required */
  96278. if( xCallback && (SQLITE_ROW==rc ||
  96279. (SQLITE_DONE==rc && !callbackIsInit
  96280. && db->flags&SQLITE_NullCallback)) ){
  96281. if( !callbackIsInit ){
  96282. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  96283. if( azCols==0 ){
  96284. goto exec_out;
  96285. }
  96286. for(i=0; i<nCol; i++){
  96287. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  96288. /* sqlite3VdbeSetColName() installs column names as UTF8
  96289. ** strings so there is no way for sqlite3_column_name() to fail. */
  96290. assert( azCols[i]!=0 );
  96291. }
  96292. callbackIsInit = 1;
  96293. }
  96294. if( rc==SQLITE_ROW ){
  96295. azVals = &azCols[nCol];
  96296. for(i=0; i<nCol; i++){
  96297. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  96298. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  96299. db->mallocFailed = 1;
  96300. goto exec_out;
  96301. }
  96302. }
  96303. }
  96304. if( xCallback(pArg, nCol, azVals, azCols) ){
  96305. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  96306. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  96307. ** return SQLITE_ABORT. */
  96308. rc = SQLITE_ABORT;
  96309. sqlite3VdbeFinalize((Vdbe *)pStmt);
  96310. pStmt = 0;
  96311. sqlite3Error(db, SQLITE_ABORT);
  96312. goto exec_out;
  96313. }
  96314. }
  96315. if( rc!=SQLITE_ROW ){
  96316. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  96317. pStmt = 0;
  96318. zSql = zLeftover;
  96319. while( sqlite3Isspace(zSql[0]) ) zSql++;
  96320. break;
  96321. }
  96322. }
  96323. sqlite3DbFree(db, azCols);
  96324. azCols = 0;
  96325. }
  96326. exec_out:
  96327. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  96328. sqlite3DbFree(db, azCols);
  96329. rc = sqlite3ApiExit(db, rc);
  96330. if( rc!=SQLITE_OK && pzErrMsg ){
  96331. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  96332. *pzErrMsg = sqlite3Malloc(nErrMsg);
  96333. if( *pzErrMsg ){
  96334. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  96335. }else{
  96336. rc = SQLITE_NOMEM;
  96337. sqlite3Error(db, SQLITE_NOMEM);
  96338. }
  96339. }else if( pzErrMsg ){
  96340. *pzErrMsg = 0;
  96341. }
  96342. assert( (rc&db->errMask)==rc );
  96343. sqlite3_mutex_leave(db->mutex);
  96344. return rc;
  96345. }
  96346. /************** End of legacy.c **********************************************/
  96347. /************** Begin file loadext.c *****************************************/
  96348. /*
  96349. ** 2006 June 7
  96350. **
  96351. ** The author disclaims copyright to this source code. In place of
  96352. ** a legal notice, here is a blessing:
  96353. **
  96354. ** May you do good and not evil.
  96355. ** May you find forgiveness for yourself and forgive others.
  96356. ** May you share freely, never taking more than you give.
  96357. **
  96358. *************************************************************************
  96359. ** This file contains code used to dynamically load extensions into
  96360. ** the SQLite library.
  96361. */
  96362. #ifndef SQLITE_CORE
  96363. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  96364. #endif
  96365. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  96366. /************** Begin file sqlite3ext.h **************************************/
  96367. /*
  96368. ** 2006 June 7
  96369. **
  96370. ** The author disclaims copyright to this source code. In place of
  96371. ** a legal notice, here is a blessing:
  96372. **
  96373. ** May you do good and not evil.
  96374. ** May you find forgiveness for yourself and forgive others.
  96375. ** May you share freely, never taking more than you give.
  96376. **
  96377. *************************************************************************
  96378. ** This header file defines the SQLite interface for use by
  96379. ** shared libraries that want to be imported as extensions into
  96380. ** an SQLite instance. Shared libraries that intend to be loaded
  96381. ** as extensions by SQLite should #include this file instead of
  96382. ** sqlite3.h.
  96383. */
  96384. #ifndef _SQLITE3EXT_H_
  96385. #define _SQLITE3EXT_H_
  96386. /* #include "sqlite3.h" */
  96387. typedef struct sqlite3_api_routines sqlite3_api_routines;
  96388. /*
  96389. ** The following structure holds pointers to all of the SQLite API
  96390. ** routines.
  96391. **
  96392. ** WARNING: In order to maintain backwards compatibility, add new
  96393. ** interfaces to the end of this structure only. If you insert new
  96394. ** interfaces in the middle of this structure, then older different
  96395. ** versions of SQLite will not be able to load each other's shared
  96396. ** libraries!
  96397. */
  96398. struct sqlite3_api_routines {
  96399. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  96400. int (*aggregate_count)(sqlite3_context*);
  96401. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  96402. int (*bind_double)(sqlite3_stmt*,int,double);
  96403. int (*bind_int)(sqlite3_stmt*,int,int);
  96404. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  96405. int (*bind_null)(sqlite3_stmt*,int);
  96406. int (*bind_parameter_count)(sqlite3_stmt*);
  96407. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  96408. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  96409. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  96410. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  96411. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  96412. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  96413. int (*busy_timeout)(sqlite3*,int ms);
  96414. int (*changes)(sqlite3*);
  96415. int (*close)(sqlite3*);
  96416. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  96417. int eTextRep,const char*));
  96418. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  96419. int eTextRep,const void*));
  96420. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  96421. int (*column_bytes)(sqlite3_stmt*,int iCol);
  96422. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  96423. int (*column_count)(sqlite3_stmt*pStmt);
  96424. const char * (*column_database_name)(sqlite3_stmt*,int);
  96425. const void * (*column_database_name16)(sqlite3_stmt*,int);
  96426. const char * (*column_decltype)(sqlite3_stmt*,int i);
  96427. const void * (*column_decltype16)(sqlite3_stmt*,int);
  96428. double (*column_double)(sqlite3_stmt*,int iCol);
  96429. int (*column_int)(sqlite3_stmt*,int iCol);
  96430. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  96431. const char * (*column_name)(sqlite3_stmt*,int);
  96432. const void * (*column_name16)(sqlite3_stmt*,int);
  96433. const char * (*column_origin_name)(sqlite3_stmt*,int);
  96434. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  96435. const char * (*column_table_name)(sqlite3_stmt*,int);
  96436. const void * (*column_table_name16)(sqlite3_stmt*,int);
  96437. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  96438. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  96439. int (*column_type)(sqlite3_stmt*,int iCol);
  96440. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  96441. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  96442. int (*complete)(const char*sql);
  96443. int (*complete16)(const void*sql);
  96444. int (*create_collation)(sqlite3*,const char*,int,void*,
  96445. int(*)(void*,int,const void*,int,const void*));
  96446. int (*create_collation16)(sqlite3*,const void*,int,void*,
  96447. int(*)(void*,int,const void*,int,const void*));
  96448. int (*create_function)(sqlite3*,const char*,int,int,void*,
  96449. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  96450. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  96451. void (*xFinal)(sqlite3_context*));
  96452. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  96453. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  96454. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  96455. void (*xFinal)(sqlite3_context*));
  96456. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  96457. int (*data_count)(sqlite3_stmt*pStmt);
  96458. sqlite3 * (*db_handle)(sqlite3_stmt*);
  96459. int (*declare_vtab)(sqlite3*,const char*);
  96460. int (*enable_shared_cache)(int);
  96461. int (*errcode)(sqlite3*db);
  96462. const char * (*errmsg)(sqlite3*);
  96463. const void * (*errmsg16)(sqlite3*);
  96464. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  96465. int (*expired)(sqlite3_stmt*);
  96466. int (*finalize)(sqlite3_stmt*pStmt);
  96467. void (*free)(void*);
  96468. void (*free_table)(char**result);
  96469. int (*get_autocommit)(sqlite3*);
  96470. void * (*get_auxdata)(sqlite3_context*,int);
  96471. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  96472. int (*global_recover)(void);
  96473. void (*interruptx)(sqlite3*);
  96474. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  96475. const char * (*libversion)(void);
  96476. int (*libversion_number)(void);
  96477. void *(*malloc)(int);
  96478. char * (*mprintf)(const char*,...);
  96479. int (*open)(const char*,sqlite3**);
  96480. int (*open16)(const void*,sqlite3**);
  96481. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  96482. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  96483. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  96484. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  96485. void *(*realloc)(void*,int);
  96486. int (*reset)(sqlite3_stmt*pStmt);
  96487. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  96488. void (*result_double)(sqlite3_context*,double);
  96489. void (*result_error)(sqlite3_context*,const char*,int);
  96490. void (*result_error16)(sqlite3_context*,const void*,int);
  96491. void (*result_int)(sqlite3_context*,int);
  96492. void (*result_int64)(sqlite3_context*,sqlite_int64);
  96493. void (*result_null)(sqlite3_context*);
  96494. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  96495. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  96496. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  96497. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  96498. void (*result_value)(sqlite3_context*,sqlite3_value*);
  96499. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  96500. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  96501. const char*,const char*),void*);
  96502. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  96503. char * (*snprintf)(int,char*,const char*,...);
  96504. int (*step)(sqlite3_stmt*);
  96505. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  96506. char const**,char const**,int*,int*,int*);
  96507. void (*thread_cleanup)(void);
  96508. int (*total_changes)(sqlite3*);
  96509. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  96510. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  96511. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  96512. sqlite_int64),void*);
  96513. void * (*user_data)(sqlite3_context*);
  96514. const void * (*value_blob)(sqlite3_value*);
  96515. int (*value_bytes)(sqlite3_value*);
  96516. int (*value_bytes16)(sqlite3_value*);
  96517. double (*value_double)(sqlite3_value*);
  96518. int (*value_int)(sqlite3_value*);
  96519. sqlite_int64 (*value_int64)(sqlite3_value*);
  96520. int (*value_numeric_type)(sqlite3_value*);
  96521. const unsigned char * (*value_text)(sqlite3_value*);
  96522. const void * (*value_text16)(sqlite3_value*);
  96523. const void * (*value_text16be)(sqlite3_value*);
  96524. const void * (*value_text16le)(sqlite3_value*);
  96525. int (*value_type)(sqlite3_value*);
  96526. char *(*vmprintf)(const char*,va_list);
  96527. /* Added ??? */
  96528. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  96529. /* Added by 3.3.13 */
  96530. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  96531. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  96532. int (*clear_bindings)(sqlite3_stmt*);
  96533. /* Added by 3.4.1 */
  96534. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  96535. void (*xDestroy)(void *));
  96536. /* Added by 3.5.0 */
  96537. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  96538. int (*blob_bytes)(sqlite3_blob*);
  96539. int (*blob_close)(sqlite3_blob*);
  96540. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  96541. int,sqlite3_blob**);
  96542. int (*blob_read)(sqlite3_blob*,void*,int,int);
  96543. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  96544. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  96545. int(*)(void*,int,const void*,int,const void*),
  96546. void(*)(void*));
  96547. int (*file_control)(sqlite3*,const char*,int,void*);
  96548. sqlite3_int64 (*memory_highwater)(int);
  96549. sqlite3_int64 (*memory_used)(void);
  96550. sqlite3_mutex *(*mutex_alloc)(int);
  96551. void (*mutex_enter)(sqlite3_mutex*);
  96552. void (*mutex_free)(sqlite3_mutex*);
  96553. void (*mutex_leave)(sqlite3_mutex*);
  96554. int (*mutex_try)(sqlite3_mutex*);
  96555. int (*open_v2)(const char*,sqlite3**,int,const char*);
  96556. int (*release_memory)(int);
  96557. void (*result_error_nomem)(sqlite3_context*);
  96558. void (*result_error_toobig)(sqlite3_context*);
  96559. int (*sleep)(int);
  96560. void (*soft_heap_limit)(int);
  96561. sqlite3_vfs *(*vfs_find)(const char*);
  96562. int (*vfs_register)(sqlite3_vfs*,int);
  96563. int (*vfs_unregister)(sqlite3_vfs*);
  96564. int (*xthreadsafe)(void);
  96565. void (*result_zeroblob)(sqlite3_context*,int);
  96566. void (*result_error_code)(sqlite3_context*,int);
  96567. int (*test_control)(int, ...);
  96568. void (*randomness)(int,void*);
  96569. sqlite3 *(*context_db_handle)(sqlite3_context*);
  96570. int (*extended_result_codes)(sqlite3*,int);
  96571. int (*limit)(sqlite3*,int,int);
  96572. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  96573. const char *(*sql)(sqlite3_stmt*);
  96574. int (*status)(int,int*,int*,int);
  96575. int (*backup_finish)(sqlite3_backup*);
  96576. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  96577. int (*backup_pagecount)(sqlite3_backup*);
  96578. int (*backup_remaining)(sqlite3_backup*);
  96579. int (*backup_step)(sqlite3_backup*,int);
  96580. const char *(*compileoption_get)(int);
  96581. int (*compileoption_used)(const char*);
  96582. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  96583. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  96584. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  96585. void (*xFinal)(sqlite3_context*),
  96586. void(*xDestroy)(void*));
  96587. int (*db_config)(sqlite3*,int,...);
  96588. sqlite3_mutex *(*db_mutex)(sqlite3*);
  96589. int (*db_status)(sqlite3*,int,int*,int*,int);
  96590. int (*extended_errcode)(sqlite3*);
  96591. void (*log)(int,const char*,...);
  96592. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  96593. const char *(*sourceid)(void);
  96594. int (*stmt_status)(sqlite3_stmt*,int,int);
  96595. int (*strnicmp)(const char*,const char*,int);
  96596. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  96597. int (*wal_autocheckpoint)(sqlite3*,int);
  96598. int (*wal_checkpoint)(sqlite3*,const char*);
  96599. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  96600. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  96601. int (*vtab_config)(sqlite3*,int op,...);
  96602. int (*vtab_on_conflict)(sqlite3*);
  96603. /* Version 3.7.16 and later */
  96604. int (*close_v2)(sqlite3*);
  96605. const char *(*db_filename)(sqlite3*,const char*);
  96606. int (*db_readonly)(sqlite3*,const char*);
  96607. int (*db_release_memory)(sqlite3*);
  96608. const char *(*errstr)(int);
  96609. int (*stmt_busy)(sqlite3_stmt*);
  96610. int (*stmt_readonly)(sqlite3_stmt*);
  96611. int (*stricmp)(const char*,const char*);
  96612. int (*uri_boolean)(const char*,const char*,int);
  96613. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  96614. const char *(*uri_parameter)(const char*,const char*);
  96615. char *(*vsnprintf)(int,char*,const char*,va_list);
  96616. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  96617. /* Version 3.8.7 and later */
  96618. int (*auto_extension)(void(*)(void));
  96619. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  96620. void(*)(void*));
  96621. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  96622. void(*)(void*),unsigned char);
  96623. int (*cancel_auto_extension)(void(*)(void));
  96624. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  96625. void *(*malloc64)(sqlite3_uint64);
  96626. sqlite3_uint64 (*msize)(void*);
  96627. void *(*realloc64)(void*,sqlite3_uint64);
  96628. void (*reset_auto_extension)(void);
  96629. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  96630. void(*)(void*));
  96631. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  96632. void(*)(void*), unsigned char);
  96633. int (*strglob)(const char*,const char*);
  96634. /* Version 3.8.11 and later */
  96635. sqlite3_value *(*value_dup)(const sqlite3_value*);
  96636. void (*value_free)(sqlite3_value*);
  96637. int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
  96638. int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
  96639. };
  96640. /*
  96641. ** The following macros redefine the API routines so that they are
  96642. ** redirected through the global sqlite3_api structure.
  96643. **
  96644. ** This header file is also used by the loadext.c source file
  96645. ** (part of the main SQLite library - not an extension) so that
  96646. ** it can get access to the sqlite3_api_routines structure
  96647. ** definition. But the main library does not want to redefine
  96648. ** the API. So the redefinition macros are only valid if the
  96649. ** SQLITE_CORE macros is undefined.
  96650. */
  96651. #ifndef SQLITE_CORE
  96652. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  96653. #ifndef SQLITE_OMIT_DEPRECATED
  96654. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  96655. #endif
  96656. #define sqlite3_bind_blob sqlite3_api->bind_blob
  96657. #define sqlite3_bind_double sqlite3_api->bind_double
  96658. #define sqlite3_bind_int sqlite3_api->bind_int
  96659. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  96660. #define sqlite3_bind_null sqlite3_api->bind_null
  96661. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  96662. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  96663. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  96664. #define sqlite3_bind_text sqlite3_api->bind_text
  96665. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  96666. #define sqlite3_bind_value sqlite3_api->bind_value
  96667. #define sqlite3_busy_handler sqlite3_api->busy_handler
  96668. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  96669. #define sqlite3_changes sqlite3_api->changes
  96670. #define sqlite3_close sqlite3_api->close
  96671. #define sqlite3_collation_needed sqlite3_api->collation_needed
  96672. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  96673. #define sqlite3_column_blob sqlite3_api->column_blob
  96674. #define sqlite3_column_bytes sqlite3_api->column_bytes
  96675. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  96676. #define sqlite3_column_count sqlite3_api->column_count
  96677. #define sqlite3_column_database_name sqlite3_api->column_database_name
  96678. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  96679. #define sqlite3_column_decltype sqlite3_api->column_decltype
  96680. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  96681. #define sqlite3_column_double sqlite3_api->column_double
  96682. #define sqlite3_column_int sqlite3_api->column_int
  96683. #define sqlite3_column_int64 sqlite3_api->column_int64
  96684. #define sqlite3_column_name sqlite3_api->column_name
  96685. #define sqlite3_column_name16 sqlite3_api->column_name16
  96686. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  96687. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  96688. #define sqlite3_column_table_name sqlite3_api->column_table_name
  96689. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  96690. #define sqlite3_column_text sqlite3_api->column_text
  96691. #define sqlite3_column_text16 sqlite3_api->column_text16
  96692. #define sqlite3_column_type sqlite3_api->column_type
  96693. #define sqlite3_column_value sqlite3_api->column_value
  96694. #define sqlite3_commit_hook sqlite3_api->commit_hook
  96695. #define sqlite3_complete sqlite3_api->complete
  96696. #define sqlite3_complete16 sqlite3_api->complete16
  96697. #define sqlite3_create_collation sqlite3_api->create_collation
  96698. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  96699. #define sqlite3_create_function sqlite3_api->create_function
  96700. #define sqlite3_create_function16 sqlite3_api->create_function16
  96701. #define sqlite3_create_module sqlite3_api->create_module
  96702. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  96703. #define sqlite3_data_count sqlite3_api->data_count
  96704. #define sqlite3_db_handle sqlite3_api->db_handle
  96705. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  96706. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  96707. #define sqlite3_errcode sqlite3_api->errcode
  96708. #define sqlite3_errmsg sqlite3_api->errmsg
  96709. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  96710. #define sqlite3_exec sqlite3_api->exec
  96711. #ifndef SQLITE_OMIT_DEPRECATED
  96712. #define sqlite3_expired sqlite3_api->expired
  96713. #endif
  96714. #define sqlite3_finalize sqlite3_api->finalize
  96715. #define sqlite3_free sqlite3_api->free
  96716. #define sqlite3_free_table sqlite3_api->free_table
  96717. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  96718. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  96719. #define sqlite3_get_table sqlite3_api->get_table
  96720. #ifndef SQLITE_OMIT_DEPRECATED
  96721. #define sqlite3_global_recover sqlite3_api->global_recover
  96722. #endif
  96723. #define sqlite3_interrupt sqlite3_api->interruptx
  96724. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  96725. #define sqlite3_libversion sqlite3_api->libversion
  96726. #define sqlite3_libversion_number sqlite3_api->libversion_number
  96727. #define sqlite3_malloc sqlite3_api->malloc
  96728. #define sqlite3_mprintf sqlite3_api->mprintf
  96729. #define sqlite3_open sqlite3_api->open
  96730. #define sqlite3_open16 sqlite3_api->open16
  96731. #define sqlite3_prepare sqlite3_api->prepare
  96732. #define sqlite3_prepare16 sqlite3_api->prepare16
  96733. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  96734. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  96735. #define sqlite3_profile sqlite3_api->profile
  96736. #define sqlite3_progress_handler sqlite3_api->progress_handler
  96737. #define sqlite3_realloc sqlite3_api->realloc
  96738. #define sqlite3_reset sqlite3_api->reset
  96739. #define sqlite3_result_blob sqlite3_api->result_blob
  96740. #define sqlite3_result_double sqlite3_api->result_double
  96741. #define sqlite3_result_error sqlite3_api->result_error
  96742. #define sqlite3_result_error16 sqlite3_api->result_error16
  96743. #define sqlite3_result_int sqlite3_api->result_int
  96744. #define sqlite3_result_int64 sqlite3_api->result_int64
  96745. #define sqlite3_result_null sqlite3_api->result_null
  96746. #define sqlite3_result_text sqlite3_api->result_text
  96747. #define sqlite3_result_text16 sqlite3_api->result_text16
  96748. #define sqlite3_result_text16be sqlite3_api->result_text16be
  96749. #define sqlite3_result_text16le sqlite3_api->result_text16le
  96750. #define sqlite3_result_value sqlite3_api->result_value
  96751. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  96752. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  96753. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  96754. #define sqlite3_snprintf sqlite3_api->snprintf
  96755. #define sqlite3_step sqlite3_api->step
  96756. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  96757. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  96758. #define sqlite3_total_changes sqlite3_api->total_changes
  96759. #define sqlite3_trace sqlite3_api->trace
  96760. #ifndef SQLITE_OMIT_DEPRECATED
  96761. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  96762. #endif
  96763. #define sqlite3_update_hook sqlite3_api->update_hook
  96764. #define sqlite3_user_data sqlite3_api->user_data
  96765. #define sqlite3_value_blob sqlite3_api->value_blob
  96766. #define sqlite3_value_bytes sqlite3_api->value_bytes
  96767. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  96768. #define sqlite3_value_double sqlite3_api->value_double
  96769. #define sqlite3_value_int sqlite3_api->value_int
  96770. #define sqlite3_value_int64 sqlite3_api->value_int64
  96771. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  96772. #define sqlite3_value_text sqlite3_api->value_text
  96773. #define sqlite3_value_text16 sqlite3_api->value_text16
  96774. #define sqlite3_value_text16be sqlite3_api->value_text16be
  96775. #define sqlite3_value_text16le sqlite3_api->value_text16le
  96776. #define sqlite3_value_type sqlite3_api->value_type
  96777. #define sqlite3_vmprintf sqlite3_api->vmprintf
  96778. #define sqlite3_overload_function sqlite3_api->overload_function
  96779. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  96780. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  96781. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  96782. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  96783. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  96784. #define sqlite3_blob_close sqlite3_api->blob_close
  96785. #define sqlite3_blob_open sqlite3_api->blob_open
  96786. #define sqlite3_blob_read sqlite3_api->blob_read
  96787. #define sqlite3_blob_write sqlite3_api->blob_write
  96788. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  96789. #define sqlite3_file_control sqlite3_api->file_control
  96790. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  96791. #define sqlite3_memory_used sqlite3_api->memory_used
  96792. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  96793. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  96794. #define sqlite3_mutex_free sqlite3_api->mutex_free
  96795. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  96796. #define sqlite3_mutex_try sqlite3_api->mutex_try
  96797. #define sqlite3_open_v2 sqlite3_api->open_v2
  96798. #define sqlite3_release_memory sqlite3_api->release_memory
  96799. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  96800. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  96801. #define sqlite3_sleep sqlite3_api->sleep
  96802. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  96803. #define sqlite3_vfs_find sqlite3_api->vfs_find
  96804. #define sqlite3_vfs_register sqlite3_api->vfs_register
  96805. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  96806. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  96807. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  96808. #define sqlite3_result_error_code sqlite3_api->result_error_code
  96809. #define sqlite3_test_control sqlite3_api->test_control
  96810. #define sqlite3_randomness sqlite3_api->randomness
  96811. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  96812. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  96813. #define sqlite3_limit sqlite3_api->limit
  96814. #define sqlite3_next_stmt sqlite3_api->next_stmt
  96815. #define sqlite3_sql sqlite3_api->sql
  96816. #define sqlite3_status sqlite3_api->status
  96817. #define sqlite3_backup_finish sqlite3_api->backup_finish
  96818. #define sqlite3_backup_init sqlite3_api->backup_init
  96819. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  96820. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  96821. #define sqlite3_backup_step sqlite3_api->backup_step
  96822. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  96823. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  96824. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  96825. #define sqlite3_db_config sqlite3_api->db_config
  96826. #define sqlite3_db_mutex sqlite3_api->db_mutex
  96827. #define sqlite3_db_status sqlite3_api->db_status
  96828. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  96829. #define sqlite3_log sqlite3_api->log
  96830. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  96831. #define sqlite3_sourceid sqlite3_api->sourceid
  96832. #define sqlite3_stmt_status sqlite3_api->stmt_status
  96833. #define sqlite3_strnicmp sqlite3_api->strnicmp
  96834. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  96835. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  96836. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  96837. #define sqlite3_wal_hook sqlite3_api->wal_hook
  96838. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  96839. #define sqlite3_vtab_config sqlite3_api->vtab_config
  96840. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  96841. /* Version 3.7.16 and later */
  96842. #define sqlite3_close_v2 sqlite3_api->close_v2
  96843. #define sqlite3_db_filename sqlite3_api->db_filename
  96844. #define sqlite3_db_readonly sqlite3_api->db_readonly
  96845. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  96846. #define sqlite3_errstr sqlite3_api->errstr
  96847. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  96848. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  96849. #define sqlite3_stricmp sqlite3_api->stricmp
  96850. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  96851. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  96852. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  96853. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  96854. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  96855. /* Version 3.8.7 and later */
  96856. #define sqlite3_auto_extension sqlite3_api->auto_extension
  96857. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  96858. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  96859. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  96860. #define sqlite3_load_extension sqlite3_api->load_extension
  96861. #define sqlite3_malloc64 sqlite3_api->malloc64
  96862. #define sqlite3_msize sqlite3_api->msize
  96863. #define sqlite3_realloc64 sqlite3_api->realloc64
  96864. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  96865. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  96866. #define sqlite3_result_text64 sqlite3_api->result_text64
  96867. #define sqlite3_strglob sqlite3_api->strglob
  96868. /* Version 3.8.11 and later */
  96869. #define sqlite3_value_dup sqlite3_api->value_dup
  96870. #define sqlite3_value_free sqlite3_api->value_free
  96871. #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
  96872. #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
  96873. #endif /* SQLITE_CORE */
  96874. #ifndef SQLITE_CORE
  96875. /* This case when the file really is being compiled as a loadable
  96876. ** extension */
  96877. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  96878. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  96879. # define SQLITE_EXTENSION_INIT3 \
  96880. extern const sqlite3_api_routines *sqlite3_api;
  96881. #else
  96882. /* This case when the file is being statically linked into the
  96883. ** application */
  96884. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  96885. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  96886. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  96887. #endif
  96888. #endif /* _SQLITE3EXT_H_ */
  96889. /************** End of sqlite3ext.h ******************************************/
  96890. /************** Continuing where we left off in loadext.c ********************/
  96891. /* #include "sqliteInt.h" */
  96892. /* #include <string.h> */
  96893. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  96894. /*
  96895. ** Some API routines are omitted when various features are
  96896. ** excluded from a build of SQLite. Substitute a NULL pointer
  96897. ** for any missing APIs.
  96898. */
  96899. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  96900. # define sqlite3_column_database_name 0
  96901. # define sqlite3_column_database_name16 0
  96902. # define sqlite3_column_table_name 0
  96903. # define sqlite3_column_table_name16 0
  96904. # define sqlite3_column_origin_name 0
  96905. # define sqlite3_column_origin_name16 0
  96906. #endif
  96907. #ifdef SQLITE_OMIT_AUTHORIZATION
  96908. # define sqlite3_set_authorizer 0
  96909. #endif
  96910. #ifdef SQLITE_OMIT_UTF16
  96911. # define sqlite3_bind_text16 0
  96912. # define sqlite3_collation_needed16 0
  96913. # define sqlite3_column_decltype16 0
  96914. # define sqlite3_column_name16 0
  96915. # define sqlite3_column_text16 0
  96916. # define sqlite3_complete16 0
  96917. # define sqlite3_create_collation16 0
  96918. # define sqlite3_create_function16 0
  96919. # define sqlite3_errmsg16 0
  96920. # define sqlite3_open16 0
  96921. # define sqlite3_prepare16 0
  96922. # define sqlite3_prepare16_v2 0
  96923. # define sqlite3_result_error16 0
  96924. # define sqlite3_result_text16 0
  96925. # define sqlite3_result_text16be 0
  96926. # define sqlite3_result_text16le 0
  96927. # define sqlite3_value_text16 0
  96928. # define sqlite3_value_text16be 0
  96929. # define sqlite3_value_text16le 0
  96930. # define sqlite3_column_database_name16 0
  96931. # define sqlite3_column_table_name16 0
  96932. # define sqlite3_column_origin_name16 0
  96933. #endif
  96934. #ifdef SQLITE_OMIT_COMPLETE
  96935. # define sqlite3_complete 0
  96936. # define sqlite3_complete16 0
  96937. #endif
  96938. #ifdef SQLITE_OMIT_DECLTYPE
  96939. # define sqlite3_column_decltype16 0
  96940. # define sqlite3_column_decltype 0
  96941. #endif
  96942. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  96943. # define sqlite3_progress_handler 0
  96944. #endif
  96945. #ifdef SQLITE_OMIT_VIRTUALTABLE
  96946. # define sqlite3_create_module 0
  96947. # define sqlite3_create_module_v2 0
  96948. # define sqlite3_declare_vtab 0
  96949. # define sqlite3_vtab_config 0
  96950. # define sqlite3_vtab_on_conflict 0
  96951. #endif
  96952. #ifdef SQLITE_OMIT_SHARED_CACHE
  96953. # define sqlite3_enable_shared_cache 0
  96954. #endif
  96955. #ifdef SQLITE_OMIT_TRACE
  96956. # define sqlite3_profile 0
  96957. # define sqlite3_trace 0
  96958. #endif
  96959. #ifdef SQLITE_OMIT_GET_TABLE
  96960. # define sqlite3_free_table 0
  96961. # define sqlite3_get_table 0
  96962. #endif
  96963. #ifdef SQLITE_OMIT_INCRBLOB
  96964. #define sqlite3_bind_zeroblob 0
  96965. #define sqlite3_blob_bytes 0
  96966. #define sqlite3_blob_close 0
  96967. #define sqlite3_blob_open 0
  96968. #define sqlite3_blob_read 0
  96969. #define sqlite3_blob_write 0
  96970. #define sqlite3_blob_reopen 0
  96971. #endif
  96972. /*
  96973. ** The following structure contains pointers to all SQLite API routines.
  96974. ** A pointer to this structure is passed into extensions when they are
  96975. ** loaded so that the extension can make calls back into the SQLite
  96976. ** library.
  96977. **
  96978. ** When adding new APIs, add them to the bottom of this structure
  96979. ** in order to preserve backwards compatibility.
  96980. **
  96981. ** Extensions that use newer APIs should first call the
  96982. ** sqlite3_libversion_number() to make sure that the API they
  96983. ** intend to use is supported by the library. Extensions should
  96984. ** also check to make sure that the pointer to the function is
  96985. ** not NULL before calling it.
  96986. */
  96987. static const sqlite3_api_routines sqlite3Apis = {
  96988. sqlite3_aggregate_context,
  96989. #ifndef SQLITE_OMIT_DEPRECATED
  96990. sqlite3_aggregate_count,
  96991. #else
  96992. 0,
  96993. #endif
  96994. sqlite3_bind_blob,
  96995. sqlite3_bind_double,
  96996. sqlite3_bind_int,
  96997. sqlite3_bind_int64,
  96998. sqlite3_bind_null,
  96999. sqlite3_bind_parameter_count,
  97000. sqlite3_bind_parameter_index,
  97001. sqlite3_bind_parameter_name,
  97002. sqlite3_bind_text,
  97003. sqlite3_bind_text16,
  97004. sqlite3_bind_value,
  97005. sqlite3_busy_handler,
  97006. sqlite3_busy_timeout,
  97007. sqlite3_changes,
  97008. sqlite3_close,
  97009. sqlite3_collation_needed,
  97010. sqlite3_collation_needed16,
  97011. sqlite3_column_blob,
  97012. sqlite3_column_bytes,
  97013. sqlite3_column_bytes16,
  97014. sqlite3_column_count,
  97015. sqlite3_column_database_name,
  97016. sqlite3_column_database_name16,
  97017. sqlite3_column_decltype,
  97018. sqlite3_column_decltype16,
  97019. sqlite3_column_double,
  97020. sqlite3_column_int,
  97021. sqlite3_column_int64,
  97022. sqlite3_column_name,
  97023. sqlite3_column_name16,
  97024. sqlite3_column_origin_name,
  97025. sqlite3_column_origin_name16,
  97026. sqlite3_column_table_name,
  97027. sqlite3_column_table_name16,
  97028. sqlite3_column_text,
  97029. sqlite3_column_text16,
  97030. sqlite3_column_type,
  97031. sqlite3_column_value,
  97032. sqlite3_commit_hook,
  97033. sqlite3_complete,
  97034. sqlite3_complete16,
  97035. sqlite3_create_collation,
  97036. sqlite3_create_collation16,
  97037. sqlite3_create_function,
  97038. sqlite3_create_function16,
  97039. sqlite3_create_module,
  97040. sqlite3_data_count,
  97041. sqlite3_db_handle,
  97042. sqlite3_declare_vtab,
  97043. sqlite3_enable_shared_cache,
  97044. sqlite3_errcode,
  97045. sqlite3_errmsg,
  97046. sqlite3_errmsg16,
  97047. sqlite3_exec,
  97048. #ifndef SQLITE_OMIT_DEPRECATED
  97049. sqlite3_expired,
  97050. #else
  97051. 0,
  97052. #endif
  97053. sqlite3_finalize,
  97054. sqlite3_free,
  97055. sqlite3_free_table,
  97056. sqlite3_get_autocommit,
  97057. sqlite3_get_auxdata,
  97058. sqlite3_get_table,
  97059. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  97060. sqlite3_interrupt,
  97061. sqlite3_last_insert_rowid,
  97062. sqlite3_libversion,
  97063. sqlite3_libversion_number,
  97064. sqlite3_malloc,
  97065. sqlite3_mprintf,
  97066. sqlite3_open,
  97067. sqlite3_open16,
  97068. sqlite3_prepare,
  97069. sqlite3_prepare16,
  97070. sqlite3_profile,
  97071. sqlite3_progress_handler,
  97072. sqlite3_realloc,
  97073. sqlite3_reset,
  97074. sqlite3_result_blob,
  97075. sqlite3_result_double,
  97076. sqlite3_result_error,
  97077. sqlite3_result_error16,
  97078. sqlite3_result_int,
  97079. sqlite3_result_int64,
  97080. sqlite3_result_null,
  97081. sqlite3_result_text,
  97082. sqlite3_result_text16,
  97083. sqlite3_result_text16be,
  97084. sqlite3_result_text16le,
  97085. sqlite3_result_value,
  97086. sqlite3_rollback_hook,
  97087. sqlite3_set_authorizer,
  97088. sqlite3_set_auxdata,
  97089. sqlite3_snprintf,
  97090. sqlite3_step,
  97091. sqlite3_table_column_metadata,
  97092. #ifndef SQLITE_OMIT_DEPRECATED
  97093. sqlite3_thread_cleanup,
  97094. #else
  97095. 0,
  97096. #endif
  97097. sqlite3_total_changes,
  97098. sqlite3_trace,
  97099. #ifndef SQLITE_OMIT_DEPRECATED
  97100. sqlite3_transfer_bindings,
  97101. #else
  97102. 0,
  97103. #endif
  97104. sqlite3_update_hook,
  97105. sqlite3_user_data,
  97106. sqlite3_value_blob,
  97107. sqlite3_value_bytes,
  97108. sqlite3_value_bytes16,
  97109. sqlite3_value_double,
  97110. sqlite3_value_int,
  97111. sqlite3_value_int64,
  97112. sqlite3_value_numeric_type,
  97113. sqlite3_value_text,
  97114. sqlite3_value_text16,
  97115. sqlite3_value_text16be,
  97116. sqlite3_value_text16le,
  97117. sqlite3_value_type,
  97118. sqlite3_vmprintf,
  97119. /*
  97120. ** The original API set ends here. All extensions can call any
  97121. ** of the APIs above provided that the pointer is not NULL. But
  97122. ** before calling APIs that follow, extension should check the
  97123. ** sqlite3_libversion_number() to make sure they are dealing with
  97124. ** a library that is new enough to support that API.
  97125. *************************************************************************
  97126. */
  97127. sqlite3_overload_function,
  97128. /*
  97129. ** Added after 3.3.13
  97130. */
  97131. sqlite3_prepare_v2,
  97132. sqlite3_prepare16_v2,
  97133. sqlite3_clear_bindings,
  97134. /*
  97135. ** Added for 3.4.1
  97136. */
  97137. sqlite3_create_module_v2,
  97138. /*
  97139. ** Added for 3.5.0
  97140. */
  97141. sqlite3_bind_zeroblob,
  97142. sqlite3_blob_bytes,
  97143. sqlite3_blob_close,
  97144. sqlite3_blob_open,
  97145. sqlite3_blob_read,
  97146. sqlite3_blob_write,
  97147. sqlite3_create_collation_v2,
  97148. sqlite3_file_control,
  97149. sqlite3_memory_highwater,
  97150. sqlite3_memory_used,
  97151. #ifdef SQLITE_MUTEX_OMIT
  97152. 0,
  97153. 0,
  97154. 0,
  97155. 0,
  97156. 0,
  97157. #else
  97158. sqlite3_mutex_alloc,
  97159. sqlite3_mutex_enter,
  97160. sqlite3_mutex_free,
  97161. sqlite3_mutex_leave,
  97162. sqlite3_mutex_try,
  97163. #endif
  97164. sqlite3_open_v2,
  97165. sqlite3_release_memory,
  97166. sqlite3_result_error_nomem,
  97167. sqlite3_result_error_toobig,
  97168. sqlite3_sleep,
  97169. sqlite3_soft_heap_limit,
  97170. sqlite3_vfs_find,
  97171. sqlite3_vfs_register,
  97172. sqlite3_vfs_unregister,
  97173. /*
  97174. ** Added for 3.5.8
  97175. */
  97176. sqlite3_threadsafe,
  97177. sqlite3_result_zeroblob,
  97178. sqlite3_result_error_code,
  97179. sqlite3_test_control,
  97180. sqlite3_randomness,
  97181. sqlite3_context_db_handle,
  97182. /*
  97183. ** Added for 3.6.0
  97184. */
  97185. sqlite3_extended_result_codes,
  97186. sqlite3_limit,
  97187. sqlite3_next_stmt,
  97188. sqlite3_sql,
  97189. sqlite3_status,
  97190. /*
  97191. ** Added for 3.7.4
  97192. */
  97193. sqlite3_backup_finish,
  97194. sqlite3_backup_init,
  97195. sqlite3_backup_pagecount,
  97196. sqlite3_backup_remaining,
  97197. sqlite3_backup_step,
  97198. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  97199. sqlite3_compileoption_get,
  97200. sqlite3_compileoption_used,
  97201. #else
  97202. 0,
  97203. 0,
  97204. #endif
  97205. sqlite3_create_function_v2,
  97206. sqlite3_db_config,
  97207. sqlite3_db_mutex,
  97208. sqlite3_db_status,
  97209. sqlite3_extended_errcode,
  97210. sqlite3_log,
  97211. sqlite3_soft_heap_limit64,
  97212. sqlite3_sourceid,
  97213. sqlite3_stmt_status,
  97214. sqlite3_strnicmp,
  97215. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  97216. sqlite3_unlock_notify,
  97217. #else
  97218. 0,
  97219. #endif
  97220. #ifndef SQLITE_OMIT_WAL
  97221. sqlite3_wal_autocheckpoint,
  97222. sqlite3_wal_checkpoint,
  97223. sqlite3_wal_hook,
  97224. #else
  97225. 0,
  97226. 0,
  97227. 0,
  97228. #endif
  97229. sqlite3_blob_reopen,
  97230. sqlite3_vtab_config,
  97231. sqlite3_vtab_on_conflict,
  97232. sqlite3_close_v2,
  97233. sqlite3_db_filename,
  97234. sqlite3_db_readonly,
  97235. sqlite3_db_release_memory,
  97236. sqlite3_errstr,
  97237. sqlite3_stmt_busy,
  97238. sqlite3_stmt_readonly,
  97239. sqlite3_stricmp,
  97240. sqlite3_uri_boolean,
  97241. sqlite3_uri_int64,
  97242. sqlite3_uri_parameter,
  97243. sqlite3_vsnprintf,
  97244. sqlite3_wal_checkpoint_v2,
  97245. /* Version 3.8.7 and later */
  97246. sqlite3_auto_extension,
  97247. sqlite3_bind_blob64,
  97248. sqlite3_bind_text64,
  97249. sqlite3_cancel_auto_extension,
  97250. sqlite3_load_extension,
  97251. sqlite3_malloc64,
  97252. sqlite3_msize,
  97253. sqlite3_realloc64,
  97254. sqlite3_reset_auto_extension,
  97255. sqlite3_result_blob64,
  97256. sqlite3_result_text64,
  97257. sqlite3_strglob,
  97258. /* Version 3.8.11 and later */
  97259. (sqlite3_value*(*)(const sqlite3_value*))sqlite3_value_dup,
  97260. sqlite3_value_free,
  97261. sqlite3_result_zeroblob64,
  97262. sqlite3_bind_zeroblob64
  97263. };
  97264. /*
  97265. ** Attempt to load an SQLite extension library contained in the file
  97266. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  97267. ** default entry point name (sqlite3_extension_init) is used. Use
  97268. ** of the default name is recommended.
  97269. **
  97270. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  97271. **
  97272. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  97273. ** error message text. The calling function should free this memory
  97274. ** by calling sqlite3DbFree(db, ).
  97275. */
  97276. static int sqlite3LoadExtension(
  97277. sqlite3 *db, /* Load the extension into this database connection */
  97278. const char *zFile, /* Name of the shared library containing extension */
  97279. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  97280. char **pzErrMsg /* Put error message here if not 0 */
  97281. ){
  97282. sqlite3_vfs *pVfs = db->pVfs;
  97283. void *handle;
  97284. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  97285. char *zErrmsg = 0;
  97286. const char *zEntry;
  97287. char *zAltEntry = 0;
  97288. void **aHandle;
  97289. u64 nMsg = 300 + sqlite3Strlen30(zFile);
  97290. int ii;
  97291. /* Shared library endings to try if zFile cannot be loaded as written */
  97292. static const char *azEndings[] = {
  97293. #if SQLITE_OS_WIN
  97294. "dll"
  97295. #elif defined(__APPLE__)
  97296. "dylib"
  97297. #else
  97298. "so"
  97299. #endif
  97300. };
  97301. if( pzErrMsg ) *pzErrMsg = 0;
  97302. /* Ticket #1863. To avoid a creating security problems for older
  97303. ** applications that relink against newer versions of SQLite, the
  97304. ** ability to run load_extension is turned off by default. One
  97305. ** must call sqlite3_enable_load_extension() to turn on extension
  97306. ** loading. Otherwise you get the following error.
  97307. */
  97308. if( (db->flags & SQLITE_LoadExtension)==0 ){
  97309. if( pzErrMsg ){
  97310. *pzErrMsg = sqlite3_mprintf("not authorized");
  97311. }
  97312. return SQLITE_ERROR;
  97313. }
  97314. zEntry = zProc ? zProc : "sqlite3_extension_init";
  97315. handle = sqlite3OsDlOpen(pVfs, zFile);
  97316. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  97317. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  97318. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  97319. if( zAltFile==0 ) return SQLITE_NOMEM;
  97320. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  97321. sqlite3_free(zAltFile);
  97322. }
  97323. #endif
  97324. if( handle==0 ){
  97325. if( pzErrMsg ){
  97326. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  97327. if( zErrmsg ){
  97328. sqlite3_snprintf(nMsg, zErrmsg,
  97329. "unable to open shared library [%s]", zFile);
  97330. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  97331. }
  97332. }
  97333. return SQLITE_ERROR;
  97334. }
  97335. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  97336. sqlite3OsDlSym(pVfs, handle, zEntry);
  97337. /* If no entry point was specified and the default legacy
  97338. ** entry point name "sqlite3_extension_init" was not found, then
  97339. ** construct an entry point name "sqlite3_X_init" where the X is
  97340. ** replaced by the lowercase value of every ASCII alphabetic
  97341. ** character in the filename after the last "/" upto the first ".",
  97342. ** and eliding the first three characters if they are "lib".
  97343. ** Examples:
  97344. **
  97345. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  97346. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  97347. */
  97348. if( xInit==0 && zProc==0 ){
  97349. int iFile, iEntry, c;
  97350. int ncFile = sqlite3Strlen30(zFile);
  97351. zAltEntry = sqlite3_malloc64(ncFile+30);
  97352. if( zAltEntry==0 ){
  97353. sqlite3OsDlClose(pVfs, handle);
  97354. return SQLITE_NOMEM;
  97355. }
  97356. memcpy(zAltEntry, "sqlite3_", 8);
  97357. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  97358. iFile++;
  97359. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  97360. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  97361. if( sqlite3Isalpha(c) ){
  97362. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  97363. }
  97364. }
  97365. memcpy(zAltEntry+iEntry, "_init", 6);
  97366. zEntry = zAltEntry;
  97367. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  97368. sqlite3OsDlSym(pVfs, handle, zEntry);
  97369. }
  97370. if( xInit==0 ){
  97371. if( pzErrMsg ){
  97372. nMsg += sqlite3Strlen30(zEntry);
  97373. *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
  97374. if( zErrmsg ){
  97375. sqlite3_snprintf(nMsg, zErrmsg,
  97376. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  97377. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  97378. }
  97379. }
  97380. sqlite3OsDlClose(pVfs, handle);
  97381. sqlite3_free(zAltEntry);
  97382. return SQLITE_ERROR;
  97383. }
  97384. sqlite3_free(zAltEntry);
  97385. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  97386. if( pzErrMsg ){
  97387. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  97388. }
  97389. sqlite3_free(zErrmsg);
  97390. sqlite3OsDlClose(pVfs, handle);
  97391. return SQLITE_ERROR;
  97392. }
  97393. /* Append the new shared library handle to the db->aExtension array. */
  97394. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  97395. if( aHandle==0 ){
  97396. return SQLITE_NOMEM;
  97397. }
  97398. if( db->nExtension>0 ){
  97399. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  97400. }
  97401. sqlite3DbFree(db, db->aExtension);
  97402. db->aExtension = aHandle;
  97403. db->aExtension[db->nExtension++] = handle;
  97404. return SQLITE_OK;
  97405. }
  97406. SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
  97407. sqlite3 *db, /* Load the extension into this database connection */
  97408. const char *zFile, /* Name of the shared library containing extension */
  97409. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  97410. char **pzErrMsg /* Put error message here if not 0 */
  97411. ){
  97412. int rc;
  97413. sqlite3_mutex_enter(db->mutex);
  97414. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  97415. rc = sqlite3ApiExit(db, rc);
  97416. sqlite3_mutex_leave(db->mutex);
  97417. return rc;
  97418. }
  97419. /*
  97420. ** Call this routine when the database connection is closing in order
  97421. ** to clean up loaded extensions
  97422. */
  97423. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  97424. int i;
  97425. assert( sqlite3_mutex_held(db->mutex) );
  97426. for(i=0; i<db->nExtension; i++){
  97427. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  97428. }
  97429. sqlite3DbFree(db, db->aExtension);
  97430. }
  97431. /*
  97432. ** Enable or disable extension loading. Extension loading is disabled by
  97433. ** default so as not to open security holes in older applications.
  97434. */
  97435. SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  97436. sqlite3_mutex_enter(db->mutex);
  97437. if( onoff ){
  97438. db->flags |= SQLITE_LoadExtension;
  97439. }else{
  97440. db->flags &= ~SQLITE_LoadExtension;
  97441. }
  97442. sqlite3_mutex_leave(db->mutex);
  97443. return SQLITE_OK;
  97444. }
  97445. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  97446. /*
  97447. ** The auto-extension code added regardless of whether or not extension
  97448. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  97449. ** code if regular extension loading is not available. This is that
  97450. ** dummy pointer.
  97451. */
  97452. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  97453. static const sqlite3_api_routines sqlite3Apis = { 0 };
  97454. #endif
  97455. /*
  97456. ** The following object holds the list of automatically loaded
  97457. ** extensions.
  97458. **
  97459. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  97460. ** mutex must be held while accessing this list.
  97461. */
  97462. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  97463. static SQLITE_WSD struct sqlite3AutoExtList {
  97464. u32 nExt; /* Number of entries in aExt[] */
  97465. void (**aExt)(void); /* Pointers to the extension init functions */
  97466. } sqlite3Autoext = { 0, 0 };
  97467. /* The "wsdAutoext" macro will resolve to the autoextension
  97468. ** state vector. If writable static data is unsupported on the target,
  97469. ** we have to locate the state vector at run-time. In the more common
  97470. ** case where writable static data is supported, wsdStat can refer directly
  97471. ** to the "sqlite3Autoext" state vector declared above.
  97472. */
  97473. #ifdef SQLITE_OMIT_WSD
  97474. # define wsdAutoextInit \
  97475. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  97476. # define wsdAutoext x[0]
  97477. #else
  97478. # define wsdAutoextInit
  97479. # define wsdAutoext sqlite3Autoext
  97480. #endif
  97481. /*
  97482. ** Register a statically linked extension that is automatically
  97483. ** loaded by every new database connection.
  97484. */
  97485. SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
  97486. int rc = SQLITE_OK;
  97487. #ifndef SQLITE_OMIT_AUTOINIT
  97488. rc = sqlite3_initialize();
  97489. if( rc ){
  97490. return rc;
  97491. }else
  97492. #endif
  97493. {
  97494. u32 i;
  97495. #if SQLITE_THREADSAFE
  97496. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  97497. #endif
  97498. wsdAutoextInit;
  97499. sqlite3_mutex_enter(mutex);
  97500. for(i=0; i<wsdAutoext.nExt; i++){
  97501. if( wsdAutoext.aExt[i]==xInit ) break;
  97502. }
  97503. if( i==wsdAutoext.nExt ){
  97504. u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  97505. void (**aNew)(void);
  97506. aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
  97507. if( aNew==0 ){
  97508. rc = SQLITE_NOMEM;
  97509. }else{
  97510. wsdAutoext.aExt = aNew;
  97511. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  97512. wsdAutoext.nExt++;
  97513. }
  97514. }
  97515. sqlite3_mutex_leave(mutex);
  97516. assert( (rc&0xff)==rc );
  97517. return rc;
  97518. }
  97519. }
  97520. /*
  97521. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  97522. ** set of routines that is invoked for each new database connection, if it
  97523. ** is currently on the list. If xInit is not on the list, then this
  97524. ** routine is a no-op.
  97525. **
  97526. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  97527. ** was not on the list.
  97528. */
  97529. SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
  97530. #if SQLITE_THREADSAFE
  97531. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  97532. #endif
  97533. int i;
  97534. int n = 0;
  97535. wsdAutoextInit;
  97536. sqlite3_mutex_enter(mutex);
  97537. for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
  97538. if( wsdAutoext.aExt[i]==xInit ){
  97539. wsdAutoext.nExt--;
  97540. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  97541. n++;
  97542. break;
  97543. }
  97544. }
  97545. sqlite3_mutex_leave(mutex);
  97546. return n;
  97547. }
  97548. /*
  97549. ** Reset the automatic extension loading mechanism.
  97550. */
  97551. SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
  97552. #ifndef SQLITE_OMIT_AUTOINIT
  97553. if( sqlite3_initialize()==SQLITE_OK )
  97554. #endif
  97555. {
  97556. #if SQLITE_THREADSAFE
  97557. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  97558. #endif
  97559. wsdAutoextInit;
  97560. sqlite3_mutex_enter(mutex);
  97561. sqlite3_free(wsdAutoext.aExt);
  97562. wsdAutoext.aExt = 0;
  97563. wsdAutoext.nExt = 0;
  97564. sqlite3_mutex_leave(mutex);
  97565. }
  97566. }
  97567. /*
  97568. ** Load all automatic extensions.
  97569. **
  97570. ** If anything goes wrong, set an error in the database connection.
  97571. */
  97572. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  97573. u32 i;
  97574. int go = 1;
  97575. int rc;
  97576. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  97577. wsdAutoextInit;
  97578. if( wsdAutoext.nExt==0 ){
  97579. /* Common case: early out without every having to acquire a mutex */
  97580. return;
  97581. }
  97582. for(i=0; go; i++){
  97583. char *zErrmsg;
  97584. #if SQLITE_THREADSAFE
  97585. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  97586. #endif
  97587. sqlite3_mutex_enter(mutex);
  97588. if( i>=wsdAutoext.nExt ){
  97589. xInit = 0;
  97590. go = 0;
  97591. }else{
  97592. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  97593. wsdAutoext.aExt[i];
  97594. }
  97595. sqlite3_mutex_leave(mutex);
  97596. zErrmsg = 0;
  97597. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  97598. sqlite3ErrorWithMsg(db, rc,
  97599. "automatic extension loading failed: %s", zErrmsg);
  97600. go = 0;
  97601. }
  97602. sqlite3_free(zErrmsg);
  97603. }
  97604. }
  97605. /************** End of loadext.c *********************************************/
  97606. /************** Begin file pragma.c ******************************************/
  97607. /*
  97608. ** 2003 April 6
  97609. **
  97610. ** The author disclaims copyright to this source code. In place of
  97611. ** a legal notice, here is a blessing:
  97612. **
  97613. ** May you do good and not evil.
  97614. ** May you find forgiveness for yourself and forgive others.
  97615. ** May you share freely, never taking more than you give.
  97616. **
  97617. *************************************************************************
  97618. ** This file contains code used to implement the PRAGMA command.
  97619. */
  97620. /* #include "sqliteInt.h" */
  97621. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  97622. # if defined(__APPLE__)
  97623. # define SQLITE_ENABLE_LOCKING_STYLE 1
  97624. # else
  97625. # define SQLITE_ENABLE_LOCKING_STYLE 0
  97626. # endif
  97627. #endif
  97628. /***************************************************************************
  97629. ** The "pragma.h" include file is an automatically generated file that
  97630. ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
  97631. ** object. This ensures that the aPragmaName[] table is arranged in
  97632. ** lexicographical order to facility a binary search of the pragma name.
  97633. ** Do not edit pragma.h directly. Edit and rerun the script in at
  97634. ** ../tool/mkpragmatab.tcl. */
  97635. /************** Include pragma.h in the middle of pragma.c *******************/
  97636. /************** Begin file pragma.h ******************************************/
  97637. /* DO NOT EDIT!
  97638. ** This file is automatically generated by the script at
  97639. ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
  97640. ** that script and rerun it.
  97641. */
  97642. #define PragTyp_HEADER_VALUE 0
  97643. #define PragTyp_AUTO_VACUUM 1
  97644. #define PragTyp_FLAG 2
  97645. #define PragTyp_BUSY_TIMEOUT 3
  97646. #define PragTyp_CACHE_SIZE 4
  97647. #define PragTyp_CASE_SENSITIVE_LIKE 5
  97648. #define PragTyp_COLLATION_LIST 6
  97649. #define PragTyp_COMPILE_OPTIONS 7
  97650. #define PragTyp_DATA_STORE_DIRECTORY 8
  97651. #define PragTyp_DATABASE_LIST 9
  97652. #define PragTyp_DEFAULT_CACHE_SIZE 10
  97653. #define PragTyp_ENCODING 11
  97654. #define PragTyp_FOREIGN_KEY_CHECK 12
  97655. #define PragTyp_FOREIGN_KEY_LIST 13
  97656. #define PragTyp_INCREMENTAL_VACUUM 14
  97657. #define PragTyp_INDEX_INFO 15
  97658. #define PragTyp_INDEX_LIST 16
  97659. #define PragTyp_INTEGRITY_CHECK 17
  97660. #define PragTyp_JOURNAL_MODE 18
  97661. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  97662. #define PragTyp_LOCK_PROXY_FILE 20
  97663. #define PragTyp_LOCKING_MODE 21
  97664. #define PragTyp_PAGE_COUNT 22
  97665. #define PragTyp_MMAP_SIZE 23
  97666. #define PragTyp_PAGE_SIZE 24
  97667. #define PragTyp_SECURE_DELETE 25
  97668. #define PragTyp_SHRINK_MEMORY 26
  97669. #define PragTyp_SOFT_HEAP_LIMIT 27
  97670. #define PragTyp_STATS 28
  97671. #define PragTyp_SYNCHRONOUS 29
  97672. #define PragTyp_TABLE_INFO 30
  97673. #define PragTyp_TEMP_STORE 31
  97674. #define PragTyp_TEMP_STORE_DIRECTORY 32
  97675. #define PragTyp_THREADS 33
  97676. #define PragTyp_WAL_AUTOCHECKPOINT 34
  97677. #define PragTyp_WAL_CHECKPOINT 35
  97678. #define PragTyp_ACTIVATE_EXTENSIONS 36
  97679. #define PragTyp_HEXKEY 37
  97680. #define PragTyp_KEY 38
  97681. #define PragTyp_REKEY 39
  97682. #define PragTyp_LOCK_STATUS 40
  97683. #define PragTyp_PARSER_TRACE 41
  97684. #define PragFlag_NeedSchema 0x01
  97685. #define PragFlag_ReadOnly 0x02
  97686. static const struct sPragmaNames {
  97687. const char *const zName; /* Name of pragma */
  97688. u8 ePragTyp; /* PragTyp_XXX value */
  97689. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  97690. u32 iArg; /* Extra argument */
  97691. } aPragmaNames[] = {
  97692. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  97693. { /* zName: */ "activate_extensions",
  97694. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  97695. /* ePragFlag: */ 0,
  97696. /* iArg: */ 0 },
  97697. #endif
  97698. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  97699. { /* zName: */ "application_id",
  97700. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  97701. /* ePragFlag: */ 0,
  97702. /* iArg: */ BTREE_APPLICATION_ID },
  97703. #endif
  97704. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  97705. { /* zName: */ "auto_vacuum",
  97706. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  97707. /* ePragFlag: */ PragFlag_NeedSchema,
  97708. /* iArg: */ 0 },
  97709. #endif
  97710. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97711. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  97712. { /* zName: */ "automatic_index",
  97713. /* ePragTyp: */ PragTyp_FLAG,
  97714. /* ePragFlag: */ 0,
  97715. /* iArg: */ SQLITE_AutoIndex },
  97716. #endif
  97717. #endif
  97718. { /* zName: */ "busy_timeout",
  97719. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  97720. /* ePragFlag: */ 0,
  97721. /* iArg: */ 0 },
  97722. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  97723. { /* zName: */ "cache_size",
  97724. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  97725. /* ePragFlag: */ 0,
  97726. /* iArg: */ 0 },
  97727. #endif
  97728. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97729. { /* zName: */ "cache_spill",
  97730. /* ePragTyp: */ PragTyp_FLAG,
  97731. /* ePragFlag: */ 0,
  97732. /* iArg: */ SQLITE_CacheSpill },
  97733. #endif
  97734. { /* zName: */ "case_sensitive_like",
  97735. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  97736. /* ePragFlag: */ 0,
  97737. /* iArg: */ 0 },
  97738. { /* zName: */ "cell_size_check",
  97739. /* ePragTyp: */ PragTyp_FLAG,
  97740. /* ePragFlag: */ 0,
  97741. /* iArg: */ SQLITE_CellSizeCk },
  97742. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97743. { /* zName: */ "checkpoint_fullfsync",
  97744. /* ePragTyp: */ PragTyp_FLAG,
  97745. /* ePragFlag: */ 0,
  97746. /* iArg: */ SQLITE_CkptFullFSync },
  97747. #endif
  97748. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  97749. { /* zName: */ "collation_list",
  97750. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  97751. /* ePragFlag: */ 0,
  97752. /* iArg: */ 0 },
  97753. #endif
  97754. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  97755. { /* zName: */ "compile_options",
  97756. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  97757. /* ePragFlag: */ 0,
  97758. /* iArg: */ 0 },
  97759. #endif
  97760. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97761. { /* zName: */ "count_changes",
  97762. /* ePragTyp: */ PragTyp_FLAG,
  97763. /* ePragFlag: */ 0,
  97764. /* iArg: */ SQLITE_CountRows },
  97765. #endif
  97766. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  97767. { /* zName: */ "data_store_directory",
  97768. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  97769. /* ePragFlag: */ 0,
  97770. /* iArg: */ 0 },
  97771. #endif
  97772. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  97773. { /* zName: */ "data_version",
  97774. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  97775. /* ePragFlag: */ PragFlag_ReadOnly,
  97776. /* iArg: */ BTREE_DATA_VERSION },
  97777. #endif
  97778. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  97779. { /* zName: */ "database_list",
  97780. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  97781. /* ePragFlag: */ PragFlag_NeedSchema,
  97782. /* iArg: */ 0 },
  97783. #endif
  97784. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  97785. { /* zName: */ "default_cache_size",
  97786. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  97787. /* ePragFlag: */ PragFlag_NeedSchema,
  97788. /* iArg: */ 0 },
  97789. #endif
  97790. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97791. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  97792. { /* zName: */ "defer_foreign_keys",
  97793. /* ePragTyp: */ PragTyp_FLAG,
  97794. /* ePragFlag: */ 0,
  97795. /* iArg: */ SQLITE_DeferFKs },
  97796. #endif
  97797. #endif
  97798. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97799. { /* zName: */ "empty_result_callbacks",
  97800. /* ePragTyp: */ PragTyp_FLAG,
  97801. /* ePragFlag: */ 0,
  97802. /* iArg: */ SQLITE_NullCallback },
  97803. #endif
  97804. #if !defined(SQLITE_OMIT_UTF16)
  97805. { /* zName: */ "encoding",
  97806. /* ePragTyp: */ PragTyp_ENCODING,
  97807. /* ePragFlag: */ 0,
  97808. /* iArg: */ 0 },
  97809. #endif
  97810. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  97811. { /* zName: */ "foreign_key_check",
  97812. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  97813. /* ePragFlag: */ PragFlag_NeedSchema,
  97814. /* iArg: */ 0 },
  97815. #endif
  97816. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  97817. { /* zName: */ "foreign_key_list",
  97818. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  97819. /* ePragFlag: */ PragFlag_NeedSchema,
  97820. /* iArg: */ 0 },
  97821. #endif
  97822. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97823. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  97824. { /* zName: */ "foreign_keys",
  97825. /* ePragTyp: */ PragTyp_FLAG,
  97826. /* ePragFlag: */ 0,
  97827. /* iArg: */ SQLITE_ForeignKeys },
  97828. #endif
  97829. #endif
  97830. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  97831. { /* zName: */ "freelist_count",
  97832. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  97833. /* ePragFlag: */ PragFlag_ReadOnly,
  97834. /* iArg: */ BTREE_FREE_PAGE_COUNT },
  97835. #endif
  97836. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97837. { /* zName: */ "full_column_names",
  97838. /* ePragTyp: */ PragTyp_FLAG,
  97839. /* ePragFlag: */ 0,
  97840. /* iArg: */ SQLITE_FullColNames },
  97841. { /* zName: */ "fullfsync",
  97842. /* ePragTyp: */ PragTyp_FLAG,
  97843. /* ePragFlag: */ 0,
  97844. /* iArg: */ SQLITE_FullFSync },
  97845. #endif
  97846. #if defined(SQLITE_HAS_CODEC)
  97847. { /* zName: */ "hexkey",
  97848. /* ePragTyp: */ PragTyp_HEXKEY,
  97849. /* ePragFlag: */ 0,
  97850. /* iArg: */ 0 },
  97851. { /* zName: */ "hexrekey",
  97852. /* ePragTyp: */ PragTyp_HEXKEY,
  97853. /* ePragFlag: */ 0,
  97854. /* iArg: */ 0 },
  97855. #endif
  97856. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97857. #if !defined(SQLITE_OMIT_CHECK)
  97858. { /* zName: */ "ignore_check_constraints",
  97859. /* ePragTyp: */ PragTyp_FLAG,
  97860. /* ePragFlag: */ 0,
  97861. /* iArg: */ SQLITE_IgnoreChecks },
  97862. #endif
  97863. #endif
  97864. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  97865. { /* zName: */ "incremental_vacuum",
  97866. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  97867. /* ePragFlag: */ PragFlag_NeedSchema,
  97868. /* iArg: */ 0 },
  97869. #endif
  97870. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  97871. { /* zName: */ "index_info",
  97872. /* ePragTyp: */ PragTyp_INDEX_INFO,
  97873. /* ePragFlag: */ PragFlag_NeedSchema,
  97874. /* iArg: */ 0 },
  97875. { /* zName: */ "index_list",
  97876. /* ePragTyp: */ PragTyp_INDEX_LIST,
  97877. /* ePragFlag: */ PragFlag_NeedSchema,
  97878. /* iArg: */ 0 },
  97879. { /* zName: */ "index_xinfo",
  97880. /* ePragTyp: */ PragTyp_INDEX_INFO,
  97881. /* ePragFlag: */ PragFlag_NeedSchema,
  97882. /* iArg: */ 1 },
  97883. #endif
  97884. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  97885. { /* zName: */ "integrity_check",
  97886. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  97887. /* ePragFlag: */ PragFlag_NeedSchema,
  97888. /* iArg: */ 0 },
  97889. #endif
  97890. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  97891. { /* zName: */ "journal_mode",
  97892. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  97893. /* ePragFlag: */ PragFlag_NeedSchema,
  97894. /* iArg: */ 0 },
  97895. { /* zName: */ "journal_size_limit",
  97896. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  97897. /* ePragFlag: */ 0,
  97898. /* iArg: */ 0 },
  97899. #endif
  97900. #if defined(SQLITE_HAS_CODEC)
  97901. { /* zName: */ "key",
  97902. /* ePragTyp: */ PragTyp_KEY,
  97903. /* ePragFlag: */ 0,
  97904. /* iArg: */ 0 },
  97905. #endif
  97906. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97907. { /* zName: */ "legacy_file_format",
  97908. /* ePragTyp: */ PragTyp_FLAG,
  97909. /* ePragFlag: */ 0,
  97910. /* iArg: */ SQLITE_LegacyFileFmt },
  97911. #endif
  97912. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  97913. { /* zName: */ "lock_proxy_file",
  97914. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  97915. /* ePragFlag: */ 0,
  97916. /* iArg: */ 0 },
  97917. #endif
  97918. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  97919. { /* zName: */ "lock_status",
  97920. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  97921. /* ePragFlag: */ 0,
  97922. /* iArg: */ 0 },
  97923. #endif
  97924. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  97925. { /* zName: */ "locking_mode",
  97926. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  97927. /* ePragFlag: */ 0,
  97928. /* iArg: */ 0 },
  97929. { /* zName: */ "max_page_count",
  97930. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  97931. /* ePragFlag: */ PragFlag_NeedSchema,
  97932. /* iArg: */ 0 },
  97933. { /* zName: */ "mmap_size",
  97934. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  97935. /* ePragFlag: */ 0,
  97936. /* iArg: */ 0 },
  97937. { /* zName: */ "page_count",
  97938. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  97939. /* ePragFlag: */ PragFlag_NeedSchema,
  97940. /* iArg: */ 0 },
  97941. { /* zName: */ "page_size",
  97942. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  97943. /* ePragFlag: */ 0,
  97944. /* iArg: */ 0 },
  97945. #endif
  97946. #if defined(SQLITE_DEBUG)
  97947. { /* zName: */ "parser_trace",
  97948. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  97949. /* ePragFlag: */ 0,
  97950. /* iArg: */ 0 },
  97951. #endif
  97952. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97953. { /* zName: */ "query_only",
  97954. /* ePragTyp: */ PragTyp_FLAG,
  97955. /* ePragFlag: */ 0,
  97956. /* iArg: */ SQLITE_QueryOnly },
  97957. #endif
  97958. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  97959. { /* zName: */ "quick_check",
  97960. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  97961. /* ePragFlag: */ PragFlag_NeedSchema,
  97962. /* iArg: */ 0 },
  97963. #endif
  97964. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97965. { /* zName: */ "read_uncommitted",
  97966. /* ePragTyp: */ PragTyp_FLAG,
  97967. /* ePragFlag: */ 0,
  97968. /* iArg: */ SQLITE_ReadUncommitted },
  97969. { /* zName: */ "recursive_triggers",
  97970. /* ePragTyp: */ PragTyp_FLAG,
  97971. /* ePragFlag: */ 0,
  97972. /* iArg: */ SQLITE_RecTriggers },
  97973. #endif
  97974. #if defined(SQLITE_HAS_CODEC)
  97975. { /* zName: */ "rekey",
  97976. /* ePragTyp: */ PragTyp_REKEY,
  97977. /* ePragFlag: */ 0,
  97978. /* iArg: */ 0 },
  97979. #endif
  97980. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97981. { /* zName: */ "reverse_unordered_selects",
  97982. /* ePragTyp: */ PragTyp_FLAG,
  97983. /* ePragFlag: */ 0,
  97984. /* iArg: */ SQLITE_ReverseOrder },
  97985. #endif
  97986. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  97987. { /* zName: */ "schema_version",
  97988. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  97989. /* ePragFlag: */ 0,
  97990. /* iArg: */ BTREE_SCHEMA_VERSION },
  97991. #endif
  97992. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  97993. { /* zName: */ "secure_delete",
  97994. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  97995. /* ePragFlag: */ 0,
  97996. /* iArg: */ 0 },
  97997. #endif
  97998. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  97999. { /* zName: */ "short_column_names",
  98000. /* ePragTyp: */ PragTyp_FLAG,
  98001. /* ePragFlag: */ 0,
  98002. /* iArg: */ SQLITE_ShortColNames },
  98003. #endif
  98004. { /* zName: */ "shrink_memory",
  98005. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  98006. /* ePragFlag: */ 0,
  98007. /* iArg: */ 0 },
  98008. { /* zName: */ "soft_heap_limit",
  98009. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  98010. /* ePragFlag: */ 0,
  98011. /* iArg: */ 0 },
  98012. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98013. #if defined(SQLITE_DEBUG)
  98014. { /* zName: */ "sql_trace",
  98015. /* ePragTyp: */ PragTyp_FLAG,
  98016. /* ePragFlag: */ 0,
  98017. /* iArg: */ SQLITE_SqlTrace },
  98018. #endif
  98019. #endif
  98020. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  98021. { /* zName: */ "stats",
  98022. /* ePragTyp: */ PragTyp_STATS,
  98023. /* ePragFlag: */ PragFlag_NeedSchema,
  98024. /* iArg: */ 0 },
  98025. #endif
  98026. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  98027. { /* zName: */ "synchronous",
  98028. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  98029. /* ePragFlag: */ PragFlag_NeedSchema,
  98030. /* iArg: */ 0 },
  98031. #endif
  98032. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  98033. { /* zName: */ "table_info",
  98034. /* ePragTyp: */ PragTyp_TABLE_INFO,
  98035. /* ePragFlag: */ PragFlag_NeedSchema,
  98036. /* iArg: */ 0 },
  98037. #endif
  98038. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  98039. { /* zName: */ "temp_store",
  98040. /* ePragTyp: */ PragTyp_TEMP_STORE,
  98041. /* ePragFlag: */ 0,
  98042. /* iArg: */ 0 },
  98043. { /* zName: */ "temp_store_directory",
  98044. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  98045. /* ePragFlag: */ 0,
  98046. /* iArg: */ 0 },
  98047. #endif
  98048. { /* zName: */ "threads",
  98049. /* ePragTyp: */ PragTyp_THREADS,
  98050. /* ePragFlag: */ 0,
  98051. /* iArg: */ 0 },
  98052. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  98053. { /* zName: */ "user_version",
  98054. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  98055. /* ePragFlag: */ 0,
  98056. /* iArg: */ BTREE_USER_VERSION },
  98057. #endif
  98058. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98059. #if defined(SQLITE_DEBUG)
  98060. { /* zName: */ "vdbe_addoptrace",
  98061. /* ePragTyp: */ PragTyp_FLAG,
  98062. /* ePragFlag: */ 0,
  98063. /* iArg: */ SQLITE_VdbeAddopTrace },
  98064. { /* zName: */ "vdbe_debug",
  98065. /* ePragTyp: */ PragTyp_FLAG,
  98066. /* ePragFlag: */ 0,
  98067. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  98068. { /* zName: */ "vdbe_eqp",
  98069. /* ePragTyp: */ PragTyp_FLAG,
  98070. /* ePragFlag: */ 0,
  98071. /* iArg: */ SQLITE_VdbeEQP },
  98072. { /* zName: */ "vdbe_listing",
  98073. /* ePragTyp: */ PragTyp_FLAG,
  98074. /* ePragFlag: */ 0,
  98075. /* iArg: */ SQLITE_VdbeListing },
  98076. { /* zName: */ "vdbe_trace",
  98077. /* ePragTyp: */ PragTyp_FLAG,
  98078. /* ePragFlag: */ 0,
  98079. /* iArg: */ SQLITE_VdbeTrace },
  98080. #endif
  98081. #endif
  98082. #if !defined(SQLITE_OMIT_WAL)
  98083. { /* zName: */ "wal_autocheckpoint",
  98084. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  98085. /* ePragFlag: */ 0,
  98086. /* iArg: */ 0 },
  98087. { /* zName: */ "wal_checkpoint",
  98088. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  98089. /* ePragFlag: */ PragFlag_NeedSchema,
  98090. /* iArg: */ 0 },
  98091. #endif
  98092. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  98093. { /* zName: */ "writable_schema",
  98094. /* ePragTyp: */ PragTyp_FLAG,
  98095. /* ePragFlag: */ 0,
  98096. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  98097. #endif
  98098. };
  98099. /* Number of pragmas: 60 on by default, 73 total. */
  98100. /************** End of pragma.h **********************************************/
  98101. /************** Continuing where we left off in pragma.c *********************/
  98102. /*
  98103. ** Interpret the given string as a safety level. Return 0 for OFF,
  98104. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  98105. ** unrecognized string argument. The FULL option is disallowed
  98106. ** if the omitFull parameter it 1.
  98107. **
  98108. ** Note that the values returned are one less that the values that
  98109. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  98110. ** to support legacy SQL code. The safety level used to be boolean
  98111. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  98112. */
  98113. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  98114. /* 123456789 123456789 */
  98115. static const char zText[] = "onoffalseyestruefull";
  98116. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  98117. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  98118. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  98119. int i, n;
  98120. if( sqlite3Isdigit(*z) ){
  98121. return (u8)sqlite3Atoi(z);
  98122. }
  98123. n = sqlite3Strlen30(z);
  98124. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  98125. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  98126. return iValue[i];
  98127. }
  98128. }
  98129. return dflt;
  98130. }
  98131. /*
  98132. ** Interpret the given string as a boolean value.
  98133. */
  98134. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  98135. return getSafetyLevel(z,1,dflt)!=0;
  98136. }
  98137. /* The sqlite3GetBoolean() function is used by other modules but the
  98138. ** remainder of this file is specific to PRAGMA processing. So omit
  98139. ** the rest of the file if PRAGMAs are omitted from the build.
  98140. */
  98141. #if !defined(SQLITE_OMIT_PRAGMA)
  98142. /*
  98143. ** Interpret the given string as a locking mode value.
  98144. */
  98145. static int getLockingMode(const char *z){
  98146. if( z ){
  98147. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  98148. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  98149. }
  98150. return PAGER_LOCKINGMODE_QUERY;
  98151. }
  98152. #ifndef SQLITE_OMIT_AUTOVACUUM
  98153. /*
  98154. ** Interpret the given string as an auto-vacuum mode value.
  98155. **
  98156. ** The following strings, "none", "full" and "incremental" are
  98157. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  98158. */
  98159. static int getAutoVacuum(const char *z){
  98160. int i;
  98161. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  98162. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  98163. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  98164. i = sqlite3Atoi(z);
  98165. return (u8)((i>=0&&i<=2)?i:0);
  98166. }
  98167. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  98168. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  98169. /*
  98170. ** Interpret the given string as a temp db location. Return 1 for file
  98171. ** backed temporary databases, 2 for the Red-Black tree in memory database
  98172. ** and 0 to use the compile-time default.
  98173. */
  98174. static int getTempStore(const char *z){
  98175. if( z[0]>='0' && z[0]<='2' ){
  98176. return z[0] - '0';
  98177. }else if( sqlite3StrICmp(z, "file")==0 ){
  98178. return 1;
  98179. }else if( sqlite3StrICmp(z, "memory")==0 ){
  98180. return 2;
  98181. }else{
  98182. return 0;
  98183. }
  98184. }
  98185. #endif /* SQLITE_PAGER_PRAGMAS */
  98186. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  98187. /*
  98188. ** Invalidate temp storage, either when the temp storage is changed
  98189. ** from default, or when 'file' and the temp_store_directory has changed
  98190. */
  98191. static int invalidateTempStorage(Parse *pParse){
  98192. sqlite3 *db = pParse->db;
  98193. if( db->aDb[1].pBt!=0 ){
  98194. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  98195. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  98196. "from within a transaction");
  98197. return SQLITE_ERROR;
  98198. }
  98199. sqlite3BtreeClose(db->aDb[1].pBt);
  98200. db->aDb[1].pBt = 0;
  98201. sqlite3ResetAllSchemasOfConnection(db);
  98202. }
  98203. return SQLITE_OK;
  98204. }
  98205. #endif /* SQLITE_PAGER_PRAGMAS */
  98206. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  98207. /*
  98208. ** If the TEMP database is open, close it and mark the database schema
  98209. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  98210. ** or DEFAULT_TEMP_STORE pragmas.
  98211. */
  98212. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  98213. int ts = getTempStore(zStorageType);
  98214. sqlite3 *db = pParse->db;
  98215. if( db->temp_store==ts ) return SQLITE_OK;
  98216. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  98217. return SQLITE_ERROR;
  98218. }
  98219. db->temp_store = (u8)ts;
  98220. return SQLITE_OK;
  98221. }
  98222. #endif /* SQLITE_PAGER_PRAGMAS */
  98223. /*
  98224. ** Generate code to return a single integer value.
  98225. */
  98226. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  98227. Vdbe *v = sqlite3GetVdbe(pParse);
  98228. int nMem = ++pParse->nMem;
  98229. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  98230. if( pI64 ){
  98231. memcpy(pI64, &value, sizeof(value));
  98232. }
  98233. sqlite3VdbeAddOp4(v, OP_Int64, 0, nMem, 0, (char*)pI64, P4_INT64);
  98234. sqlite3VdbeSetNumCols(v, 1);
  98235. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  98236. sqlite3VdbeAddOp2(v, OP_ResultRow, nMem, 1);
  98237. }
  98238. /*
  98239. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  98240. ** set these values for all pagers.
  98241. */
  98242. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  98243. static void setAllPagerFlags(sqlite3 *db){
  98244. if( db->autoCommit ){
  98245. Db *pDb = db->aDb;
  98246. int n = db->nDb;
  98247. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  98248. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  98249. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  98250. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  98251. == PAGER_FLAGS_MASK );
  98252. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  98253. while( (n--) > 0 ){
  98254. if( pDb->pBt ){
  98255. sqlite3BtreeSetPagerFlags(pDb->pBt,
  98256. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  98257. }
  98258. pDb++;
  98259. }
  98260. }
  98261. }
  98262. #else
  98263. # define setAllPagerFlags(X) /* no-op */
  98264. #endif
  98265. /*
  98266. ** Return a human-readable name for a constraint resolution action.
  98267. */
  98268. #ifndef SQLITE_OMIT_FOREIGN_KEY
  98269. static const char *actionName(u8 action){
  98270. const char *zName;
  98271. switch( action ){
  98272. case OE_SetNull: zName = "SET NULL"; break;
  98273. case OE_SetDflt: zName = "SET DEFAULT"; break;
  98274. case OE_Cascade: zName = "CASCADE"; break;
  98275. case OE_Restrict: zName = "RESTRICT"; break;
  98276. default: zName = "NO ACTION";
  98277. assert( action==OE_None ); break;
  98278. }
  98279. return zName;
  98280. }
  98281. #endif
  98282. /*
  98283. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  98284. ** defined in pager.h. This function returns the associated lowercase
  98285. ** journal-mode name.
  98286. */
  98287. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  98288. static char * const azModeName[] = {
  98289. "delete", "persist", "off", "truncate", "memory"
  98290. #ifndef SQLITE_OMIT_WAL
  98291. , "wal"
  98292. #endif
  98293. };
  98294. assert( PAGER_JOURNALMODE_DELETE==0 );
  98295. assert( PAGER_JOURNALMODE_PERSIST==1 );
  98296. assert( PAGER_JOURNALMODE_OFF==2 );
  98297. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  98298. assert( PAGER_JOURNALMODE_MEMORY==4 );
  98299. assert( PAGER_JOURNALMODE_WAL==5 );
  98300. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  98301. if( eMode==ArraySize(azModeName) ) return 0;
  98302. return azModeName[eMode];
  98303. }
  98304. /*
  98305. ** Process a pragma statement.
  98306. **
  98307. ** Pragmas are of this form:
  98308. **
  98309. ** PRAGMA [database.]id [= value]
  98310. **
  98311. ** The identifier might also be a string. The value is a string, and
  98312. ** identifier, or a number. If minusFlag is true, then the value is
  98313. ** a number that was preceded by a minus sign.
  98314. **
  98315. ** If the left side is "database.id" then pId1 is the database name
  98316. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  98317. ** id and pId2 is any empty string.
  98318. */
  98319. SQLITE_PRIVATE void sqlite3Pragma(
  98320. Parse *pParse,
  98321. Token *pId1, /* First part of [database.]id field */
  98322. Token *pId2, /* Second part of [database.]id field, or NULL */
  98323. Token *pValue, /* Token for <value>, or NULL */
  98324. int minusFlag /* True if a '-' sign preceded <value> */
  98325. ){
  98326. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  98327. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  98328. const char *zDb = 0; /* The database name */
  98329. Token *pId; /* Pointer to <id> token */
  98330. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  98331. int iDb; /* Database index for <database> */
  98332. int lwr, upr, mid = 0; /* Binary search bounds */
  98333. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  98334. sqlite3 *db = pParse->db; /* The database connection */
  98335. Db *pDb; /* The specific database being pragmaed */
  98336. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  98337. const struct sPragmaNames *pPragma;
  98338. if( v==0 ) return;
  98339. sqlite3VdbeRunOnlyOnce(v);
  98340. pParse->nMem = 2;
  98341. /* Interpret the [database.] part of the pragma statement. iDb is the
  98342. ** index of the database this pragma is being applied to in db.aDb[]. */
  98343. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  98344. if( iDb<0 ) return;
  98345. pDb = &db->aDb[iDb];
  98346. /* If the temp database has been explicitly named as part of the
  98347. ** pragma, make sure it is open.
  98348. */
  98349. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  98350. return;
  98351. }
  98352. zLeft = sqlite3NameFromToken(db, pId);
  98353. if( !zLeft ) return;
  98354. if( minusFlag ){
  98355. zRight = sqlite3MPrintf(db, "-%T", pValue);
  98356. }else{
  98357. zRight = sqlite3NameFromToken(db, pValue);
  98358. }
  98359. assert( pId2 );
  98360. zDb = pId2->n>0 ? pDb->zName : 0;
  98361. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  98362. goto pragma_out;
  98363. }
  98364. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  98365. ** connection. If it returns SQLITE_OK, then assume that the VFS
  98366. ** handled the pragma and generate a no-op prepared statement.
  98367. **
  98368. ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
  98369. ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
  98370. ** object corresponding to the database file to which the pragma
  98371. ** statement refers.
  98372. **
  98373. ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
  98374. ** file control is an array of pointers to strings (char**) in which the
  98375. ** second element of the array is the name of the pragma and the third
  98376. ** element is the argument to the pragma or NULL if the pragma has no
  98377. ** argument.
  98378. */
  98379. aFcntl[0] = 0;
  98380. aFcntl[1] = zLeft;
  98381. aFcntl[2] = zRight;
  98382. aFcntl[3] = 0;
  98383. db->busyHandler.nBusy = 0;
  98384. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  98385. if( rc==SQLITE_OK ){
  98386. if( aFcntl[0] ){
  98387. int nMem = ++pParse->nMem;
  98388. sqlite3VdbeAddOp4(v, OP_String8, 0, nMem, 0, aFcntl[0], 0);
  98389. sqlite3VdbeSetNumCols(v, 1);
  98390. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  98391. sqlite3VdbeAddOp2(v, OP_ResultRow, nMem, 1);
  98392. sqlite3_free(aFcntl[0]);
  98393. }
  98394. goto pragma_out;
  98395. }
  98396. if( rc!=SQLITE_NOTFOUND ){
  98397. if( aFcntl[0] ){
  98398. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  98399. sqlite3_free(aFcntl[0]);
  98400. }
  98401. pParse->nErr++;
  98402. pParse->rc = rc;
  98403. goto pragma_out;
  98404. }
  98405. /* Locate the pragma in the lookup table */
  98406. lwr = 0;
  98407. upr = ArraySize(aPragmaNames)-1;
  98408. while( lwr<=upr ){
  98409. mid = (lwr+upr)/2;
  98410. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  98411. if( rc==0 ) break;
  98412. if( rc<0 ){
  98413. upr = mid - 1;
  98414. }else{
  98415. lwr = mid + 1;
  98416. }
  98417. }
  98418. if( lwr>upr ) goto pragma_out;
  98419. pPragma = &aPragmaNames[mid];
  98420. /* Make sure the database schema is loaded if the pragma requires that */
  98421. if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
  98422. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  98423. }
  98424. /* Jump to the appropriate pragma handler */
  98425. switch( pPragma->ePragTyp ){
  98426. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  98427. /*
  98428. ** PRAGMA [database.]default_cache_size
  98429. ** PRAGMA [database.]default_cache_size=N
  98430. **
  98431. ** The first form reports the current persistent setting for the
  98432. ** page cache size. The value returned is the maximum number of
  98433. ** pages in the page cache. The second form sets both the current
  98434. ** page cache size value and the persistent page cache size value
  98435. ** stored in the database file.
  98436. **
  98437. ** Older versions of SQLite would set the default cache size to a
  98438. ** negative number to indicate synchronous=OFF. These days, synchronous
  98439. ** is always on by default regardless of the sign of the default cache
  98440. ** size. But continue to take the absolute value of the default cache
  98441. ** size of historical compatibility.
  98442. */
  98443. case PragTyp_DEFAULT_CACHE_SIZE: {
  98444. static const int iLn = VDBE_OFFSET_LINENO(2);
  98445. static const VdbeOpList getCacheSize[] = {
  98446. { OP_Transaction, 0, 0, 0}, /* 0 */
  98447. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  98448. { OP_IfPos, 1, 8, 0},
  98449. { OP_Integer, 0, 2, 0},
  98450. { OP_Subtract, 1, 2, 1},
  98451. { OP_IfPos, 1, 8, 0},
  98452. { OP_Integer, 0, 1, 0}, /* 6 */
  98453. { OP_Noop, 0, 0, 0},
  98454. { OP_ResultRow, 1, 1, 0},
  98455. };
  98456. int addr;
  98457. sqlite3VdbeUsesBtree(v, iDb);
  98458. if( !zRight ){
  98459. sqlite3VdbeSetNumCols(v, 1);
  98460. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  98461. pParse->nMem += 2;
  98462. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
  98463. sqlite3VdbeChangeP1(v, addr, iDb);
  98464. sqlite3VdbeChangeP1(v, addr+1, iDb);
  98465. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  98466. }else{
  98467. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  98468. sqlite3BeginWriteOperation(pParse, 0, iDb);
  98469. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  98470. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  98471. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98472. pDb->pSchema->cache_size = size;
  98473. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  98474. }
  98475. break;
  98476. }
  98477. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  98478. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  98479. /*
  98480. ** PRAGMA [database.]page_size
  98481. ** PRAGMA [database.]page_size=N
  98482. **
  98483. ** The first form reports the current setting for the
  98484. ** database page size in bytes. The second form sets the
  98485. ** database page size value. The value can only be set if
  98486. ** the database has not yet been created.
  98487. */
  98488. case PragTyp_PAGE_SIZE: {
  98489. Btree *pBt = pDb->pBt;
  98490. assert( pBt!=0 );
  98491. if( !zRight ){
  98492. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  98493. returnSingleInt(pParse, "page_size", size);
  98494. }else{
  98495. /* Malloc may fail when setting the page-size, as there is an internal
  98496. ** buffer that the pager module resizes using sqlite3_realloc().
  98497. */
  98498. db->nextPagesize = sqlite3Atoi(zRight);
  98499. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  98500. db->mallocFailed = 1;
  98501. }
  98502. }
  98503. break;
  98504. }
  98505. /*
  98506. ** PRAGMA [database.]secure_delete
  98507. ** PRAGMA [database.]secure_delete=ON/OFF
  98508. **
  98509. ** The first form reports the current setting for the
  98510. ** secure_delete flag. The second form changes the secure_delete
  98511. ** flag setting and reports thenew value.
  98512. */
  98513. case PragTyp_SECURE_DELETE: {
  98514. Btree *pBt = pDb->pBt;
  98515. int b = -1;
  98516. assert( pBt!=0 );
  98517. if( zRight ){
  98518. b = sqlite3GetBoolean(zRight, 0);
  98519. }
  98520. if( pId2->n==0 && b>=0 ){
  98521. int ii;
  98522. for(ii=0; ii<db->nDb; ii++){
  98523. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  98524. }
  98525. }
  98526. b = sqlite3BtreeSecureDelete(pBt, b);
  98527. returnSingleInt(pParse, "secure_delete", b);
  98528. break;
  98529. }
  98530. /*
  98531. ** PRAGMA [database.]max_page_count
  98532. ** PRAGMA [database.]max_page_count=N
  98533. **
  98534. ** The first form reports the current setting for the
  98535. ** maximum number of pages in the database file. The
  98536. ** second form attempts to change this setting. Both
  98537. ** forms return the current setting.
  98538. **
  98539. ** The absolute value of N is used. This is undocumented and might
  98540. ** change. The only purpose is to provide an easy way to test
  98541. ** the sqlite3AbsInt32() function.
  98542. **
  98543. ** PRAGMA [database.]page_count
  98544. **
  98545. ** Return the number of pages in the specified database.
  98546. */
  98547. case PragTyp_PAGE_COUNT: {
  98548. int iReg;
  98549. sqlite3CodeVerifySchema(pParse, iDb);
  98550. iReg = ++pParse->nMem;
  98551. if( sqlite3Tolower(zLeft[0])=='p' ){
  98552. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  98553. }else{
  98554. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  98555. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  98556. }
  98557. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  98558. sqlite3VdbeSetNumCols(v, 1);
  98559. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  98560. break;
  98561. }
  98562. /*
  98563. ** PRAGMA [database.]locking_mode
  98564. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  98565. */
  98566. case PragTyp_LOCKING_MODE: {
  98567. const char *zRet = "normal";
  98568. int eMode = getLockingMode(zRight);
  98569. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  98570. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  98571. ** the current default locking mode (which may be different to
  98572. ** the locking-mode of the main database).
  98573. */
  98574. eMode = db->dfltLockMode;
  98575. }else{
  98576. Pager *pPager;
  98577. if( pId2->n==0 ){
  98578. /* This indicates that no database name was specified as part
  98579. ** of the PRAGMA command. In this case the locking-mode must be
  98580. ** set on all attached databases, as well as the main db file.
  98581. **
  98582. ** Also, the sqlite3.dfltLockMode variable is set so that
  98583. ** any subsequently attached databases also use the specified
  98584. ** locking mode.
  98585. */
  98586. int ii;
  98587. assert(pDb==&db->aDb[0]);
  98588. for(ii=2; ii<db->nDb; ii++){
  98589. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  98590. sqlite3PagerLockingMode(pPager, eMode);
  98591. }
  98592. db->dfltLockMode = (u8)eMode;
  98593. }
  98594. pPager = sqlite3BtreePager(pDb->pBt);
  98595. eMode = sqlite3PagerLockingMode(pPager, eMode);
  98596. }
  98597. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  98598. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  98599. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  98600. zRet = "exclusive";
  98601. }
  98602. sqlite3VdbeSetNumCols(v, 1);
  98603. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  98604. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  98605. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  98606. break;
  98607. }
  98608. /*
  98609. ** PRAGMA [database.]journal_mode
  98610. ** PRAGMA [database.]journal_mode =
  98611. ** (delete|persist|off|truncate|memory|wal|off)
  98612. */
  98613. case PragTyp_JOURNAL_MODE: {
  98614. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  98615. int ii; /* Loop counter */
  98616. sqlite3VdbeSetNumCols(v, 1);
  98617. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  98618. if( zRight==0 ){
  98619. /* If there is no "=MODE" part of the pragma, do a query for the
  98620. ** current mode */
  98621. eMode = PAGER_JOURNALMODE_QUERY;
  98622. }else{
  98623. const char *zMode;
  98624. int n = sqlite3Strlen30(zRight);
  98625. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  98626. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  98627. }
  98628. if( !zMode ){
  98629. /* If the "=MODE" part does not match any known journal mode,
  98630. ** then do a query */
  98631. eMode = PAGER_JOURNALMODE_QUERY;
  98632. }
  98633. }
  98634. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  98635. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  98636. iDb = 0;
  98637. pId2->n = 1;
  98638. }
  98639. for(ii=db->nDb-1; ii>=0; ii--){
  98640. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  98641. sqlite3VdbeUsesBtree(v, ii);
  98642. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  98643. }
  98644. }
  98645. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  98646. break;
  98647. }
  98648. /*
  98649. ** PRAGMA [database.]journal_size_limit
  98650. ** PRAGMA [database.]journal_size_limit=N
  98651. **
  98652. ** Get or set the size limit on rollback journal files.
  98653. */
  98654. case PragTyp_JOURNAL_SIZE_LIMIT: {
  98655. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  98656. i64 iLimit = -2;
  98657. if( zRight ){
  98658. sqlite3DecOrHexToI64(zRight, &iLimit);
  98659. if( iLimit<-1 ) iLimit = -1;
  98660. }
  98661. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  98662. returnSingleInt(pParse, "journal_size_limit", iLimit);
  98663. break;
  98664. }
  98665. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  98666. /*
  98667. ** PRAGMA [database.]auto_vacuum
  98668. ** PRAGMA [database.]auto_vacuum=N
  98669. **
  98670. ** Get or set the value of the database 'auto-vacuum' parameter.
  98671. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  98672. */
  98673. #ifndef SQLITE_OMIT_AUTOVACUUM
  98674. case PragTyp_AUTO_VACUUM: {
  98675. Btree *pBt = pDb->pBt;
  98676. assert( pBt!=0 );
  98677. if( !zRight ){
  98678. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  98679. }else{
  98680. int eAuto = getAutoVacuum(zRight);
  98681. assert( eAuto>=0 && eAuto<=2 );
  98682. db->nextAutovac = (u8)eAuto;
  98683. /* Call SetAutoVacuum() to set initialize the internal auto and
  98684. ** incr-vacuum flags. This is required in case this connection
  98685. ** creates the database file. It is important that it is created
  98686. ** as an auto-vacuum capable db.
  98687. */
  98688. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  98689. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  98690. /* When setting the auto_vacuum mode to either "full" or
  98691. ** "incremental", write the value of meta[6] in the database
  98692. ** file. Before writing to meta[6], check that meta[3] indicates
  98693. ** that this really is an auto-vacuum capable database.
  98694. */
  98695. static const int iLn = VDBE_OFFSET_LINENO(2);
  98696. static const VdbeOpList setMeta6[] = {
  98697. { OP_Transaction, 0, 1, 0}, /* 0 */
  98698. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  98699. { OP_If, 1, 0, 0}, /* 2 */
  98700. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  98701. { OP_Integer, 0, 1, 0}, /* 4 */
  98702. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  98703. };
  98704. int iAddr;
  98705. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  98706. sqlite3VdbeChangeP1(v, iAddr, iDb);
  98707. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  98708. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  98709. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  98710. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  98711. sqlite3VdbeUsesBtree(v, iDb);
  98712. }
  98713. }
  98714. break;
  98715. }
  98716. #endif
  98717. /*
  98718. ** PRAGMA [database.]incremental_vacuum(N)
  98719. **
  98720. ** Do N steps of incremental vacuuming on a database.
  98721. */
  98722. #ifndef SQLITE_OMIT_AUTOVACUUM
  98723. case PragTyp_INCREMENTAL_VACUUM: {
  98724. int iLimit, addr;
  98725. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  98726. iLimit = 0x7fffffff;
  98727. }
  98728. sqlite3BeginWriteOperation(pParse, 0, iDb);
  98729. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  98730. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  98731. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  98732. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  98733. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  98734. sqlite3VdbeJumpHere(v, addr);
  98735. break;
  98736. }
  98737. #endif
  98738. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  98739. /*
  98740. ** PRAGMA [database.]cache_size
  98741. ** PRAGMA [database.]cache_size=N
  98742. **
  98743. ** The first form reports the current local setting for the
  98744. ** page cache size. The second form sets the local
  98745. ** page cache size value. If N is positive then that is the
  98746. ** number of pages in the cache. If N is negative, then the
  98747. ** number of pages is adjusted so that the cache uses -N kibibytes
  98748. ** of memory.
  98749. */
  98750. case PragTyp_CACHE_SIZE: {
  98751. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98752. if( !zRight ){
  98753. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  98754. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  98755. }else{
  98756. int size = sqlite3Atoi(zRight);
  98757. pDb->pSchema->cache_size = size;
  98758. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  98759. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  98760. }
  98761. break;
  98762. }
  98763. /*
  98764. ** PRAGMA [database.]mmap_size(N)
  98765. **
  98766. ** Used to set mapping size limit. The mapping size limit is
  98767. ** used to limit the aggregate size of all memory mapped regions of the
  98768. ** database file. If this parameter is set to zero, then memory mapping
  98769. ** is not used at all. If N is negative, then the default memory map
  98770. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  98771. ** The parameter N is measured in bytes.
  98772. **
  98773. ** This value is advisory. The underlying VFS is free to memory map
  98774. ** as little or as much as it wants. Except, if N is set to 0 then the
  98775. ** upper layers will never invoke the xFetch interfaces to the VFS.
  98776. */
  98777. case PragTyp_MMAP_SIZE: {
  98778. sqlite3_int64 sz;
  98779. #if SQLITE_MAX_MMAP_SIZE>0
  98780. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  98781. if( zRight ){
  98782. int ii;
  98783. sqlite3DecOrHexToI64(zRight, &sz);
  98784. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  98785. if( pId2->n==0 ) db->szMmap = sz;
  98786. for(ii=db->nDb-1; ii>=0; ii--){
  98787. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  98788. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  98789. }
  98790. }
  98791. }
  98792. sz = -1;
  98793. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  98794. #else
  98795. sz = 0;
  98796. rc = SQLITE_OK;
  98797. #endif
  98798. if( rc==SQLITE_OK ){
  98799. returnSingleInt(pParse, "mmap_size", sz);
  98800. }else if( rc!=SQLITE_NOTFOUND ){
  98801. pParse->nErr++;
  98802. pParse->rc = rc;
  98803. }
  98804. break;
  98805. }
  98806. /*
  98807. ** PRAGMA temp_store
  98808. ** PRAGMA temp_store = "default"|"memory"|"file"
  98809. **
  98810. ** Return or set the local value of the temp_store flag. Changing
  98811. ** the local value does not make changes to the disk file and the default
  98812. ** value will be restored the next time the database is opened.
  98813. **
  98814. ** Note that it is possible for the library compile-time options to
  98815. ** override this setting
  98816. */
  98817. case PragTyp_TEMP_STORE: {
  98818. if( !zRight ){
  98819. returnSingleInt(pParse, "temp_store", db->temp_store);
  98820. }else{
  98821. changeTempStorage(pParse, zRight);
  98822. }
  98823. break;
  98824. }
  98825. /*
  98826. ** PRAGMA temp_store_directory
  98827. ** PRAGMA temp_store_directory = ""|"directory_name"
  98828. **
  98829. ** Return or set the local value of the temp_store_directory flag. Changing
  98830. ** the value sets a specific directory to be used for temporary files.
  98831. ** Setting to a null string reverts to the default temporary directory search.
  98832. ** If temporary directory is changed, then invalidateTempStorage.
  98833. **
  98834. */
  98835. case PragTyp_TEMP_STORE_DIRECTORY: {
  98836. if( !zRight ){
  98837. if( sqlite3_temp_directory ){
  98838. sqlite3VdbeSetNumCols(v, 1);
  98839. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  98840. "temp_store_directory", SQLITE_STATIC);
  98841. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  98842. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  98843. }
  98844. }else{
  98845. #ifndef SQLITE_OMIT_WSD
  98846. if( zRight[0] ){
  98847. int res;
  98848. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  98849. if( rc!=SQLITE_OK || res==0 ){
  98850. sqlite3ErrorMsg(pParse, "not a writable directory");
  98851. goto pragma_out;
  98852. }
  98853. }
  98854. if( SQLITE_TEMP_STORE==0
  98855. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  98856. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  98857. ){
  98858. invalidateTempStorage(pParse);
  98859. }
  98860. sqlite3_free(sqlite3_temp_directory);
  98861. if( zRight[0] ){
  98862. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  98863. }else{
  98864. sqlite3_temp_directory = 0;
  98865. }
  98866. #endif /* SQLITE_OMIT_WSD */
  98867. }
  98868. break;
  98869. }
  98870. #if SQLITE_OS_WIN
  98871. /*
  98872. ** PRAGMA data_store_directory
  98873. ** PRAGMA data_store_directory = ""|"directory_name"
  98874. **
  98875. ** Return or set the local value of the data_store_directory flag. Changing
  98876. ** the value sets a specific directory to be used for database files that
  98877. ** were specified with a relative pathname. Setting to a null string reverts
  98878. ** to the default database directory, which for database files specified with
  98879. ** a relative path will probably be based on the current directory for the
  98880. ** process. Database file specified with an absolute path are not impacted
  98881. ** by this setting, regardless of its value.
  98882. **
  98883. */
  98884. case PragTyp_DATA_STORE_DIRECTORY: {
  98885. if( !zRight ){
  98886. if( sqlite3_data_directory ){
  98887. sqlite3VdbeSetNumCols(v, 1);
  98888. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  98889. "data_store_directory", SQLITE_STATIC);
  98890. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  98891. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  98892. }
  98893. }else{
  98894. #ifndef SQLITE_OMIT_WSD
  98895. if( zRight[0] ){
  98896. int res;
  98897. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  98898. if( rc!=SQLITE_OK || res==0 ){
  98899. sqlite3ErrorMsg(pParse, "not a writable directory");
  98900. goto pragma_out;
  98901. }
  98902. }
  98903. sqlite3_free(sqlite3_data_directory);
  98904. if( zRight[0] ){
  98905. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  98906. }else{
  98907. sqlite3_data_directory = 0;
  98908. }
  98909. #endif /* SQLITE_OMIT_WSD */
  98910. }
  98911. break;
  98912. }
  98913. #endif
  98914. #if SQLITE_ENABLE_LOCKING_STYLE
  98915. /*
  98916. ** PRAGMA [database.]lock_proxy_file
  98917. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  98918. **
  98919. ** Return or set the value of the lock_proxy_file flag. Changing
  98920. ** the value sets a specific file to be used for database access locks.
  98921. **
  98922. */
  98923. case PragTyp_LOCK_PROXY_FILE: {
  98924. if( !zRight ){
  98925. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  98926. char *proxy_file_path = NULL;
  98927. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  98928. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  98929. &proxy_file_path);
  98930. if( proxy_file_path ){
  98931. sqlite3VdbeSetNumCols(v, 1);
  98932. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  98933. "lock_proxy_file", SQLITE_STATIC);
  98934. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  98935. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  98936. }
  98937. }else{
  98938. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  98939. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  98940. int res;
  98941. if( zRight[0] ){
  98942. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  98943. zRight);
  98944. } else {
  98945. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  98946. NULL);
  98947. }
  98948. if( res!=SQLITE_OK ){
  98949. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  98950. goto pragma_out;
  98951. }
  98952. }
  98953. break;
  98954. }
  98955. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  98956. /*
  98957. ** PRAGMA [database.]synchronous
  98958. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  98959. **
  98960. ** Return or set the local value of the synchronous flag. Changing
  98961. ** the local value does not make changes to the disk file and the
  98962. ** default value will be restored the next time the database is
  98963. ** opened.
  98964. */
  98965. case PragTyp_SYNCHRONOUS: {
  98966. if( !zRight ){
  98967. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  98968. }else{
  98969. if( !db->autoCommit ){
  98970. sqlite3ErrorMsg(pParse,
  98971. "Safety level may not be changed inside a transaction");
  98972. }else{
  98973. int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
  98974. if( iLevel==0 ) iLevel = 1;
  98975. pDb->safety_level = iLevel;
  98976. setAllPagerFlags(db);
  98977. }
  98978. }
  98979. break;
  98980. }
  98981. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  98982. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  98983. case PragTyp_FLAG: {
  98984. if( zRight==0 ){
  98985. returnSingleInt(pParse, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
  98986. }else{
  98987. int mask = pPragma->iArg; /* Mask of bits to set or clear. */
  98988. if( db->autoCommit==0 ){
  98989. /* Foreign key support may not be enabled or disabled while not
  98990. ** in auto-commit mode. */
  98991. mask &= ~(SQLITE_ForeignKeys);
  98992. }
  98993. #if SQLITE_USER_AUTHENTICATION
  98994. if( db->auth.authLevel==UAUTH_User ){
  98995. /* Do not allow non-admin users to modify the schema arbitrarily */
  98996. mask &= ~(SQLITE_WriteSchema);
  98997. }
  98998. #endif
  98999. if( sqlite3GetBoolean(zRight, 0) ){
  99000. db->flags |= mask;
  99001. }else{
  99002. db->flags &= ~mask;
  99003. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  99004. }
  99005. /* Many of the flag-pragmas modify the code generated by the SQL
  99006. ** compiler (eg. count_changes). So add an opcode to expire all
  99007. ** compiled SQL statements after modifying a pragma value.
  99008. */
  99009. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  99010. setAllPagerFlags(db);
  99011. }
  99012. break;
  99013. }
  99014. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  99015. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  99016. /*
  99017. ** PRAGMA table_info(<table>)
  99018. **
  99019. ** Return a single row for each column of the named table. The columns of
  99020. ** the returned data set are:
  99021. **
  99022. ** cid: Column id (numbered from left to right, starting at 0)
  99023. ** name: Column name
  99024. ** type: Column declaration type.
  99025. ** notnull: True if 'NOT NULL' is part of column declaration
  99026. ** dflt_value: The default value for the column, if any.
  99027. */
  99028. case PragTyp_TABLE_INFO: if( zRight ){
  99029. Table *pTab;
  99030. pTab = sqlite3FindTable(db, zRight, zDb);
  99031. if( pTab ){
  99032. int i, k;
  99033. int nHidden = 0;
  99034. Column *pCol;
  99035. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  99036. sqlite3VdbeSetNumCols(v, 6);
  99037. pParse->nMem = 6;
  99038. sqlite3CodeVerifySchema(pParse, iDb);
  99039. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  99040. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  99041. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  99042. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  99043. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  99044. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  99045. sqlite3ViewGetColumnNames(pParse, pTab);
  99046. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  99047. if( IsHiddenColumn(pCol) ){
  99048. nHidden++;
  99049. continue;
  99050. }
  99051. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  99052. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  99053. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  99054. pCol->zType ? pCol->zType : "", 0);
  99055. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  99056. if( pCol->zDflt ){
  99057. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  99058. }else{
  99059. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  99060. }
  99061. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  99062. k = 0;
  99063. }else if( pPk==0 ){
  99064. k = 1;
  99065. }else{
  99066. for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
  99067. }
  99068. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  99069. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  99070. }
  99071. }
  99072. }
  99073. break;
  99074. case PragTyp_STATS: {
  99075. Index *pIdx;
  99076. HashElem *i;
  99077. v = sqlite3GetVdbe(pParse);
  99078. sqlite3VdbeSetNumCols(v, 4);
  99079. pParse->nMem = 4;
  99080. sqlite3CodeVerifySchema(pParse, iDb);
  99081. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  99082. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  99083. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  99084. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  99085. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  99086. Table *pTab = sqliteHashData(i);
  99087. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  99088. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  99089. sqlite3VdbeAddOp2(v, OP_Integer,
  99090. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  99091. sqlite3VdbeAddOp2(v, OP_Integer,
  99092. (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
  99093. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  99094. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99095. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  99096. sqlite3VdbeAddOp2(v, OP_Integer,
  99097. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  99098. sqlite3VdbeAddOp2(v, OP_Integer,
  99099. (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
  99100. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  99101. }
  99102. }
  99103. }
  99104. break;
  99105. case PragTyp_INDEX_INFO: if( zRight ){
  99106. Index *pIdx;
  99107. Table *pTab;
  99108. pIdx = sqlite3FindIndex(db, zRight, zDb);
  99109. if( pIdx ){
  99110. int i;
  99111. int mx;
  99112. if( pPragma->iArg ){
  99113. /* PRAGMA index_xinfo (newer version with more rows and columns) */
  99114. mx = pIdx->nColumn;
  99115. pParse->nMem = 6;
  99116. }else{
  99117. /* PRAGMA index_info (legacy version) */
  99118. mx = pIdx->nKeyCol;
  99119. pParse->nMem = 3;
  99120. }
  99121. pTab = pIdx->pTable;
  99122. sqlite3VdbeSetNumCols(v, pParse->nMem);
  99123. sqlite3CodeVerifySchema(pParse, iDb);
  99124. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  99125. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  99126. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  99127. if( pPragma->iArg ){
  99128. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "desc", SQLITE_STATIC);
  99129. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "coll", SQLITE_STATIC);
  99130. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "key", SQLITE_STATIC);
  99131. }
  99132. for(i=0; i<mx; i++){
  99133. i16 cnum = pIdx->aiColumn[i];
  99134. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  99135. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  99136. if( cnum<0 ){
  99137. sqlite3VdbeAddOp2(v, OP_Null, 0, 3);
  99138. }else{
  99139. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  99140. }
  99141. if( pPragma->iArg ){
  99142. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->aSortOrder[i], 4);
  99143. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, pIdx->azColl[i], 0);
  99144. sqlite3VdbeAddOp2(v, OP_Integer, i<pIdx->nKeyCol, 6);
  99145. }
  99146. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
  99147. }
  99148. }
  99149. }
  99150. break;
  99151. case PragTyp_INDEX_LIST: if( zRight ){
  99152. Index *pIdx;
  99153. Table *pTab;
  99154. int i;
  99155. pTab = sqlite3FindTable(db, zRight, zDb);
  99156. if( pTab ){
  99157. v = sqlite3GetVdbe(pParse);
  99158. sqlite3VdbeSetNumCols(v, 5);
  99159. pParse->nMem = 5;
  99160. sqlite3CodeVerifySchema(pParse, iDb);
  99161. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  99162. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  99163. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  99164. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "origin", SQLITE_STATIC);
  99165. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "partial", SQLITE_STATIC);
  99166. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  99167. const char *azOrigin[] = { "c", "u", "pk" };
  99168. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  99169. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  99170. sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
  99171. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, azOrigin[pIdx->idxType], 0);
  99172. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->pPartIdxWhere!=0, 5);
  99173. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
  99174. }
  99175. }
  99176. }
  99177. break;
  99178. case PragTyp_DATABASE_LIST: {
  99179. int i;
  99180. sqlite3VdbeSetNumCols(v, 3);
  99181. pParse->nMem = 3;
  99182. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  99183. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  99184. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  99185. for(i=0; i<db->nDb; i++){
  99186. if( db->aDb[i].pBt==0 ) continue;
  99187. assert( db->aDb[i].zName!=0 );
  99188. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  99189. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  99190. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  99191. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  99192. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  99193. }
  99194. }
  99195. break;
  99196. case PragTyp_COLLATION_LIST: {
  99197. int i = 0;
  99198. HashElem *p;
  99199. sqlite3VdbeSetNumCols(v, 2);
  99200. pParse->nMem = 2;
  99201. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  99202. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  99203. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  99204. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  99205. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  99206. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  99207. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  99208. }
  99209. }
  99210. break;
  99211. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  99212. #ifndef SQLITE_OMIT_FOREIGN_KEY
  99213. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  99214. FKey *pFK;
  99215. Table *pTab;
  99216. pTab = sqlite3FindTable(db, zRight, zDb);
  99217. if( pTab ){
  99218. v = sqlite3GetVdbe(pParse);
  99219. pFK = pTab->pFKey;
  99220. if( pFK ){
  99221. int i = 0;
  99222. sqlite3VdbeSetNumCols(v, 8);
  99223. pParse->nMem = 8;
  99224. sqlite3CodeVerifySchema(pParse, iDb);
  99225. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  99226. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  99227. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  99228. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  99229. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  99230. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  99231. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  99232. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  99233. while(pFK){
  99234. int j;
  99235. for(j=0; j<pFK->nCol; j++){
  99236. char *zCol = pFK->aCol[j].zCol;
  99237. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  99238. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  99239. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  99240. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  99241. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  99242. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  99243. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  99244. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  99245. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  99246. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  99247. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  99248. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  99249. }
  99250. ++i;
  99251. pFK = pFK->pNextFrom;
  99252. }
  99253. }
  99254. }
  99255. }
  99256. break;
  99257. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  99258. #ifndef SQLITE_OMIT_FOREIGN_KEY
  99259. #ifndef SQLITE_OMIT_TRIGGER
  99260. case PragTyp_FOREIGN_KEY_CHECK: {
  99261. FKey *pFK; /* A foreign key constraint */
  99262. Table *pTab; /* Child table contain "REFERENCES" keyword */
  99263. Table *pParent; /* Parent table that child points to */
  99264. Index *pIdx; /* Index in the parent table */
  99265. int i; /* Loop counter: Foreign key number for pTab */
  99266. int j; /* Loop counter: Field of the foreign key */
  99267. HashElem *k; /* Loop counter: Next table in schema */
  99268. int x; /* result variable */
  99269. int regResult; /* 3 registers to hold a result row */
  99270. int regKey; /* Register to hold key for checking the FK */
  99271. int regRow; /* Registers to hold a row from pTab */
  99272. int addrTop; /* Top of a loop checking foreign keys */
  99273. int addrOk; /* Jump here if the key is OK */
  99274. int *aiCols; /* child to parent column mapping */
  99275. regResult = pParse->nMem+1;
  99276. pParse->nMem += 4;
  99277. regKey = ++pParse->nMem;
  99278. regRow = ++pParse->nMem;
  99279. v = sqlite3GetVdbe(pParse);
  99280. sqlite3VdbeSetNumCols(v, 4);
  99281. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  99282. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  99283. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  99284. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  99285. sqlite3CodeVerifySchema(pParse, iDb);
  99286. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  99287. while( k ){
  99288. if( zRight ){
  99289. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  99290. k = 0;
  99291. }else{
  99292. pTab = (Table*)sqliteHashData(k);
  99293. k = sqliteHashNext(k);
  99294. }
  99295. if( pTab==0 || pTab->pFKey==0 ) continue;
  99296. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  99297. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  99298. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  99299. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  99300. P4_TRANSIENT);
  99301. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  99302. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  99303. if( pParent==0 ) continue;
  99304. pIdx = 0;
  99305. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  99306. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  99307. if( x==0 ){
  99308. if( pIdx==0 ){
  99309. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  99310. }else{
  99311. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  99312. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  99313. }
  99314. }else{
  99315. k = 0;
  99316. break;
  99317. }
  99318. }
  99319. assert( pParse->nErr>0 || pFK==0 );
  99320. if( pFK ) break;
  99321. if( pParse->nTab<i ) pParse->nTab = i;
  99322. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  99323. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  99324. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  99325. pIdx = 0;
  99326. aiCols = 0;
  99327. if( pParent ){
  99328. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  99329. assert( x==0 );
  99330. }
  99331. addrOk = sqlite3VdbeMakeLabel(v);
  99332. if( pParent && pIdx==0 ){
  99333. int iKey = pFK->aCol[0].iFrom;
  99334. assert( iKey>=0 && iKey<pTab->nCol );
  99335. if( iKey!=pTab->iPKey ){
  99336. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  99337. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  99338. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
  99339. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  99340. sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  99341. }else{
  99342. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  99343. }
  99344. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  99345. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  99346. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  99347. }else{
  99348. for(j=0; j<pFK->nCol; j++){
  99349. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  99350. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  99351. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  99352. }
  99353. if( pParent ){
  99354. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  99355. sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
  99356. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  99357. VdbeCoverage(v);
  99358. }
  99359. }
  99360. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  99361. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  99362. pFK->zTo, P4_TRANSIENT);
  99363. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  99364. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  99365. sqlite3VdbeResolveLabel(v, addrOk);
  99366. sqlite3DbFree(db, aiCols);
  99367. }
  99368. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  99369. sqlite3VdbeJumpHere(v, addrTop);
  99370. }
  99371. }
  99372. break;
  99373. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  99374. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  99375. #ifndef NDEBUG
  99376. case PragTyp_PARSER_TRACE: {
  99377. if( zRight ){
  99378. if( sqlite3GetBoolean(zRight, 0) ){
  99379. sqlite3ParserTrace(stderr, "parser: ");
  99380. }else{
  99381. sqlite3ParserTrace(0, 0);
  99382. }
  99383. }
  99384. }
  99385. break;
  99386. #endif
  99387. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  99388. ** used will be case sensitive or not depending on the RHS.
  99389. */
  99390. case PragTyp_CASE_SENSITIVE_LIKE: {
  99391. if( zRight ){
  99392. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  99393. }
  99394. }
  99395. break;
  99396. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  99397. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  99398. #endif
  99399. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  99400. /* Pragma "quick_check" is reduced version of
  99401. ** integrity_check designed to detect most database corruption
  99402. ** without most of the overhead of a full integrity-check.
  99403. */
  99404. case PragTyp_INTEGRITY_CHECK: {
  99405. int i, j, addr, mxErr;
  99406. /* Code that appears at the end of the integrity check. If no error
  99407. ** messages have been generated, output OK. Otherwise output the
  99408. ** error message
  99409. */
  99410. static const int iLn = VDBE_OFFSET_LINENO(2);
  99411. static const VdbeOpList endCode[] = {
  99412. { OP_IfNeg, 1, 0, 0}, /* 0 */
  99413. { OP_String8, 0, 3, 0}, /* 1 */
  99414. { OP_ResultRow, 3, 1, 0},
  99415. };
  99416. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  99417. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  99418. ** then iDb is set to the index of the database identified by <db>.
  99419. ** In this case, the integrity of database iDb only is verified by
  99420. ** the VDBE created below.
  99421. **
  99422. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  99423. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  99424. ** to -1 here, to indicate that the VDBE should verify the integrity
  99425. ** of all attached databases. */
  99426. assert( iDb>=0 );
  99427. assert( iDb==0 || pId2->z );
  99428. if( pId2->z==0 ) iDb = -1;
  99429. /* Initialize the VDBE program */
  99430. pParse->nMem = 6;
  99431. sqlite3VdbeSetNumCols(v, 1);
  99432. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  99433. /* Set the maximum error count */
  99434. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  99435. if( zRight ){
  99436. sqlite3GetInt32(zRight, &mxErr);
  99437. if( mxErr<=0 ){
  99438. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  99439. }
  99440. }
  99441. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  99442. /* Do an integrity check on each database file */
  99443. for(i=0; i<db->nDb; i++){
  99444. HashElem *x;
  99445. Hash *pTbls;
  99446. int cnt = 0;
  99447. if( OMIT_TEMPDB && i==1 ) continue;
  99448. if( iDb>=0 && i!=iDb ) continue;
  99449. sqlite3CodeVerifySchema(pParse, i);
  99450. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  99451. VdbeCoverage(v);
  99452. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  99453. sqlite3VdbeJumpHere(v, addr);
  99454. /* Do an integrity check of the B-Tree
  99455. **
  99456. ** Begin by filling registers 2, 3, ... with the root pages numbers
  99457. ** for all tables and indices in the database.
  99458. */
  99459. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  99460. pTbls = &db->aDb[i].pSchema->tblHash;
  99461. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  99462. Table *pTab = sqliteHashData(x);
  99463. Index *pIdx;
  99464. if( HasRowid(pTab) ){
  99465. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  99466. VdbeComment((v, "%s", pTab->zName));
  99467. cnt++;
  99468. }
  99469. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99470. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  99471. VdbeComment((v, "%s", pIdx->zName));
  99472. cnt++;
  99473. }
  99474. }
  99475. /* Make sure sufficient number of registers have been allocated */
  99476. pParse->nMem = MAX( pParse->nMem, cnt+8 );
  99477. /* Do the b-tree integrity checks */
  99478. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  99479. sqlite3VdbeChangeP5(v, (u8)i);
  99480. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  99481. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  99482. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  99483. P4_DYNAMIC);
  99484. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  99485. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  99486. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  99487. sqlite3VdbeJumpHere(v, addr);
  99488. /* Make sure all the indices are constructed correctly.
  99489. */
  99490. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  99491. Table *pTab = sqliteHashData(x);
  99492. Index *pIdx, *pPk;
  99493. Index *pPrior = 0;
  99494. int loopTop;
  99495. int iDataCur, iIdxCur;
  99496. int r1 = -1;
  99497. if( pTab->pIndex==0 ) continue;
  99498. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  99499. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  99500. VdbeCoverage(v);
  99501. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  99502. sqlite3VdbeJumpHere(v, addr);
  99503. sqlite3ExprCacheClear(pParse);
  99504. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
  99505. 1, 0, &iDataCur, &iIdxCur);
  99506. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  99507. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  99508. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  99509. }
  99510. pParse->nMem = MAX(pParse->nMem, 8+j);
  99511. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  99512. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  99513. /* Verify that all NOT NULL columns really are NOT NULL */
  99514. for(j=0; j<pTab->nCol; j++){
  99515. char *zErr;
  99516. int jmp2, jmp3;
  99517. if( j==pTab->iPKey ) continue;
  99518. if( pTab->aCol[j].notNull==0 ) continue;
  99519. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  99520. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  99521. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  99522. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  99523. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  99524. pTab->aCol[j].zName);
  99525. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  99526. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  99527. jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  99528. sqlite3VdbeAddOp0(v, OP_Halt);
  99529. sqlite3VdbeJumpHere(v, jmp2);
  99530. sqlite3VdbeJumpHere(v, jmp3);
  99531. }
  99532. /* Validate index entries for the current row */
  99533. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  99534. int jmp2, jmp3, jmp4, jmp5;
  99535. int ckUniq = sqlite3VdbeMakeLabel(v);
  99536. if( pPk==pIdx ) continue;
  99537. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  99538. pPrior, r1);
  99539. pPrior = pIdx;
  99540. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  99541. /* Verify that an index entry exists for the current table row */
  99542. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  99543. pIdx->nColumn); VdbeCoverage(v);
  99544. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  99545. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
  99546. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  99547. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  99548. " missing from index ", P4_STATIC);
  99549. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  99550. jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  99551. pIdx->zName, P4_TRANSIENT);
  99552. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  99553. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  99554. jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  99555. sqlite3VdbeAddOp0(v, OP_Halt);
  99556. sqlite3VdbeJumpHere(v, jmp2);
  99557. /* For UNIQUE indexes, verify that only one entry exists with the
  99558. ** current key. The entry is unique if (1) any column is NULL
  99559. ** or (2) the next entry has a different key */
  99560. if( IsUniqueIndex(pIdx) ){
  99561. int uniqOk = sqlite3VdbeMakeLabel(v);
  99562. int jmp6;
  99563. int kk;
  99564. for(kk=0; kk<pIdx->nKeyCol; kk++){
  99565. int iCol = pIdx->aiColumn[kk];
  99566. assert( iCol>=0 && iCol<pTab->nCol );
  99567. if( pTab->aCol[iCol].notNull ) continue;
  99568. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  99569. VdbeCoverage(v);
  99570. }
  99571. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  99572. sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
  99573. sqlite3VdbeJumpHere(v, jmp6);
  99574. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  99575. pIdx->nKeyCol); VdbeCoverage(v);
  99576. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  99577. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  99578. "non-unique entry in index ", P4_STATIC);
  99579. sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
  99580. sqlite3VdbeResolveLabel(v, uniqOk);
  99581. }
  99582. sqlite3VdbeJumpHere(v, jmp4);
  99583. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  99584. }
  99585. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  99586. sqlite3VdbeJumpHere(v, loopTop-1);
  99587. #ifndef SQLITE_OMIT_BTREECOUNT
  99588. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  99589. "wrong # of entries in index ", P4_STATIC);
  99590. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  99591. if( pPk==pIdx ) continue;
  99592. addr = sqlite3VdbeCurrentAddr(v);
  99593. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  99594. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  99595. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  99596. sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
  99597. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  99598. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  99599. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  99600. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  99601. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  99602. }
  99603. #endif /* SQLITE_OMIT_BTREECOUNT */
  99604. }
  99605. }
  99606. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  99607. sqlite3VdbeChangeP3(v, addr, -mxErr);
  99608. sqlite3VdbeJumpHere(v, addr);
  99609. sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
  99610. }
  99611. break;
  99612. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  99613. #ifndef SQLITE_OMIT_UTF16
  99614. /*
  99615. ** PRAGMA encoding
  99616. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  99617. **
  99618. ** In its first form, this pragma returns the encoding of the main
  99619. ** database. If the database is not initialized, it is initialized now.
  99620. **
  99621. ** The second form of this pragma is a no-op if the main database file
  99622. ** has not already been initialized. In this case it sets the default
  99623. ** encoding that will be used for the main database file if a new file
  99624. ** is created. If an existing main database file is opened, then the
  99625. ** default text encoding for the existing database is used.
  99626. **
  99627. ** In all cases new databases created using the ATTACH command are
  99628. ** created to use the same default text encoding as the main database. If
  99629. ** the main database has not been initialized and/or created when ATTACH
  99630. ** is executed, this is done before the ATTACH operation.
  99631. **
  99632. ** In the second form this pragma sets the text encoding to be used in
  99633. ** new database files created using this database handle. It is only
  99634. ** useful if invoked immediately after the main database i
  99635. */
  99636. case PragTyp_ENCODING: {
  99637. static const struct EncName {
  99638. char *zName;
  99639. u8 enc;
  99640. } encnames[] = {
  99641. { "UTF8", SQLITE_UTF8 },
  99642. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  99643. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  99644. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  99645. { "UTF16le", SQLITE_UTF16LE },
  99646. { "UTF16be", SQLITE_UTF16BE },
  99647. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  99648. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  99649. { 0, 0 }
  99650. };
  99651. const struct EncName *pEnc;
  99652. if( !zRight ){ /* "PRAGMA encoding" */
  99653. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  99654. sqlite3VdbeSetNumCols(v, 1);
  99655. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  99656. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  99657. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  99658. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  99659. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  99660. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  99661. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  99662. }else{ /* "PRAGMA encoding = XXX" */
  99663. /* Only change the value of sqlite.enc if the database handle is not
  99664. ** initialized. If the main database exists, the new sqlite.enc value
  99665. ** will be overwritten when the schema is next loaded. If it does not
  99666. ** already exists, it will be created to use the new encoding value.
  99667. */
  99668. if(
  99669. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  99670. DbHasProperty(db, 0, DB_Empty)
  99671. ){
  99672. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  99673. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  99674. SCHEMA_ENC(db) = ENC(db) =
  99675. pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  99676. break;
  99677. }
  99678. }
  99679. if( !pEnc->zName ){
  99680. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  99681. }
  99682. }
  99683. }
  99684. }
  99685. break;
  99686. #endif /* SQLITE_OMIT_UTF16 */
  99687. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  99688. /*
  99689. ** PRAGMA [database.]schema_version
  99690. ** PRAGMA [database.]schema_version = <integer>
  99691. **
  99692. ** PRAGMA [database.]user_version
  99693. ** PRAGMA [database.]user_version = <integer>
  99694. **
  99695. ** PRAGMA [database.]freelist_count = <integer>
  99696. **
  99697. ** PRAGMA [database.]application_id
  99698. ** PRAGMA [database.]application_id = <integer>
  99699. **
  99700. ** The pragma's schema_version and user_version are used to set or get
  99701. ** the value of the schema-version and user-version, respectively. Both
  99702. ** the schema-version and the user-version are 32-bit signed integers
  99703. ** stored in the database header.
  99704. **
  99705. ** The schema-cookie is usually only manipulated internally by SQLite. It
  99706. ** is incremented by SQLite whenever the database schema is modified (by
  99707. ** creating or dropping a table or index). The schema version is used by
  99708. ** SQLite each time a query is executed to ensure that the internal cache
  99709. ** of the schema used when compiling the SQL query matches the schema of
  99710. ** the database against which the compiled query is actually executed.
  99711. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  99712. ** the schema-version is potentially dangerous and may lead to program
  99713. ** crashes or database corruption. Use with caution!
  99714. **
  99715. ** The user-version is not used internally by SQLite. It may be used by
  99716. ** applications for any purpose.
  99717. */
  99718. case PragTyp_HEADER_VALUE: {
  99719. int iCookie = pPragma->iArg; /* Which cookie to read or write */
  99720. sqlite3VdbeUsesBtree(v, iDb);
  99721. if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
  99722. /* Write the specified cookie value */
  99723. static const VdbeOpList setCookie[] = {
  99724. { OP_Transaction, 0, 1, 0}, /* 0 */
  99725. { OP_Integer, 0, 1, 0}, /* 1 */
  99726. { OP_SetCookie, 0, 0, 1}, /* 2 */
  99727. };
  99728. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  99729. sqlite3VdbeChangeP1(v, addr, iDb);
  99730. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  99731. sqlite3VdbeChangeP1(v, addr+2, iDb);
  99732. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  99733. }else{
  99734. /* Read the specified cookie value */
  99735. static const VdbeOpList readCookie[] = {
  99736. { OP_Transaction, 0, 0, 0}, /* 0 */
  99737. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  99738. { OP_ResultRow, 1, 1, 0}
  99739. };
  99740. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
  99741. sqlite3VdbeChangeP1(v, addr, iDb);
  99742. sqlite3VdbeChangeP1(v, addr+1, iDb);
  99743. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  99744. sqlite3VdbeSetNumCols(v, 1);
  99745. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  99746. }
  99747. }
  99748. break;
  99749. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  99750. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  99751. /*
  99752. ** PRAGMA compile_options
  99753. **
  99754. ** Return the names of all compile-time options used in this build,
  99755. ** one option per row.
  99756. */
  99757. case PragTyp_COMPILE_OPTIONS: {
  99758. int i = 0;
  99759. const char *zOpt;
  99760. sqlite3VdbeSetNumCols(v, 1);
  99761. pParse->nMem = 1;
  99762. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  99763. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  99764. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  99765. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  99766. }
  99767. }
  99768. break;
  99769. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  99770. #ifndef SQLITE_OMIT_WAL
  99771. /*
  99772. ** PRAGMA [database.]wal_checkpoint = passive|full|restart|truncate
  99773. **
  99774. ** Checkpoint the database.
  99775. */
  99776. case PragTyp_WAL_CHECKPOINT: {
  99777. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  99778. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  99779. if( zRight ){
  99780. if( sqlite3StrICmp(zRight, "full")==0 ){
  99781. eMode = SQLITE_CHECKPOINT_FULL;
  99782. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  99783. eMode = SQLITE_CHECKPOINT_RESTART;
  99784. }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
  99785. eMode = SQLITE_CHECKPOINT_TRUNCATE;
  99786. }
  99787. }
  99788. sqlite3VdbeSetNumCols(v, 3);
  99789. pParse->nMem = 3;
  99790. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  99791. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  99792. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  99793. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  99794. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  99795. }
  99796. break;
  99797. /*
  99798. ** PRAGMA wal_autocheckpoint
  99799. ** PRAGMA wal_autocheckpoint = N
  99800. **
  99801. ** Configure a database connection to automatically checkpoint a database
  99802. ** after accumulating N frames in the log. Or query for the current value
  99803. ** of N.
  99804. */
  99805. case PragTyp_WAL_AUTOCHECKPOINT: {
  99806. if( zRight ){
  99807. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  99808. }
  99809. returnSingleInt(pParse, "wal_autocheckpoint",
  99810. db->xWalCallback==sqlite3WalDefaultHook ?
  99811. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  99812. }
  99813. break;
  99814. #endif
  99815. /*
  99816. ** PRAGMA shrink_memory
  99817. **
  99818. ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
  99819. ** connection on which it is invoked to free up as much memory as it
  99820. ** can, by calling sqlite3_db_release_memory().
  99821. */
  99822. case PragTyp_SHRINK_MEMORY: {
  99823. sqlite3_db_release_memory(db);
  99824. break;
  99825. }
  99826. /*
  99827. ** PRAGMA busy_timeout
  99828. ** PRAGMA busy_timeout = N
  99829. **
  99830. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  99831. ** if one is set. If no busy handler or a different busy handler is set
  99832. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  99833. ** disables the timeout.
  99834. */
  99835. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  99836. assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
  99837. if( zRight ){
  99838. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  99839. }
  99840. returnSingleInt(pParse, "timeout", db->busyTimeout);
  99841. break;
  99842. }
  99843. /*
  99844. ** PRAGMA soft_heap_limit
  99845. ** PRAGMA soft_heap_limit = N
  99846. **
  99847. ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
  99848. ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
  99849. ** specified and is a non-negative integer.
  99850. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
  99851. ** returns the same integer that would be returned by the
  99852. ** sqlite3_soft_heap_limit64(-1) C-language function.
  99853. */
  99854. case PragTyp_SOFT_HEAP_LIMIT: {
  99855. sqlite3_int64 N;
  99856. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  99857. sqlite3_soft_heap_limit64(N);
  99858. }
  99859. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  99860. break;
  99861. }
  99862. /*
  99863. ** PRAGMA threads
  99864. ** PRAGMA threads = N
  99865. **
  99866. ** Configure the maximum number of worker threads. Return the new
  99867. ** maximum, which might be less than requested.
  99868. */
  99869. case PragTyp_THREADS: {
  99870. sqlite3_int64 N;
  99871. if( zRight
  99872. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  99873. && N>=0
  99874. ){
  99875. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  99876. }
  99877. returnSingleInt(pParse, "threads",
  99878. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  99879. break;
  99880. }
  99881. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  99882. /*
  99883. ** Report the current state of file logs for all databases
  99884. */
  99885. case PragTyp_LOCK_STATUS: {
  99886. static const char *const azLockName[] = {
  99887. "unlocked", "shared", "reserved", "pending", "exclusive"
  99888. };
  99889. int i;
  99890. sqlite3VdbeSetNumCols(v, 2);
  99891. pParse->nMem = 2;
  99892. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  99893. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  99894. for(i=0; i<db->nDb; i++){
  99895. Btree *pBt;
  99896. const char *zState = "unknown";
  99897. int j;
  99898. if( db->aDb[i].zName==0 ) continue;
  99899. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  99900. pBt = db->aDb[i].pBt;
  99901. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  99902. zState = "closed";
  99903. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  99904. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  99905. zState = azLockName[j];
  99906. }
  99907. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  99908. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  99909. }
  99910. break;
  99911. }
  99912. #endif
  99913. #ifdef SQLITE_HAS_CODEC
  99914. case PragTyp_KEY: {
  99915. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  99916. break;
  99917. }
  99918. case PragTyp_REKEY: {
  99919. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  99920. break;
  99921. }
  99922. case PragTyp_HEXKEY: {
  99923. if( zRight ){
  99924. u8 iByte;
  99925. int i;
  99926. char zKey[40];
  99927. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  99928. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  99929. if( (i&1)!=0 ) zKey[i/2] = iByte;
  99930. }
  99931. if( (zLeft[3] & 0xf)==0xb ){
  99932. sqlite3_key_v2(db, zDb, zKey, i/2);
  99933. }else{
  99934. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  99935. }
  99936. }
  99937. break;
  99938. }
  99939. #endif
  99940. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  99941. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  99942. #ifdef SQLITE_HAS_CODEC
  99943. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  99944. sqlite3_activate_see(&zRight[4]);
  99945. }
  99946. #endif
  99947. #ifdef SQLITE_ENABLE_CEROD
  99948. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  99949. sqlite3_activate_cerod(&zRight[6]);
  99950. }
  99951. #endif
  99952. }
  99953. break;
  99954. #endif
  99955. } /* End of the PRAGMA switch */
  99956. pragma_out:
  99957. sqlite3DbFree(db, zLeft);
  99958. sqlite3DbFree(db, zRight);
  99959. }
  99960. #endif /* SQLITE_OMIT_PRAGMA */
  99961. /************** End of pragma.c **********************************************/
  99962. /************** Begin file prepare.c *****************************************/
  99963. /*
  99964. ** 2005 May 25
  99965. **
  99966. ** The author disclaims copyright to this source code. In place of
  99967. ** a legal notice, here is a blessing:
  99968. **
  99969. ** May you do good and not evil.
  99970. ** May you find forgiveness for yourself and forgive others.
  99971. ** May you share freely, never taking more than you give.
  99972. **
  99973. *************************************************************************
  99974. ** This file contains the implementation of the sqlite3_prepare()
  99975. ** interface, and routines that contribute to loading the database schema
  99976. ** from disk.
  99977. */
  99978. /* #include "sqliteInt.h" */
  99979. /*
  99980. ** Fill the InitData structure with an error message that indicates
  99981. ** that the database is corrupt.
  99982. */
  99983. static void corruptSchema(
  99984. InitData *pData, /* Initialization context */
  99985. const char *zObj, /* Object being parsed at the point of error */
  99986. const char *zExtra /* Error information */
  99987. ){
  99988. sqlite3 *db = pData->db;
  99989. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  99990. char *z;
  99991. if( zObj==0 ) zObj = "?";
  99992. z = sqlite3_mprintf("malformed database schema (%s)", zObj);
  99993. if( z && zExtra ) z = sqlite3_mprintf("%z - %s", z, zExtra);
  99994. sqlite3DbFree(db, *pData->pzErrMsg);
  99995. *pData->pzErrMsg = z;
  99996. if( z==0 ) db->mallocFailed = 1;
  99997. }
  99998. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  99999. }
  100000. /*
  100001. ** This is the callback routine for the code that initializes the
  100002. ** database. See sqlite3Init() below for additional information.
  100003. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  100004. **
  100005. ** Each callback contains the following information:
  100006. **
  100007. ** argv[0] = name of thing being created
  100008. ** argv[1] = root page number for table or index. 0 for trigger or view.
  100009. ** argv[2] = SQL text for the CREATE statement.
  100010. **
  100011. */
  100012. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  100013. InitData *pData = (InitData*)pInit;
  100014. sqlite3 *db = pData->db;
  100015. int iDb = pData->iDb;
  100016. assert( argc==3 );
  100017. UNUSED_PARAMETER2(NotUsed, argc);
  100018. assert( sqlite3_mutex_held(db->mutex) );
  100019. DbClearProperty(db, iDb, DB_Empty);
  100020. if( db->mallocFailed ){
  100021. corruptSchema(pData, argv[0], 0);
  100022. return 1;
  100023. }
  100024. assert( iDb>=0 && iDb<db->nDb );
  100025. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  100026. if( argv[1]==0 ){
  100027. corruptSchema(pData, argv[0], 0);
  100028. }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
  100029. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  100030. ** But because db->init.busy is set to 1, no VDBE code is generated
  100031. ** or executed. All the parser does is build the internal data
  100032. ** structures that describe the table, index, or view.
  100033. */
  100034. int rc;
  100035. sqlite3_stmt *pStmt;
  100036. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  100037. assert( db->init.busy );
  100038. db->init.iDb = iDb;
  100039. db->init.newTnum = sqlite3Atoi(argv[1]);
  100040. db->init.orphanTrigger = 0;
  100041. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  100042. rc = db->errCode;
  100043. assert( (rc&0xFF)==(rcp&0xFF) );
  100044. db->init.iDb = 0;
  100045. if( SQLITE_OK!=rc ){
  100046. if( db->init.orphanTrigger ){
  100047. assert( iDb==1 );
  100048. }else{
  100049. pData->rc = rc;
  100050. if( rc==SQLITE_NOMEM ){
  100051. db->mallocFailed = 1;
  100052. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  100053. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  100054. }
  100055. }
  100056. }
  100057. sqlite3_finalize(pStmt);
  100058. }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
  100059. corruptSchema(pData, argv[0], 0);
  100060. }else{
  100061. /* If the SQL column is blank it means this is an index that
  100062. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  100063. ** constraint for a CREATE TABLE. The index should have already
  100064. ** been created when we processed the CREATE TABLE. All we have
  100065. ** to do here is record the root page number for that index.
  100066. */
  100067. Index *pIndex;
  100068. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  100069. if( pIndex==0 ){
  100070. /* This can occur if there exists an index on a TEMP table which
  100071. ** has the same name as another index on a permanent index. Since
  100072. ** the permanent table is hidden by the TEMP table, we can also
  100073. ** safely ignore the index on the permanent table.
  100074. */
  100075. /* Do Nothing */;
  100076. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  100077. corruptSchema(pData, argv[0], "invalid rootpage");
  100078. }
  100079. }
  100080. return 0;
  100081. }
  100082. /*
  100083. ** Attempt to read the database schema and initialize internal
  100084. ** data structures for a single database file. The index of the
  100085. ** database file is given by iDb. iDb==0 is used for the main
  100086. ** database. iDb==1 should never be used. iDb>=2 is used for
  100087. ** auxiliary databases. Return one of the SQLITE_ error codes to
  100088. ** indicate success or failure.
  100089. */
  100090. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  100091. int rc;
  100092. int i;
  100093. #ifndef SQLITE_OMIT_DEPRECATED
  100094. int size;
  100095. #endif
  100096. Table *pTab;
  100097. Db *pDb;
  100098. char const *azArg[4];
  100099. int meta[5];
  100100. InitData initData;
  100101. char const *zMasterSchema;
  100102. char const *zMasterName;
  100103. int openedTransaction = 0;
  100104. /*
  100105. ** The master database table has a structure like this
  100106. */
  100107. static const char master_schema[] =
  100108. "CREATE TABLE sqlite_master(\n"
  100109. " type text,\n"
  100110. " name text,\n"
  100111. " tbl_name text,\n"
  100112. " rootpage integer,\n"
  100113. " sql text\n"
  100114. ")"
  100115. ;
  100116. #ifndef SQLITE_OMIT_TEMPDB
  100117. static const char temp_master_schema[] =
  100118. "CREATE TEMP TABLE sqlite_temp_master(\n"
  100119. " type text,\n"
  100120. " name text,\n"
  100121. " tbl_name text,\n"
  100122. " rootpage integer,\n"
  100123. " sql text\n"
  100124. ")"
  100125. ;
  100126. #else
  100127. #define temp_master_schema 0
  100128. #endif
  100129. assert( iDb>=0 && iDb<db->nDb );
  100130. assert( db->aDb[iDb].pSchema );
  100131. assert( sqlite3_mutex_held(db->mutex) );
  100132. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  100133. /* zMasterSchema and zInitScript are set to point at the master schema
  100134. ** and initialisation script appropriate for the database being
  100135. ** initialized. zMasterName is the name of the master table.
  100136. */
  100137. if( !OMIT_TEMPDB && iDb==1 ){
  100138. zMasterSchema = temp_master_schema;
  100139. }else{
  100140. zMasterSchema = master_schema;
  100141. }
  100142. zMasterName = SCHEMA_TABLE(iDb);
  100143. /* Construct the schema tables. */
  100144. azArg[0] = zMasterName;
  100145. azArg[1] = "1";
  100146. azArg[2] = zMasterSchema;
  100147. azArg[3] = 0;
  100148. initData.db = db;
  100149. initData.iDb = iDb;
  100150. initData.rc = SQLITE_OK;
  100151. initData.pzErrMsg = pzErrMsg;
  100152. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  100153. if( initData.rc ){
  100154. rc = initData.rc;
  100155. goto error_out;
  100156. }
  100157. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  100158. if( ALWAYS(pTab) ){
  100159. pTab->tabFlags |= TF_Readonly;
  100160. }
  100161. /* Create a cursor to hold the database open
  100162. */
  100163. pDb = &db->aDb[iDb];
  100164. if( pDb->pBt==0 ){
  100165. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  100166. DbSetProperty(db, 1, DB_SchemaLoaded);
  100167. }
  100168. return SQLITE_OK;
  100169. }
  100170. /* If there is not already a read-only (or read-write) transaction opened
  100171. ** on the b-tree database, open one now. If a transaction is opened, it
  100172. ** will be closed before this function returns. */
  100173. sqlite3BtreeEnter(pDb->pBt);
  100174. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  100175. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  100176. if( rc!=SQLITE_OK ){
  100177. sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
  100178. goto initone_error_out;
  100179. }
  100180. openedTransaction = 1;
  100181. }
  100182. /* Get the database meta information.
  100183. **
  100184. ** Meta values are as follows:
  100185. ** meta[0] Schema cookie. Changes with each schema change.
  100186. ** meta[1] File format of schema layer.
  100187. ** meta[2] Size of the page cache.
  100188. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  100189. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  100190. ** meta[5] User version
  100191. ** meta[6] Incremental vacuum mode
  100192. ** meta[7] unused
  100193. ** meta[8] unused
  100194. ** meta[9] unused
  100195. **
  100196. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  100197. ** the possible values of meta[4].
  100198. */
  100199. for(i=0; i<ArraySize(meta); i++){
  100200. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  100201. }
  100202. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  100203. /* If opening a non-empty database, check the text encoding. For the
  100204. ** main database, set sqlite3.enc to the encoding of the main database.
  100205. ** For an attached db, it is an error if the encoding is not the same
  100206. ** as sqlite3.enc.
  100207. */
  100208. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  100209. if( iDb==0 ){
  100210. #ifndef SQLITE_OMIT_UTF16
  100211. u8 encoding;
  100212. /* If opening the main database, set ENC(db). */
  100213. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  100214. if( encoding==0 ) encoding = SQLITE_UTF8;
  100215. ENC(db) = encoding;
  100216. #else
  100217. ENC(db) = SQLITE_UTF8;
  100218. #endif
  100219. }else{
  100220. /* If opening an attached database, the encoding much match ENC(db) */
  100221. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  100222. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  100223. " text encoding as main database");
  100224. rc = SQLITE_ERROR;
  100225. goto initone_error_out;
  100226. }
  100227. }
  100228. }else{
  100229. DbSetProperty(db, iDb, DB_Empty);
  100230. }
  100231. pDb->pSchema->enc = ENC(db);
  100232. if( pDb->pSchema->cache_size==0 ){
  100233. #ifndef SQLITE_OMIT_DEPRECATED
  100234. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  100235. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  100236. pDb->pSchema->cache_size = size;
  100237. #else
  100238. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  100239. #endif
  100240. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  100241. }
  100242. /*
  100243. ** file_format==1 Version 3.0.0.
  100244. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  100245. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  100246. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  100247. */
  100248. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  100249. if( pDb->pSchema->file_format==0 ){
  100250. pDb->pSchema->file_format = 1;
  100251. }
  100252. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  100253. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  100254. rc = SQLITE_ERROR;
  100255. goto initone_error_out;
  100256. }
  100257. /* Ticket #2804: When we open a database in the newer file format,
  100258. ** clear the legacy_file_format pragma flag so that a VACUUM will
  100259. ** not downgrade the database and thus invalidate any descending
  100260. ** indices that the user might have created.
  100261. */
  100262. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  100263. db->flags &= ~SQLITE_LegacyFileFmt;
  100264. }
  100265. /* Read the schema information out of the schema tables
  100266. */
  100267. assert( db->init.busy );
  100268. {
  100269. char *zSql;
  100270. zSql = sqlite3MPrintf(db,
  100271. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  100272. db->aDb[iDb].zName, zMasterName);
  100273. #ifndef SQLITE_OMIT_AUTHORIZATION
  100274. {
  100275. sqlite3_xauth xAuth;
  100276. xAuth = db->xAuth;
  100277. db->xAuth = 0;
  100278. #endif
  100279. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  100280. #ifndef SQLITE_OMIT_AUTHORIZATION
  100281. db->xAuth = xAuth;
  100282. }
  100283. #endif
  100284. if( rc==SQLITE_OK ) rc = initData.rc;
  100285. sqlite3DbFree(db, zSql);
  100286. #ifndef SQLITE_OMIT_ANALYZE
  100287. if( rc==SQLITE_OK ){
  100288. sqlite3AnalysisLoad(db, iDb);
  100289. }
  100290. #endif
  100291. }
  100292. if( db->mallocFailed ){
  100293. rc = SQLITE_NOMEM;
  100294. sqlite3ResetAllSchemasOfConnection(db);
  100295. }
  100296. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  100297. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  100298. ** the schema loaded, even if errors occurred. In this situation the
  100299. ** current sqlite3_prepare() operation will fail, but the following one
  100300. ** will attempt to compile the supplied statement against whatever subset
  100301. ** of the schema was loaded before the error occurred. The primary
  100302. ** purpose of this is to allow access to the sqlite_master table
  100303. ** even when its contents have been corrupted.
  100304. */
  100305. DbSetProperty(db, iDb, DB_SchemaLoaded);
  100306. rc = SQLITE_OK;
  100307. }
  100308. /* Jump here for an error that occurs after successfully allocating
  100309. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  100310. ** before that point, jump to error_out.
  100311. */
  100312. initone_error_out:
  100313. if( openedTransaction ){
  100314. sqlite3BtreeCommit(pDb->pBt);
  100315. }
  100316. sqlite3BtreeLeave(pDb->pBt);
  100317. error_out:
  100318. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  100319. db->mallocFailed = 1;
  100320. }
  100321. return rc;
  100322. }
  100323. /*
  100324. ** Initialize all database files - the main database file, the file
  100325. ** used to store temporary tables, and any additional database files
  100326. ** created using ATTACH statements. Return a success code. If an
  100327. ** error occurs, write an error message into *pzErrMsg.
  100328. **
  100329. ** After a database is initialized, the DB_SchemaLoaded bit is set
  100330. ** bit is set in the flags field of the Db structure. If the database
  100331. ** file was of zero-length, then the DB_Empty flag is also set.
  100332. */
  100333. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  100334. int i, rc;
  100335. int commit_internal = !(db->flags&SQLITE_InternChanges);
  100336. assert( sqlite3_mutex_held(db->mutex) );
  100337. assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
  100338. assert( db->init.busy==0 );
  100339. rc = SQLITE_OK;
  100340. db->init.busy = 1;
  100341. ENC(db) = SCHEMA_ENC(db);
  100342. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  100343. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  100344. rc = sqlite3InitOne(db, i, pzErrMsg);
  100345. if( rc ){
  100346. sqlite3ResetOneSchema(db, i);
  100347. }
  100348. }
  100349. /* Once all the other databases have been initialized, load the schema
  100350. ** for the TEMP database. This is loaded last, as the TEMP database
  100351. ** schema may contain references to objects in other databases.
  100352. */
  100353. #ifndef SQLITE_OMIT_TEMPDB
  100354. assert( db->nDb>1 );
  100355. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  100356. rc = sqlite3InitOne(db, 1, pzErrMsg);
  100357. if( rc ){
  100358. sqlite3ResetOneSchema(db, 1);
  100359. }
  100360. }
  100361. #endif
  100362. db->init.busy = 0;
  100363. if( rc==SQLITE_OK && commit_internal ){
  100364. sqlite3CommitInternalChanges(db);
  100365. }
  100366. return rc;
  100367. }
  100368. /*
  100369. ** This routine is a no-op if the database schema is already initialized.
  100370. ** Otherwise, the schema is loaded. An error code is returned.
  100371. */
  100372. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  100373. int rc = SQLITE_OK;
  100374. sqlite3 *db = pParse->db;
  100375. assert( sqlite3_mutex_held(db->mutex) );
  100376. if( !db->init.busy ){
  100377. rc = sqlite3Init(db, &pParse->zErrMsg);
  100378. }
  100379. if( rc!=SQLITE_OK ){
  100380. pParse->rc = rc;
  100381. pParse->nErr++;
  100382. }
  100383. return rc;
  100384. }
  100385. /*
  100386. ** Check schema cookies in all databases. If any cookie is out
  100387. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  100388. ** make no changes to pParse->rc.
  100389. */
  100390. static void schemaIsValid(Parse *pParse){
  100391. sqlite3 *db = pParse->db;
  100392. int iDb;
  100393. int rc;
  100394. int cookie;
  100395. assert( pParse->checkSchema );
  100396. assert( sqlite3_mutex_held(db->mutex) );
  100397. for(iDb=0; iDb<db->nDb; iDb++){
  100398. int openedTransaction = 0; /* True if a transaction is opened */
  100399. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  100400. if( pBt==0 ) continue;
  100401. /* If there is not already a read-only (or read-write) transaction opened
  100402. ** on the b-tree database, open one now. If a transaction is opened, it
  100403. ** will be closed immediately after reading the meta-value. */
  100404. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  100405. rc = sqlite3BtreeBeginTrans(pBt, 0);
  100406. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  100407. db->mallocFailed = 1;
  100408. }
  100409. if( rc!=SQLITE_OK ) return;
  100410. openedTransaction = 1;
  100411. }
  100412. /* Read the schema cookie from the database. If it does not match the
  100413. ** value stored as part of the in-memory schema representation,
  100414. ** set Parse.rc to SQLITE_SCHEMA. */
  100415. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  100416. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100417. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  100418. sqlite3ResetOneSchema(db, iDb);
  100419. pParse->rc = SQLITE_SCHEMA;
  100420. }
  100421. /* Close the transaction, if one was opened. */
  100422. if( openedTransaction ){
  100423. sqlite3BtreeCommit(pBt);
  100424. }
  100425. }
  100426. }
  100427. /*
  100428. ** Convert a schema pointer into the iDb index that indicates
  100429. ** which database file in db->aDb[] the schema refers to.
  100430. **
  100431. ** If the same database is attached more than once, the first
  100432. ** attached database is returned.
  100433. */
  100434. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  100435. int i = -1000000;
  100436. /* If pSchema is NULL, then return -1000000. This happens when code in
  100437. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  100438. ** created by a sub-select). In this case the return value of this
  100439. ** function should never be used.
  100440. **
  100441. ** We return -1000000 instead of the more usual -1 simply because using
  100442. ** -1000000 as the incorrect index into db->aDb[] is much
  100443. ** more likely to cause a segfault than -1 (of course there are assert()
  100444. ** statements too, but it never hurts to play the odds).
  100445. */
  100446. assert( sqlite3_mutex_held(db->mutex) );
  100447. if( pSchema ){
  100448. for(i=0; ALWAYS(i<db->nDb); i++){
  100449. if( db->aDb[i].pSchema==pSchema ){
  100450. break;
  100451. }
  100452. }
  100453. assert( i>=0 && i<db->nDb );
  100454. }
  100455. return i;
  100456. }
  100457. /*
  100458. ** Free all memory allocations in the pParse object
  100459. */
  100460. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  100461. if( pParse ){
  100462. sqlite3 *db = pParse->db;
  100463. sqlite3DbFree(db, pParse->aLabel);
  100464. sqlite3ExprListDelete(db, pParse->pConstExpr);
  100465. }
  100466. }
  100467. /*
  100468. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  100469. */
  100470. static int sqlite3Prepare(
  100471. sqlite3 *db, /* Database handle. */
  100472. const char *zSql, /* UTF-8 encoded SQL statement. */
  100473. int nBytes, /* Length of zSql in bytes. */
  100474. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  100475. Vdbe *pReprepare, /* VM being reprepared */
  100476. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  100477. const char **pzTail /* OUT: End of parsed string */
  100478. ){
  100479. Parse *pParse; /* Parsing context */
  100480. char *zErrMsg = 0; /* Error message */
  100481. int rc = SQLITE_OK; /* Result code */
  100482. int i; /* Loop counter */
  100483. /* Allocate the parsing context */
  100484. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  100485. if( pParse==0 ){
  100486. rc = SQLITE_NOMEM;
  100487. goto end_prepare;
  100488. }
  100489. pParse->pReprepare = pReprepare;
  100490. assert( ppStmt && *ppStmt==0 );
  100491. assert( !db->mallocFailed );
  100492. assert( sqlite3_mutex_held(db->mutex) );
  100493. /* Check to verify that it is possible to get a read lock on all
  100494. ** database schemas. The inability to get a read lock indicates that
  100495. ** some other database connection is holding a write-lock, which in
  100496. ** turn means that the other connection has made uncommitted changes
  100497. ** to the schema.
  100498. **
  100499. ** Were we to proceed and prepare the statement against the uncommitted
  100500. ** schema changes and if those schema changes are subsequently rolled
  100501. ** back and different changes are made in their place, then when this
  100502. ** prepared statement goes to run the schema cookie would fail to detect
  100503. ** the schema change. Disaster would follow.
  100504. **
  100505. ** This thread is currently holding mutexes on all Btrees (because
  100506. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  100507. ** is not possible for another thread to start a new schema change
  100508. ** while this routine is running. Hence, we do not need to hold
  100509. ** locks on the schema, we just need to make sure nobody else is
  100510. ** holding them.
  100511. **
  100512. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  100513. ** but it does *not* override schema lock detection, so this all still
  100514. ** works even if READ_UNCOMMITTED is set.
  100515. */
  100516. for(i=0; i<db->nDb; i++) {
  100517. Btree *pBt = db->aDb[i].pBt;
  100518. if( pBt ){
  100519. assert( sqlite3BtreeHoldsMutex(pBt) );
  100520. rc = sqlite3BtreeSchemaLocked(pBt);
  100521. if( rc ){
  100522. const char *zDb = db->aDb[i].zName;
  100523. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  100524. testcase( db->flags & SQLITE_ReadUncommitted );
  100525. goto end_prepare;
  100526. }
  100527. }
  100528. }
  100529. sqlite3VtabUnlockList(db);
  100530. pParse->db = db;
  100531. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  100532. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  100533. char *zSqlCopy;
  100534. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  100535. testcase( nBytes==mxLen );
  100536. testcase( nBytes==mxLen+1 );
  100537. if( nBytes>mxLen ){
  100538. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  100539. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  100540. goto end_prepare;
  100541. }
  100542. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  100543. if( zSqlCopy ){
  100544. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  100545. sqlite3DbFree(db, zSqlCopy);
  100546. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  100547. }else{
  100548. pParse->zTail = &zSql[nBytes];
  100549. }
  100550. }else{
  100551. sqlite3RunParser(pParse, zSql, &zErrMsg);
  100552. }
  100553. assert( 0==pParse->nQueryLoop );
  100554. if( db->mallocFailed ){
  100555. pParse->rc = SQLITE_NOMEM;
  100556. }
  100557. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  100558. if( pParse->checkSchema ){
  100559. schemaIsValid(pParse);
  100560. }
  100561. if( db->mallocFailed ){
  100562. pParse->rc = SQLITE_NOMEM;
  100563. }
  100564. if( pzTail ){
  100565. *pzTail = pParse->zTail;
  100566. }
  100567. rc = pParse->rc;
  100568. #ifndef SQLITE_OMIT_EXPLAIN
  100569. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  100570. static const char * const azColName[] = {
  100571. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  100572. "selectid", "order", "from", "detail"
  100573. };
  100574. int iFirst, mx;
  100575. if( pParse->explain==2 ){
  100576. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  100577. iFirst = 8;
  100578. mx = 12;
  100579. }else{
  100580. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  100581. iFirst = 0;
  100582. mx = 8;
  100583. }
  100584. for(i=iFirst; i<mx; i++){
  100585. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  100586. azColName[i], SQLITE_STATIC);
  100587. }
  100588. }
  100589. #endif
  100590. if( db->init.busy==0 ){
  100591. Vdbe *pVdbe = pParse->pVdbe;
  100592. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  100593. }
  100594. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  100595. sqlite3VdbeFinalize(pParse->pVdbe);
  100596. assert(!(*ppStmt));
  100597. }else{
  100598. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  100599. }
  100600. if( zErrMsg ){
  100601. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  100602. sqlite3DbFree(db, zErrMsg);
  100603. }else{
  100604. sqlite3Error(db, rc);
  100605. }
  100606. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  100607. while( pParse->pTriggerPrg ){
  100608. TriggerPrg *pT = pParse->pTriggerPrg;
  100609. pParse->pTriggerPrg = pT->pNext;
  100610. sqlite3DbFree(db, pT);
  100611. }
  100612. end_prepare:
  100613. sqlite3ParserReset(pParse);
  100614. sqlite3StackFree(db, pParse);
  100615. rc = sqlite3ApiExit(db, rc);
  100616. assert( (rc&db->errMask)==rc );
  100617. return rc;
  100618. }
  100619. static int sqlite3LockAndPrepare(
  100620. sqlite3 *db, /* Database handle. */
  100621. const char *zSql, /* UTF-8 encoded SQL statement. */
  100622. int nBytes, /* Length of zSql in bytes. */
  100623. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  100624. Vdbe *pOld, /* VM being reprepared */
  100625. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  100626. const char **pzTail /* OUT: End of parsed string */
  100627. ){
  100628. int rc;
  100629. #ifdef SQLITE_ENABLE_API_ARMOR
  100630. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  100631. #endif
  100632. *ppStmt = 0;
  100633. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  100634. return SQLITE_MISUSE_BKPT;
  100635. }
  100636. sqlite3_mutex_enter(db->mutex);
  100637. sqlite3BtreeEnterAll(db);
  100638. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  100639. if( rc==SQLITE_SCHEMA ){
  100640. sqlite3_finalize(*ppStmt);
  100641. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  100642. }
  100643. sqlite3BtreeLeaveAll(db);
  100644. sqlite3_mutex_leave(db->mutex);
  100645. assert( rc==SQLITE_OK || *ppStmt==0 );
  100646. return rc;
  100647. }
  100648. /*
  100649. ** Rerun the compilation of a statement after a schema change.
  100650. **
  100651. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  100652. ** if the statement cannot be recompiled because another connection has
  100653. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  100654. ** occurs, return SQLITE_SCHEMA.
  100655. */
  100656. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  100657. int rc;
  100658. sqlite3_stmt *pNew;
  100659. const char *zSql;
  100660. sqlite3 *db;
  100661. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  100662. zSql = sqlite3_sql((sqlite3_stmt *)p);
  100663. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  100664. db = sqlite3VdbeDb(p);
  100665. assert( sqlite3_mutex_held(db->mutex) );
  100666. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  100667. if( rc ){
  100668. if( rc==SQLITE_NOMEM ){
  100669. db->mallocFailed = 1;
  100670. }
  100671. assert( pNew==0 );
  100672. return rc;
  100673. }else{
  100674. assert( pNew!=0 );
  100675. }
  100676. sqlite3VdbeSwap((Vdbe*)pNew, p);
  100677. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  100678. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  100679. sqlite3VdbeFinalize((Vdbe*)pNew);
  100680. return SQLITE_OK;
  100681. }
  100682. /*
  100683. ** Two versions of the official API. Legacy and new use. In the legacy
  100684. ** version, the original SQL text is not saved in the prepared statement
  100685. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  100686. ** sqlite3_step(). In the new version, the original SQL text is retained
  100687. ** and the statement is automatically recompiled if an schema change
  100688. ** occurs.
  100689. */
  100690. SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
  100691. sqlite3 *db, /* Database handle. */
  100692. const char *zSql, /* UTF-8 encoded SQL statement. */
  100693. int nBytes, /* Length of zSql in bytes. */
  100694. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  100695. const char **pzTail /* OUT: End of parsed string */
  100696. ){
  100697. int rc;
  100698. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  100699. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  100700. return rc;
  100701. }
  100702. SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
  100703. sqlite3 *db, /* Database handle. */
  100704. const char *zSql, /* UTF-8 encoded SQL statement. */
  100705. int nBytes, /* Length of zSql in bytes. */
  100706. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  100707. const char **pzTail /* OUT: End of parsed string */
  100708. ){
  100709. int rc;
  100710. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  100711. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  100712. return rc;
  100713. }
  100714. #ifndef SQLITE_OMIT_UTF16
  100715. /*
  100716. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  100717. */
  100718. static int sqlite3Prepare16(
  100719. sqlite3 *db, /* Database handle. */
  100720. const void *zSql, /* UTF-16 encoded SQL statement. */
  100721. int nBytes, /* Length of zSql in bytes. */
  100722. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  100723. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  100724. const void **pzTail /* OUT: End of parsed string */
  100725. ){
  100726. /* This function currently works by first transforming the UTF-16
  100727. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  100728. ** tricky bit is figuring out the pointer to return in *pzTail.
  100729. */
  100730. char *zSql8;
  100731. const char *zTail8 = 0;
  100732. int rc = SQLITE_OK;
  100733. #ifdef SQLITE_ENABLE_API_ARMOR
  100734. if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
  100735. #endif
  100736. *ppStmt = 0;
  100737. if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
  100738. return SQLITE_MISUSE_BKPT;
  100739. }
  100740. if( nBytes>=0 ){
  100741. int sz;
  100742. const char *z = (const char*)zSql;
  100743. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  100744. nBytes = sz;
  100745. }
  100746. sqlite3_mutex_enter(db->mutex);
  100747. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  100748. if( zSql8 ){
  100749. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  100750. }
  100751. if( zTail8 && pzTail ){
  100752. /* If sqlite3_prepare returns a tail pointer, we calculate the
  100753. ** equivalent pointer into the UTF-16 string by counting the unicode
  100754. ** characters between zSql8 and zTail8, and then returning a pointer
  100755. ** the same number of characters into the UTF-16 string.
  100756. */
  100757. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  100758. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  100759. }
  100760. sqlite3DbFree(db, zSql8);
  100761. rc = sqlite3ApiExit(db, rc);
  100762. sqlite3_mutex_leave(db->mutex);
  100763. return rc;
  100764. }
  100765. /*
  100766. ** Two versions of the official API. Legacy and new use. In the legacy
  100767. ** version, the original SQL text is not saved in the prepared statement
  100768. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  100769. ** sqlite3_step(). In the new version, the original SQL text is retained
  100770. ** and the statement is automatically recompiled if an schema change
  100771. ** occurs.
  100772. */
  100773. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
  100774. sqlite3 *db, /* Database handle. */
  100775. const void *zSql, /* UTF-16 encoded SQL statement. */
  100776. int nBytes, /* Length of zSql in bytes. */
  100777. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  100778. const void **pzTail /* OUT: End of parsed string */
  100779. ){
  100780. int rc;
  100781. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  100782. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  100783. return rc;
  100784. }
  100785. SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
  100786. sqlite3 *db, /* Database handle. */
  100787. const void *zSql, /* UTF-16 encoded SQL statement. */
  100788. int nBytes, /* Length of zSql in bytes. */
  100789. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  100790. const void **pzTail /* OUT: End of parsed string */
  100791. ){
  100792. int rc;
  100793. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  100794. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  100795. return rc;
  100796. }
  100797. #endif /* SQLITE_OMIT_UTF16 */
  100798. /************** End of prepare.c *********************************************/
  100799. /************** Begin file select.c ******************************************/
  100800. /*
  100801. ** 2001 September 15
  100802. **
  100803. ** The author disclaims copyright to this source code. In place of
  100804. ** a legal notice, here is a blessing:
  100805. **
  100806. ** May you do good and not evil.
  100807. ** May you find forgiveness for yourself and forgive others.
  100808. ** May you share freely, never taking more than you give.
  100809. **
  100810. *************************************************************************
  100811. ** This file contains C code routines that are called by the parser
  100812. ** to handle SELECT statements in SQLite.
  100813. */
  100814. /* #include "sqliteInt.h" */
  100815. /*
  100816. ** Trace output macros
  100817. */
  100818. #if SELECTTRACE_ENABLED
  100819. /***/ int sqlite3SelectTrace = 0;
  100820. # define SELECTTRACE(K,P,S,X) \
  100821. if(sqlite3SelectTrace&(K)) \
  100822. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
  100823. (S)->zSelName,(S)),\
  100824. sqlite3DebugPrintf X
  100825. #else
  100826. # define SELECTTRACE(K,P,S,X)
  100827. #endif
  100828. /*
  100829. ** An instance of the following object is used to record information about
  100830. ** how to process the DISTINCT keyword, to simplify passing that information
  100831. ** into the selectInnerLoop() routine.
  100832. */
  100833. typedef struct DistinctCtx DistinctCtx;
  100834. struct DistinctCtx {
  100835. u8 isTnct; /* True if the DISTINCT keyword is present */
  100836. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  100837. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  100838. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  100839. };
  100840. /*
  100841. ** An instance of the following object is used to record information about
  100842. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  100843. */
  100844. typedef struct SortCtx SortCtx;
  100845. struct SortCtx {
  100846. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  100847. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  100848. int iECursor; /* Cursor number for the sorter */
  100849. int regReturn; /* Register holding block-output return address */
  100850. int labelBkOut; /* Start label for the block-output subroutine */
  100851. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  100852. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  100853. };
  100854. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  100855. /*
  100856. ** Delete all the content of a Select structure. Deallocate the structure
  100857. ** itself only if bFree is true.
  100858. */
  100859. static void clearSelect(sqlite3 *db, Select *p, int bFree){
  100860. while( p ){
  100861. Select *pPrior = p->pPrior;
  100862. sqlite3ExprListDelete(db, p->pEList);
  100863. sqlite3SrcListDelete(db, p->pSrc);
  100864. sqlite3ExprDelete(db, p->pWhere);
  100865. sqlite3ExprListDelete(db, p->pGroupBy);
  100866. sqlite3ExprDelete(db, p->pHaving);
  100867. sqlite3ExprListDelete(db, p->pOrderBy);
  100868. sqlite3ExprDelete(db, p->pLimit);
  100869. sqlite3ExprDelete(db, p->pOffset);
  100870. sqlite3WithDelete(db, p->pWith);
  100871. if( bFree ) sqlite3DbFree(db, p);
  100872. p = pPrior;
  100873. bFree = 1;
  100874. }
  100875. }
  100876. /*
  100877. ** Initialize a SelectDest structure.
  100878. */
  100879. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  100880. pDest->eDest = (u8)eDest;
  100881. pDest->iSDParm = iParm;
  100882. pDest->affSdst = 0;
  100883. pDest->iSdst = 0;
  100884. pDest->nSdst = 0;
  100885. }
  100886. /*
  100887. ** Allocate a new Select structure and return a pointer to that
  100888. ** structure.
  100889. */
  100890. SQLITE_PRIVATE Select *sqlite3SelectNew(
  100891. Parse *pParse, /* Parsing context */
  100892. ExprList *pEList, /* which columns to include in the result */
  100893. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  100894. Expr *pWhere, /* the WHERE clause */
  100895. ExprList *pGroupBy, /* the GROUP BY clause */
  100896. Expr *pHaving, /* the HAVING clause */
  100897. ExprList *pOrderBy, /* the ORDER BY clause */
  100898. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  100899. Expr *pLimit, /* LIMIT value. NULL means not used */
  100900. Expr *pOffset /* OFFSET value. NULL means no offset */
  100901. ){
  100902. Select *pNew;
  100903. Select standin;
  100904. sqlite3 *db = pParse->db;
  100905. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  100906. if( pNew==0 ){
  100907. assert( db->mallocFailed );
  100908. pNew = &standin;
  100909. memset(pNew, 0, sizeof(*pNew));
  100910. }
  100911. if( pEList==0 ){
  100912. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  100913. }
  100914. pNew->pEList = pEList;
  100915. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  100916. pNew->pSrc = pSrc;
  100917. pNew->pWhere = pWhere;
  100918. pNew->pGroupBy = pGroupBy;
  100919. pNew->pHaving = pHaving;
  100920. pNew->pOrderBy = pOrderBy;
  100921. pNew->selFlags = selFlags;
  100922. pNew->op = TK_SELECT;
  100923. pNew->pLimit = pLimit;
  100924. pNew->pOffset = pOffset;
  100925. assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
  100926. pNew->addrOpenEphm[0] = -1;
  100927. pNew->addrOpenEphm[1] = -1;
  100928. if( db->mallocFailed ) {
  100929. clearSelect(db, pNew, pNew!=&standin);
  100930. pNew = 0;
  100931. }else{
  100932. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  100933. }
  100934. assert( pNew!=&standin );
  100935. return pNew;
  100936. }
  100937. #if SELECTTRACE_ENABLED
  100938. /*
  100939. ** Set the name of a Select object
  100940. */
  100941. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  100942. if( p && zName ){
  100943. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  100944. }
  100945. }
  100946. #endif
  100947. /*
  100948. ** Delete the given Select structure and all of its substructures.
  100949. */
  100950. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  100951. clearSelect(db, p, 1);
  100952. }
  100953. /*
  100954. ** Return a pointer to the right-most SELECT statement in a compound.
  100955. */
  100956. static Select *findRightmost(Select *p){
  100957. while( p->pNext ) p = p->pNext;
  100958. return p;
  100959. }
  100960. /*
  100961. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  100962. ** type of join. Return an integer constant that expresses that type
  100963. ** in terms of the following bit values:
  100964. **
  100965. ** JT_INNER
  100966. ** JT_CROSS
  100967. ** JT_OUTER
  100968. ** JT_NATURAL
  100969. ** JT_LEFT
  100970. ** JT_RIGHT
  100971. **
  100972. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  100973. **
  100974. ** If an illegal or unsupported join type is seen, then still return
  100975. ** a join type, but put an error in the pParse structure.
  100976. */
  100977. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  100978. int jointype = 0;
  100979. Token *apAll[3];
  100980. Token *p;
  100981. /* 0123456789 123456789 123456789 123 */
  100982. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  100983. static const struct {
  100984. u8 i; /* Beginning of keyword text in zKeyText[] */
  100985. u8 nChar; /* Length of the keyword in characters */
  100986. u8 code; /* Join type mask */
  100987. } aKeyword[] = {
  100988. /* natural */ { 0, 7, JT_NATURAL },
  100989. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  100990. /* outer */ { 10, 5, JT_OUTER },
  100991. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  100992. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  100993. /* inner */ { 23, 5, JT_INNER },
  100994. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  100995. };
  100996. int i, j;
  100997. apAll[0] = pA;
  100998. apAll[1] = pB;
  100999. apAll[2] = pC;
  101000. for(i=0; i<3 && apAll[i]; i++){
  101001. p = apAll[i];
  101002. for(j=0; j<ArraySize(aKeyword); j++){
  101003. if( p->n==aKeyword[j].nChar
  101004. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  101005. jointype |= aKeyword[j].code;
  101006. break;
  101007. }
  101008. }
  101009. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  101010. if( j>=ArraySize(aKeyword) ){
  101011. jointype |= JT_ERROR;
  101012. break;
  101013. }
  101014. }
  101015. if(
  101016. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  101017. (jointype & JT_ERROR)!=0
  101018. ){
  101019. const char *zSp = " ";
  101020. assert( pB!=0 );
  101021. if( pC==0 ){ zSp++; }
  101022. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  101023. "%T %T%s%T", pA, pB, zSp, pC);
  101024. jointype = JT_INNER;
  101025. }else if( (jointype & JT_OUTER)!=0
  101026. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  101027. sqlite3ErrorMsg(pParse,
  101028. "RIGHT and FULL OUTER JOINs are not currently supported");
  101029. jointype = JT_INNER;
  101030. }
  101031. return jointype;
  101032. }
  101033. /*
  101034. ** Return the index of a column in a table. Return -1 if the column
  101035. ** is not contained in the table.
  101036. */
  101037. static int columnIndex(Table *pTab, const char *zCol){
  101038. int i;
  101039. for(i=0; i<pTab->nCol; i++){
  101040. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  101041. }
  101042. return -1;
  101043. }
  101044. /*
  101045. ** Search the first N tables in pSrc, from left to right, looking for a
  101046. ** table that has a column named zCol.
  101047. **
  101048. ** When found, set *piTab and *piCol to the table index and column index
  101049. ** of the matching column and return TRUE.
  101050. **
  101051. ** If not found, return FALSE.
  101052. */
  101053. static int tableAndColumnIndex(
  101054. SrcList *pSrc, /* Array of tables to search */
  101055. int N, /* Number of tables in pSrc->a[] to search */
  101056. const char *zCol, /* Name of the column we are looking for */
  101057. int *piTab, /* Write index of pSrc->a[] here */
  101058. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  101059. ){
  101060. int i; /* For looping over tables in pSrc */
  101061. int iCol; /* Index of column matching zCol */
  101062. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  101063. for(i=0; i<N; i++){
  101064. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  101065. if( iCol>=0 ){
  101066. if( piTab ){
  101067. *piTab = i;
  101068. *piCol = iCol;
  101069. }
  101070. return 1;
  101071. }
  101072. }
  101073. return 0;
  101074. }
  101075. /*
  101076. ** This function is used to add terms implied by JOIN syntax to the
  101077. ** WHERE clause expression of a SELECT statement. The new term, which
  101078. ** is ANDed with the existing WHERE clause, is of the form:
  101079. **
  101080. ** (tab1.col1 = tab2.col2)
  101081. **
  101082. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  101083. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  101084. ** column iColRight of tab2.
  101085. */
  101086. static void addWhereTerm(
  101087. Parse *pParse, /* Parsing context */
  101088. SrcList *pSrc, /* List of tables in FROM clause */
  101089. int iLeft, /* Index of first table to join in pSrc */
  101090. int iColLeft, /* Index of column in first table */
  101091. int iRight, /* Index of second table in pSrc */
  101092. int iColRight, /* Index of column in second table */
  101093. int isOuterJoin, /* True if this is an OUTER join */
  101094. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  101095. ){
  101096. sqlite3 *db = pParse->db;
  101097. Expr *pE1;
  101098. Expr *pE2;
  101099. Expr *pEq;
  101100. assert( iLeft<iRight );
  101101. assert( pSrc->nSrc>iRight );
  101102. assert( pSrc->a[iLeft].pTab );
  101103. assert( pSrc->a[iRight].pTab );
  101104. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  101105. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  101106. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  101107. if( pEq && isOuterJoin ){
  101108. ExprSetProperty(pEq, EP_FromJoin);
  101109. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  101110. ExprSetVVAProperty(pEq, EP_NoReduce);
  101111. pEq->iRightJoinTable = (i16)pE2->iTable;
  101112. }
  101113. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  101114. }
  101115. /*
  101116. ** Set the EP_FromJoin property on all terms of the given expression.
  101117. ** And set the Expr.iRightJoinTable to iTable for every term in the
  101118. ** expression.
  101119. **
  101120. ** The EP_FromJoin property is used on terms of an expression to tell
  101121. ** the LEFT OUTER JOIN processing logic that this term is part of the
  101122. ** join restriction specified in the ON or USING clause and not a part
  101123. ** of the more general WHERE clause. These terms are moved over to the
  101124. ** WHERE clause during join processing but we need to remember that they
  101125. ** originated in the ON or USING clause.
  101126. **
  101127. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  101128. ** expression depends on table iRightJoinTable even if that table is not
  101129. ** explicitly mentioned in the expression. That information is needed
  101130. ** for cases like this:
  101131. **
  101132. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  101133. **
  101134. ** The where clause needs to defer the handling of the t1.x=5
  101135. ** term until after the t2 loop of the join. In that way, a
  101136. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  101137. ** defer the handling of t1.x=5, it will be processed immediately
  101138. ** after the t1 loop and rows with t1.x!=5 will never appear in
  101139. ** the output, which is incorrect.
  101140. */
  101141. static void setJoinExpr(Expr *p, int iTable){
  101142. while( p ){
  101143. ExprSetProperty(p, EP_FromJoin);
  101144. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  101145. ExprSetVVAProperty(p, EP_NoReduce);
  101146. p->iRightJoinTable = (i16)iTable;
  101147. if( p->op==TK_FUNCTION && p->x.pList ){
  101148. int i;
  101149. for(i=0; i<p->x.pList->nExpr; i++){
  101150. setJoinExpr(p->x.pList->a[i].pExpr, iTable);
  101151. }
  101152. }
  101153. setJoinExpr(p->pLeft, iTable);
  101154. p = p->pRight;
  101155. }
  101156. }
  101157. /*
  101158. ** This routine processes the join information for a SELECT statement.
  101159. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  101160. ** NATURAL joins also create extra WHERE clause terms.
  101161. **
  101162. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  101163. ** The left most table is the first entry in Select.pSrc. The right-most
  101164. ** table is the last entry. The join operator is held in the entry to
  101165. ** the left. Thus entry 0 contains the join operator for the join between
  101166. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  101167. ** also attached to the left entry.
  101168. **
  101169. ** This routine returns the number of errors encountered.
  101170. */
  101171. static int sqliteProcessJoin(Parse *pParse, Select *p){
  101172. SrcList *pSrc; /* All tables in the FROM clause */
  101173. int i, j; /* Loop counters */
  101174. struct SrcList_item *pLeft; /* Left table being joined */
  101175. struct SrcList_item *pRight; /* Right table being joined */
  101176. pSrc = p->pSrc;
  101177. pLeft = &pSrc->a[0];
  101178. pRight = &pLeft[1];
  101179. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  101180. Table *pLeftTab = pLeft->pTab;
  101181. Table *pRightTab = pRight->pTab;
  101182. int isOuter;
  101183. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  101184. isOuter = (pRight->jointype & JT_OUTER)!=0;
  101185. /* When the NATURAL keyword is present, add WHERE clause terms for
  101186. ** every column that the two tables have in common.
  101187. */
  101188. if( pRight->jointype & JT_NATURAL ){
  101189. if( pRight->pOn || pRight->pUsing ){
  101190. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  101191. "an ON or USING clause", 0);
  101192. return 1;
  101193. }
  101194. for(j=0; j<pRightTab->nCol; j++){
  101195. char *zName; /* Name of column in the right table */
  101196. int iLeft; /* Matching left table */
  101197. int iLeftCol; /* Matching column in the left table */
  101198. zName = pRightTab->aCol[j].zName;
  101199. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  101200. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  101201. isOuter, &p->pWhere);
  101202. }
  101203. }
  101204. }
  101205. /* Disallow both ON and USING clauses in the same join
  101206. */
  101207. if( pRight->pOn && pRight->pUsing ){
  101208. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  101209. "clauses in the same join");
  101210. return 1;
  101211. }
  101212. /* Add the ON clause to the end of the WHERE clause, connected by
  101213. ** an AND operator.
  101214. */
  101215. if( pRight->pOn ){
  101216. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  101217. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  101218. pRight->pOn = 0;
  101219. }
  101220. /* Create extra terms on the WHERE clause for each column named
  101221. ** in the USING clause. Example: If the two tables to be joined are
  101222. ** A and B and the USING clause names X, Y, and Z, then add this
  101223. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  101224. ** Report an error if any column mentioned in the USING clause is
  101225. ** not contained in both tables to be joined.
  101226. */
  101227. if( pRight->pUsing ){
  101228. IdList *pList = pRight->pUsing;
  101229. for(j=0; j<pList->nId; j++){
  101230. char *zName; /* Name of the term in the USING clause */
  101231. int iLeft; /* Table on the left with matching column name */
  101232. int iLeftCol; /* Column number of matching column on the left */
  101233. int iRightCol; /* Column number of matching column on the right */
  101234. zName = pList->a[j].zName;
  101235. iRightCol = columnIndex(pRightTab, zName);
  101236. if( iRightCol<0
  101237. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  101238. ){
  101239. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  101240. "not present in both tables", zName);
  101241. return 1;
  101242. }
  101243. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  101244. isOuter, &p->pWhere);
  101245. }
  101246. }
  101247. }
  101248. return 0;
  101249. }
  101250. /* Forward reference */
  101251. static KeyInfo *keyInfoFromExprList(
  101252. Parse *pParse, /* Parsing context */
  101253. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  101254. int iStart, /* Begin with this column of pList */
  101255. int nExtra /* Add this many extra columns to the end */
  101256. );
  101257. /*
  101258. ** Generate code that will push the record in registers regData
  101259. ** through regData+nData-1 onto the sorter.
  101260. */
  101261. static void pushOntoSorter(
  101262. Parse *pParse, /* Parser context */
  101263. SortCtx *pSort, /* Information about the ORDER BY clause */
  101264. Select *pSelect, /* The whole SELECT statement */
  101265. int regData, /* First register holding data to be sorted */
  101266. int nData, /* Number of elements in the data array */
  101267. int nPrefixReg /* No. of reg prior to regData available for use */
  101268. ){
  101269. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  101270. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  101271. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  101272. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  101273. int regBase; /* Regs for sorter record */
  101274. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  101275. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  101276. int op; /* Opcode to add sorter record to sorter */
  101277. assert( bSeq==0 || bSeq==1 );
  101278. if( nPrefixReg ){
  101279. assert( nPrefixReg==nExpr+bSeq );
  101280. regBase = regData - nExpr - bSeq;
  101281. }else{
  101282. regBase = pParse->nMem + 1;
  101283. pParse->nMem += nBase;
  101284. }
  101285. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
  101286. if( bSeq ){
  101287. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  101288. }
  101289. if( nPrefixReg==0 ){
  101290. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  101291. }
  101292. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  101293. if( nOBSat>0 ){
  101294. int regPrevKey; /* The first nOBSat columns of the previous row */
  101295. int addrFirst; /* Address of the OP_IfNot opcode */
  101296. int addrJmp; /* Address of the OP_Jump opcode */
  101297. VdbeOp *pOp; /* Opcode that opens the sorter */
  101298. int nKey; /* Number of sorting key columns, including OP_Sequence */
  101299. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  101300. regPrevKey = pParse->nMem+1;
  101301. pParse->nMem += pSort->nOBSat;
  101302. nKey = nExpr - pSort->nOBSat + bSeq;
  101303. if( bSeq ){
  101304. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  101305. }else{
  101306. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  101307. }
  101308. VdbeCoverage(v);
  101309. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  101310. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  101311. if( pParse->db->mallocFailed ) return;
  101312. pOp->p2 = nKey + nData;
  101313. pKI = pOp->p4.pKeyInfo;
  101314. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  101315. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  101316. testcase( pKI->nXField>2 );
  101317. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
  101318. pKI->nXField-1);
  101319. addrJmp = sqlite3VdbeCurrentAddr(v);
  101320. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  101321. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  101322. pSort->regReturn = ++pParse->nMem;
  101323. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  101324. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  101325. sqlite3VdbeJumpHere(v, addrFirst);
  101326. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  101327. sqlite3VdbeJumpHere(v, addrJmp);
  101328. }
  101329. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  101330. op = OP_SorterInsert;
  101331. }else{
  101332. op = OP_IdxInsert;
  101333. }
  101334. sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
  101335. if( pSelect->iLimit ){
  101336. int addr;
  101337. int iLimit;
  101338. if( pSelect->iOffset ){
  101339. iLimit = pSelect->iOffset+1;
  101340. }else{
  101341. iLimit = pSelect->iLimit;
  101342. }
  101343. addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, -1); VdbeCoverage(v);
  101344. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  101345. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  101346. sqlite3VdbeJumpHere(v, addr);
  101347. }
  101348. }
  101349. /*
  101350. ** Add code to implement the OFFSET
  101351. */
  101352. static void codeOffset(
  101353. Vdbe *v, /* Generate code into this VM */
  101354. int iOffset, /* Register holding the offset counter */
  101355. int iContinue /* Jump here to skip the current record */
  101356. ){
  101357. if( iOffset>0 ){
  101358. int addr;
  101359. addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
  101360. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  101361. VdbeComment((v, "skip OFFSET records"));
  101362. sqlite3VdbeJumpHere(v, addr);
  101363. }
  101364. }
  101365. /*
  101366. ** Add code that will check to make sure the N registers starting at iMem
  101367. ** form a distinct entry. iTab is a sorting index that holds previously
  101368. ** seen combinations of the N values. A new entry is made in iTab
  101369. ** if the current N values are new.
  101370. **
  101371. ** A jump to addrRepeat is made and the N+1 values are popped from the
  101372. ** stack if the top N elements are not distinct.
  101373. */
  101374. static void codeDistinct(
  101375. Parse *pParse, /* Parsing and code generating context */
  101376. int iTab, /* A sorting index used to test for distinctness */
  101377. int addrRepeat, /* Jump to here if not distinct */
  101378. int N, /* Number of elements */
  101379. int iMem /* First element */
  101380. ){
  101381. Vdbe *v;
  101382. int r1;
  101383. v = pParse->pVdbe;
  101384. r1 = sqlite3GetTempReg(pParse);
  101385. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  101386. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  101387. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  101388. sqlite3ReleaseTempReg(pParse, r1);
  101389. }
  101390. #ifndef SQLITE_OMIT_SUBQUERY
  101391. /*
  101392. ** Generate an error message when a SELECT is used within a subexpression
  101393. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  101394. ** column. We do this in a subroutine because the error used to occur
  101395. ** in multiple places. (The error only occurs in one place now, but we
  101396. ** retain the subroutine to minimize code disruption.)
  101397. */
  101398. static int checkForMultiColumnSelectError(
  101399. Parse *pParse, /* Parse context. */
  101400. SelectDest *pDest, /* Destination of SELECT results */
  101401. int nExpr /* Number of result columns returned by SELECT */
  101402. ){
  101403. int eDest = pDest->eDest;
  101404. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  101405. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  101406. "a SELECT that is part of an expression");
  101407. return 1;
  101408. }else{
  101409. return 0;
  101410. }
  101411. }
  101412. #endif
  101413. /*
  101414. ** This routine generates the code for the inside of the inner loop
  101415. ** of a SELECT.
  101416. **
  101417. ** If srcTab is negative, then the pEList expressions
  101418. ** are evaluated in order to get the data for this row. If srcTab is
  101419. ** zero or more, then data is pulled from srcTab and pEList is used only
  101420. ** to get number columns and the datatype for each column.
  101421. */
  101422. static void selectInnerLoop(
  101423. Parse *pParse, /* The parser context */
  101424. Select *p, /* The complete select statement being coded */
  101425. ExprList *pEList, /* List of values being extracted */
  101426. int srcTab, /* Pull data from this table */
  101427. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  101428. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  101429. SelectDest *pDest, /* How to dispose of the results */
  101430. int iContinue, /* Jump here to continue with next row */
  101431. int iBreak /* Jump here to break out of the inner loop */
  101432. ){
  101433. Vdbe *v = pParse->pVdbe;
  101434. int i;
  101435. int hasDistinct; /* True if the DISTINCT keyword is present */
  101436. int regResult; /* Start of memory holding result set */
  101437. int eDest = pDest->eDest; /* How to dispose of results */
  101438. int iParm = pDest->iSDParm; /* First argument to disposal method */
  101439. int nResultCol; /* Number of result columns */
  101440. int nPrefixReg = 0; /* Number of extra registers before regResult */
  101441. assert( v );
  101442. assert( pEList!=0 );
  101443. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  101444. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  101445. if( pSort==0 && !hasDistinct ){
  101446. assert( iContinue!=0 );
  101447. codeOffset(v, p->iOffset, iContinue);
  101448. }
  101449. /* Pull the requested columns.
  101450. */
  101451. nResultCol = pEList->nExpr;
  101452. if( pDest->iSdst==0 ){
  101453. if( pSort ){
  101454. nPrefixReg = pSort->pOrderBy->nExpr;
  101455. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  101456. pParse->nMem += nPrefixReg;
  101457. }
  101458. pDest->iSdst = pParse->nMem+1;
  101459. pParse->nMem += nResultCol;
  101460. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  101461. /* This is an error condition that can result, for example, when a SELECT
  101462. ** on the right-hand side of an INSERT contains more result columns than
  101463. ** there are columns in the table on the left. The error will be caught
  101464. ** and reported later. But we need to make sure enough memory is allocated
  101465. ** to avoid other spurious errors in the meantime. */
  101466. pParse->nMem += nResultCol;
  101467. }
  101468. pDest->nSdst = nResultCol;
  101469. regResult = pDest->iSdst;
  101470. if( srcTab>=0 ){
  101471. for(i=0; i<nResultCol; i++){
  101472. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  101473. VdbeComment((v, "%s", pEList->a[i].zName));
  101474. }
  101475. }else if( eDest!=SRT_Exists ){
  101476. /* If the destination is an EXISTS(...) expression, the actual
  101477. ** values returned by the SELECT are not required.
  101478. */
  101479. u8 ecelFlags;
  101480. if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
  101481. ecelFlags = SQLITE_ECEL_DUP;
  101482. }else{
  101483. ecelFlags = 0;
  101484. }
  101485. sqlite3ExprCodeExprList(pParse, pEList, regResult, ecelFlags);
  101486. }
  101487. /* If the DISTINCT keyword was present on the SELECT statement
  101488. ** and this row has been seen before, then do not make this row
  101489. ** part of the result.
  101490. */
  101491. if( hasDistinct ){
  101492. switch( pDistinct->eTnctType ){
  101493. case WHERE_DISTINCT_ORDERED: {
  101494. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  101495. int iJump; /* Jump destination */
  101496. int regPrev; /* Previous row content */
  101497. /* Allocate space for the previous row */
  101498. regPrev = pParse->nMem+1;
  101499. pParse->nMem += nResultCol;
  101500. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  101501. ** sets the MEM_Cleared bit on the first register of the
  101502. ** previous value. This will cause the OP_Ne below to always
  101503. ** fail on the first iteration of the loop even if the first
  101504. ** row is all NULLs.
  101505. */
  101506. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  101507. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  101508. pOp->opcode = OP_Null;
  101509. pOp->p1 = 1;
  101510. pOp->p2 = regPrev;
  101511. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  101512. for(i=0; i<nResultCol; i++){
  101513. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  101514. if( i<nResultCol-1 ){
  101515. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  101516. VdbeCoverage(v);
  101517. }else{
  101518. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  101519. VdbeCoverage(v);
  101520. }
  101521. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  101522. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  101523. }
  101524. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  101525. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  101526. break;
  101527. }
  101528. case WHERE_DISTINCT_UNIQUE: {
  101529. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  101530. break;
  101531. }
  101532. default: {
  101533. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  101534. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
  101535. regResult);
  101536. break;
  101537. }
  101538. }
  101539. if( pSort==0 ){
  101540. codeOffset(v, p->iOffset, iContinue);
  101541. }
  101542. }
  101543. switch( eDest ){
  101544. /* In this mode, write each query result to the key of the temporary
  101545. ** table iParm.
  101546. */
  101547. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  101548. case SRT_Union: {
  101549. int r1;
  101550. r1 = sqlite3GetTempReg(pParse);
  101551. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  101552. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  101553. sqlite3ReleaseTempReg(pParse, r1);
  101554. break;
  101555. }
  101556. /* Construct a record from the query result, but instead of
  101557. ** saving that record, use it as a key to delete elements from
  101558. ** the temporary table iParm.
  101559. */
  101560. case SRT_Except: {
  101561. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  101562. break;
  101563. }
  101564. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  101565. /* Store the result as data using a unique key.
  101566. */
  101567. case SRT_Fifo:
  101568. case SRT_DistFifo:
  101569. case SRT_Table:
  101570. case SRT_EphemTab: {
  101571. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  101572. testcase( eDest==SRT_Table );
  101573. testcase( eDest==SRT_EphemTab );
  101574. testcase( eDest==SRT_Fifo );
  101575. testcase( eDest==SRT_DistFifo );
  101576. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  101577. #ifndef SQLITE_OMIT_CTE
  101578. if( eDest==SRT_DistFifo ){
  101579. /* If the destination is DistFifo, then cursor (iParm+1) is open
  101580. ** on an ephemeral index. If the current row is already present
  101581. ** in the index, do not write it to the output. If not, add the
  101582. ** current row to the index and proceed with writing it to the
  101583. ** output table as well. */
  101584. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  101585. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
  101586. VdbeCoverage(v);
  101587. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
  101588. assert( pSort==0 );
  101589. }
  101590. #endif
  101591. if( pSort ){
  101592. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
  101593. }else{
  101594. int r2 = sqlite3GetTempReg(pParse);
  101595. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  101596. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  101597. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  101598. sqlite3ReleaseTempReg(pParse, r2);
  101599. }
  101600. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  101601. break;
  101602. }
  101603. #ifndef SQLITE_OMIT_SUBQUERY
  101604. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  101605. ** then there should be a single item on the stack. Write this
  101606. ** item into the set table with bogus data.
  101607. */
  101608. case SRT_Set: {
  101609. assert( nResultCol==1 );
  101610. pDest->affSdst =
  101611. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  101612. if( pSort ){
  101613. /* At first glance you would think we could optimize out the
  101614. ** ORDER BY in this case since the order of entries in the set
  101615. ** does not matter. But there might be a LIMIT clause, in which
  101616. ** case the order does matter */
  101617. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  101618. }else{
  101619. int r1 = sqlite3GetTempReg(pParse);
  101620. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  101621. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  101622. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  101623. sqlite3ReleaseTempReg(pParse, r1);
  101624. }
  101625. break;
  101626. }
  101627. /* If any row exist in the result set, record that fact and abort.
  101628. */
  101629. case SRT_Exists: {
  101630. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  101631. /* The LIMIT clause will terminate the loop for us */
  101632. break;
  101633. }
  101634. /* If this is a scalar select that is part of an expression, then
  101635. ** store the results in the appropriate memory cell and break out
  101636. ** of the scan loop.
  101637. */
  101638. case SRT_Mem: {
  101639. assert( nResultCol==1 );
  101640. if( pSort ){
  101641. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  101642. }else{
  101643. assert( regResult==iParm );
  101644. /* The LIMIT clause will jump out of the loop for us */
  101645. }
  101646. break;
  101647. }
  101648. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  101649. case SRT_Coroutine: /* Send data to a co-routine */
  101650. case SRT_Output: { /* Return the results */
  101651. testcase( eDest==SRT_Coroutine );
  101652. testcase( eDest==SRT_Output );
  101653. if( pSort ){
  101654. pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
  101655. }else if( eDest==SRT_Coroutine ){
  101656. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  101657. }else{
  101658. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  101659. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  101660. }
  101661. break;
  101662. }
  101663. #ifndef SQLITE_OMIT_CTE
  101664. /* Write the results into a priority queue that is order according to
  101665. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  101666. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  101667. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  101668. ** final OP_Sequence column. The last column is the record as a blob.
  101669. */
  101670. case SRT_DistQueue:
  101671. case SRT_Queue: {
  101672. int nKey;
  101673. int r1, r2, r3;
  101674. int addrTest = 0;
  101675. ExprList *pSO;
  101676. pSO = pDest->pOrderBy;
  101677. assert( pSO );
  101678. nKey = pSO->nExpr;
  101679. r1 = sqlite3GetTempReg(pParse);
  101680. r2 = sqlite3GetTempRange(pParse, nKey+2);
  101681. r3 = r2+nKey+1;
  101682. if( eDest==SRT_DistQueue ){
  101683. /* If the destination is DistQueue, then cursor (iParm+1) is open
  101684. ** on a second ephemeral index that holds all values every previously
  101685. ** added to the queue. */
  101686. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  101687. regResult, nResultCol);
  101688. VdbeCoverage(v);
  101689. }
  101690. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  101691. if( eDest==SRT_DistQueue ){
  101692. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  101693. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  101694. }
  101695. for(i=0; i<nKey; i++){
  101696. sqlite3VdbeAddOp2(v, OP_SCopy,
  101697. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  101698. r2+i);
  101699. }
  101700. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  101701. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  101702. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  101703. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  101704. sqlite3ReleaseTempReg(pParse, r1);
  101705. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  101706. break;
  101707. }
  101708. #endif /* SQLITE_OMIT_CTE */
  101709. #if !defined(SQLITE_OMIT_TRIGGER)
  101710. /* Discard the results. This is used for SELECT statements inside
  101711. ** the body of a TRIGGER. The purpose of such selects is to call
  101712. ** user-defined functions that have side effects. We do not care
  101713. ** about the actual results of the select.
  101714. */
  101715. default: {
  101716. assert( eDest==SRT_Discard );
  101717. break;
  101718. }
  101719. #endif
  101720. }
  101721. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  101722. ** there is a sorter, in which case the sorter has already limited
  101723. ** the output for us.
  101724. */
  101725. if( pSort==0 && p->iLimit ){
  101726. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  101727. }
  101728. }
  101729. /*
  101730. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  101731. ** X extra columns.
  101732. */
  101733. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  101734. KeyInfo *p = sqlite3DbMallocZero(0,
  101735. sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
  101736. if( p ){
  101737. p->aSortOrder = (u8*)&p->aColl[N+X];
  101738. p->nField = (u16)N;
  101739. p->nXField = (u16)X;
  101740. p->enc = ENC(db);
  101741. p->db = db;
  101742. p->nRef = 1;
  101743. }else{
  101744. db->mallocFailed = 1;
  101745. }
  101746. return p;
  101747. }
  101748. /*
  101749. ** Deallocate a KeyInfo object
  101750. */
  101751. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  101752. if( p ){
  101753. assert( p->nRef>0 );
  101754. p->nRef--;
  101755. if( p->nRef==0 ) sqlite3DbFree(0, p);
  101756. }
  101757. }
  101758. /*
  101759. ** Make a new pointer to a KeyInfo object
  101760. */
  101761. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  101762. if( p ){
  101763. assert( p->nRef>0 );
  101764. p->nRef++;
  101765. }
  101766. return p;
  101767. }
  101768. #ifdef SQLITE_DEBUG
  101769. /*
  101770. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  101771. ** can only be changed if this is just a single reference to the object.
  101772. **
  101773. ** This routine is used only inside of assert() statements.
  101774. */
  101775. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  101776. #endif /* SQLITE_DEBUG */
  101777. /*
  101778. ** Given an expression list, generate a KeyInfo structure that records
  101779. ** the collating sequence for each expression in that expression list.
  101780. **
  101781. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  101782. ** KeyInfo structure is appropriate for initializing a virtual index to
  101783. ** implement that clause. If the ExprList is the result set of a SELECT
  101784. ** then the KeyInfo structure is appropriate for initializing a virtual
  101785. ** index to implement a DISTINCT test.
  101786. **
  101787. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  101788. ** function is responsible for seeing that this structure is eventually
  101789. ** freed.
  101790. */
  101791. static KeyInfo *keyInfoFromExprList(
  101792. Parse *pParse, /* Parsing context */
  101793. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  101794. int iStart, /* Begin with this column of pList */
  101795. int nExtra /* Add this many extra columns to the end */
  101796. ){
  101797. int nExpr;
  101798. KeyInfo *pInfo;
  101799. struct ExprList_item *pItem;
  101800. sqlite3 *db = pParse->db;
  101801. int i;
  101802. nExpr = pList->nExpr;
  101803. pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
  101804. if( pInfo ){
  101805. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  101806. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  101807. CollSeq *pColl;
  101808. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  101809. if( !pColl ) pColl = db->pDfltColl;
  101810. pInfo->aColl[i-iStart] = pColl;
  101811. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  101812. }
  101813. }
  101814. return pInfo;
  101815. }
  101816. /*
  101817. ** Name of the connection operator, used for error messages.
  101818. */
  101819. static const char *selectOpName(int id){
  101820. char *z;
  101821. switch( id ){
  101822. case TK_ALL: z = "UNION ALL"; break;
  101823. case TK_INTERSECT: z = "INTERSECT"; break;
  101824. case TK_EXCEPT: z = "EXCEPT"; break;
  101825. default: z = "UNION"; break;
  101826. }
  101827. return z;
  101828. }
  101829. #ifndef SQLITE_OMIT_EXPLAIN
  101830. /*
  101831. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  101832. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  101833. ** where the caption is of the form:
  101834. **
  101835. ** "USE TEMP B-TREE FOR xxx"
  101836. **
  101837. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  101838. ** is determined by the zUsage argument.
  101839. */
  101840. static void explainTempTable(Parse *pParse, const char *zUsage){
  101841. if( pParse->explain==2 ){
  101842. Vdbe *v = pParse->pVdbe;
  101843. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  101844. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  101845. }
  101846. }
  101847. /*
  101848. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  101849. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  101850. ** in sqlite3Select() to assign values to structure member variables that
  101851. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  101852. ** code with #ifndef directives.
  101853. */
  101854. # define explainSetInteger(a, b) a = b
  101855. #else
  101856. /* No-op versions of the explainXXX() functions and macros. */
  101857. # define explainTempTable(y,z)
  101858. # define explainSetInteger(y,z)
  101859. #endif
  101860. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  101861. /*
  101862. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  101863. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  101864. ** where the caption is of one of the two forms:
  101865. **
  101866. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  101867. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  101868. **
  101869. ** where iSub1 and iSub2 are the integers passed as the corresponding
  101870. ** function parameters, and op is the text representation of the parameter
  101871. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  101872. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  101873. ** false, or the second form if it is true.
  101874. */
  101875. static void explainComposite(
  101876. Parse *pParse, /* Parse context */
  101877. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  101878. int iSub1, /* Subquery id 1 */
  101879. int iSub2, /* Subquery id 2 */
  101880. int bUseTmp /* True if a temp table was used */
  101881. ){
  101882. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  101883. if( pParse->explain==2 ){
  101884. Vdbe *v = pParse->pVdbe;
  101885. char *zMsg = sqlite3MPrintf(
  101886. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  101887. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  101888. );
  101889. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  101890. }
  101891. }
  101892. #else
  101893. /* No-op versions of the explainXXX() functions and macros. */
  101894. # define explainComposite(v,w,x,y,z)
  101895. #endif
  101896. /*
  101897. ** If the inner loop was generated using a non-null pOrderBy argument,
  101898. ** then the results were placed in a sorter. After the loop is terminated
  101899. ** we need to run the sorter and output the results. The following
  101900. ** routine generates the code needed to do that.
  101901. */
  101902. static void generateSortTail(
  101903. Parse *pParse, /* Parsing context */
  101904. Select *p, /* The SELECT statement */
  101905. SortCtx *pSort, /* Information on the ORDER BY clause */
  101906. int nColumn, /* Number of columns of data */
  101907. SelectDest *pDest /* Write the sorted results here */
  101908. ){
  101909. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  101910. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  101911. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  101912. int addr;
  101913. int addrOnce = 0;
  101914. int iTab;
  101915. ExprList *pOrderBy = pSort->pOrderBy;
  101916. int eDest = pDest->eDest;
  101917. int iParm = pDest->iSDParm;
  101918. int regRow;
  101919. int regRowid;
  101920. int nKey;
  101921. int iSortTab; /* Sorter cursor to read from */
  101922. int nSortData; /* Trailing values to read from sorter */
  101923. int i;
  101924. int bSeq; /* True if sorter record includes seq. no. */
  101925. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  101926. struct ExprList_item *aOutEx = p->pEList->a;
  101927. #endif
  101928. if( pSort->labelBkOut ){
  101929. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  101930. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
  101931. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  101932. }
  101933. iTab = pSort->iECursor;
  101934. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  101935. regRowid = 0;
  101936. regRow = pDest->iSdst;
  101937. nSortData = nColumn;
  101938. }else{
  101939. regRowid = sqlite3GetTempReg(pParse);
  101940. regRow = sqlite3GetTempReg(pParse);
  101941. nSortData = 1;
  101942. }
  101943. nKey = pOrderBy->nExpr - pSort->nOBSat;
  101944. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  101945. int regSortOut = ++pParse->nMem;
  101946. iSortTab = pParse->nTab++;
  101947. if( pSort->labelBkOut ){
  101948. addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  101949. }
  101950. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  101951. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  101952. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  101953. VdbeCoverage(v);
  101954. codeOffset(v, p->iOffset, addrContinue);
  101955. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  101956. bSeq = 0;
  101957. }else{
  101958. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  101959. codeOffset(v, p->iOffset, addrContinue);
  101960. iSortTab = iTab;
  101961. bSeq = 1;
  101962. }
  101963. for(i=0; i<nSortData; i++){
  101964. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
  101965. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  101966. }
  101967. switch( eDest ){
  101968. case SRT_EphemTab: {
  101969. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  101970. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  101971. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  101972. break;
  101973. }
  101974. #ifndef SQLITE_OMIT_SUBQUERY
  101975. case SRT_Set: {
  101976. assert( nColumn==1 );
  101977. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  101978. &pDest->affSdst, 1);
  101979. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  101980. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  101981. break;
  101982. }
  101983. case SRT_Mem: {
  101984. assert( nColumn==1 );
  101985. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  101986. /* The LIMIT clause will terminate the loop for us */
  101987. break;
  101988. }
  101989. #endif
  101990. default: {
  101991. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  101992. testcase( eDest==SRT_Output );
  101993. testcase( eDest==SRT_Coroutine );
  101994. if( eDest==SRT_Output ){
  101995. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  101996. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  101997. }else{
  101998. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  101999. }
  102000. break;
  102001. }
  102002. }
  102003. if( regRowid ){
  102004. sqlite3ReleaseTempReg(pParse, regRow);
  102005. sqlite3ReleaseTempReg(pParse, regRowid);
  102006. }
  102007. /* The bottom of the loop
  102008. */
  102009. sqlite3VdbeResolveLabel(v, addrContinue);
  102010. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  102011. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  102012. }else{
  102013. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  102014. }
  102015. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  102016. sqlite3VdbeResolveLabel(v, addrBreak);
  102017. }
  102018. /*
  102019. ** Return a pointer to a string containing the 'declaration type' of the
  102020. ** expression pExpr. The string may be treated as static by the caller.
  102021. **
  102022. ** Also try to estimate the size of the returned value and return that
  102023. ** result in *pEstWidth.
  102024. **
  102025. ** The declaration type is the exact datatype definition extracted from the
  102026. ** original CREATE TABLE statement if the expression is a column. The
  102027. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  102028. ** is considered a column can be complex in the presence of subqueries. The
  102029. ** result-set expression in all of the following SELECT statements is
  102030. ** considered a column by this function.
  102031. **
  102032. ** SELECT col FROM tbl;
  102033. ** SELECT (SELECT col FROM tbl;
  102034. ** SELECT (SELECT col FROM tbl);
  102035. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  102036. **
  102037. ** The declaration type for any expression other than a column is NULL.
  102038. **
  102039. ** This routine has either 3 or 6 parameters depending on whether or not
  102040. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  102041. */
  102042. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  102043. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  102044. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  102045. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  102046. #endif
  102047. static const char *columnTypeImpl(
  102048. NameContext *pNC,
  102049. Expr *pExpr,
  102050. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  102051. const char **pzOrigDb,
  102052. const char **pzOrigTab,
  102053. const char **pzOrigCol,
  102054. #endif
  102055. u8 *pEstWidth
  102056. ){
  102057. char const *zType = 0;
  102058. int j;
  102059. u8 estWidth = 1;
  102060. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  102061. char const *zOrigDb = 0;
  102062. char const *zOrigTab = 0;
  102063. char const *zOrigCol = 0;
  102064. #endif
  102065. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  102066. switch( pExpr->op ){
  102067. case TK_AGG_COLUMN:
  102068. case TK_COLUMN: {
  102069. /* The expression is a column. Locate the table the column is being
  102070. ** extracted from in NameContext.pSrcList. This table may be real
  102071. ** database table or a subquery.
  102072. */
  102073. Table *pTab = 0; /* Table structure column is extracted from */
  102074. Select *pS = 0; /* Select the column is extracted from */
  102075. int iCol = pExpr->iColumn; /* Index of column in pTab */
  102076. testcase( pExpr->op==TK_AGG_COLUMN );
  102077. testcase( pExpr->op==TK_COLUMN );
  102078. while( pNC && !pTab ){
  102079. SrcList *pTabList = pNC->pSrcList;
  102080. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  102081. if( j<pTabList->nSrc ){
  102082. pTab = pTabList->a[j].pTab;
  102083. pS = pTabList->a[j].pSelect;
  102084. }else{
  102085. pNC = pNC->pNext;
  102086. }
  102087. }
  102088. if( pTab==0 ){
  102089. /* At one time, code such as "SELECT new.x" within a trigger would
  102090. ** cause this condition to run. Since then, we have restructured how
  102091. ** trigger code is generated and so this condition is no longer
  102092. ** possible. However, it can still be true for statements like
  102093. ** the following:
  102094. **
  102095. ** CREATE TABLE t1(col INTEGER);
  102096. ** SELECT (SELECT t1.col) FROM FROM t1;
  102097. **
  102098. ** when columnType() is called on the expression "t1.col" in the
  102099. ** sub-select. In this case, set the column type to NULL, even
  102100. ** though it should really be "INTEGER".
  102101. **
  102102. ** This is not a problem, as the column type of "t1.col" is never
  102103. ** used. When columnType() is called on the expression
  102104. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  102105. ** branch below. */
  102106. break;
  102107. }
  102108. assert( pTab && pExpr->pTab==pTab );
  102109. if( pS ){
  102110. /* The "table" is actually a sub-select or a view in the FROM clause
  102111. ** of the SELECT statement. Return the declaration type and origin
  102112. ** data for the result-set column of the sub-select.
  102113. */
  102114. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  102115. /* If iCol is less than zero, then the expression requests the
  102116. ** rowid of the sub-select or view. This expression is legal (see
  102117. ** test case misc2.2.2) - it always evaluates to NULL.
  102118. **
  102119. ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
  102120. ** caught already by name resolution.
  102121. */
  102122. NameContext sNC;
  102123. Expr *p = pS->pEList->a[iCol].pExpr;
  102124. sNC.pSrcList = pS->pSrc;
  102125. sNC.pNext = pNC;
  102126. sNC.pParse = pNC->pParse;
  102127. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  102128. }
  102129. }else if( pTab->pSchema ){
  102130. /* A real table */
  102131. assert( !pS );
  102132. if( iCol<0 ) iCol = pTab->iPKey;
  102133. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  102134. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  102135. if( iCol<0 ){
  102136. zType = "INTEGER";
  102137. zOrigCol = "rowid";
  102138. }else{
  102139. zType = pTab->aCol[iCol].zType;
  102140. zOrigCol = pTab->aCol[iCol].zName;
  102141. estWidth = pTab->aCol[iCol].szEst;
  102142. }
  102143. zOrigTab = pTab->zName;
  102144. if( pNC->pParse ){
  102145. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  102146. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  102147. }
  102148. #else
  102149. if( iCol<0 ){
  102150. zType = "INTEGER";
  102151. }else{
  102152. zType = pTab->aCol[iCol].zType;
  102153. estWidth = pTab->aCol[iCol].szEst;
  102154. }
  102155. #endif
  102156. }
  102157. break;
  102158. }
  102159. #ifndef SQLITE_OMIT_SUBQUERY
  102160. case TK_SELECT: {
  102161. /* The expression is a sub-select. Return the declaration type and
  102162. ** origin info for the single column in the result set of the SELECT
  102163. ** statement.
  102164. */
  102165. NameContext sNC;
  102166. Select *pS = pExpr->x.pSelect;
  102167. Expr *p = pS->pEList->a[0].pExpr;
  102168. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  102169. sNC.pSrcList = pS->pSrc;
  102170. sNC.pNext = pNC;
  102171. sNC.pParse = pNC->pParse;
  102172. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  102173. break;
  102174. }
  102175. #endif
  102176. }
  102177. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  102178. if( pzOrigDb ){
  102179. assert( pzOrigTab && pzOrigCol );
  102180. *pzOrigDb = zOrigDb;
  102181. *pzOrigTab = zOrigTab;
  102182. *pzOrigCol = zOrigCol;
  102183. }
  102184. #endif
  102185. if( pEstWidth ) *pEstWidth = estWidth;
  102186. return zType;
  102187. }
  102188. /*
  102189. ** Generate code that will tell the VDBE the declaration types of columns
  102190. ** in the result set.
  102191. */
  102192. static void generateColumnTypes(
  102193. Parse *pParse, /* Parser context */
  102194. SrcList *pTabList, /* List of tables */
  102195. ExprList *pEList /* Expressions defining the result set */
  102196. ){
  102197. #ifndef SQLITE_OMIT_DECLTYPE
  102198. Vdbe *v = pParse->pVdbe;
  102199. int i;
  102200. NameContext sNC;
  102201. sNC.pSrcList = pTabList;
  102202. sNC.pParse = pParse;
  102203. for(i=0; i<pEList->nExpr; i++){
  102204. Expr *p = pEList->a[i].pExpr;
  102205. const char *zType;
  102206. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  102207. const char *zOrigDb = 0;
  102208. const char *zOrigTab = 0;
  102209. const char *zOrigCol = 0;
  102210. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  102211. /* The vdbe must make its own copy of the column-type and other
  102212. ** column specific strings, in case the schema is reset before this
  102213. ** virtual machine is deleted.
  102214. */
  102215. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  102216. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  102217. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  102218. #else
  102219. zType = columnType(&sNC, p, 0, 0, 0, 0);
  102220. #endif
  102221. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  102222. }
  102223. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  102224. }
  102225. /*
  102226. ** Generate code that will tell the VDBE the names of columns
  102227. ** in the result set. This information is used to provide the
  102228. ** azCol[] values in the callback.
  102229. */
  102230. static void generateColumnNames(
  102231. Parse *pParse, /* Parser context */
  102232. SrcList *pTabList, /* List of tables */
  102233. ExprList *pEList /* Expressions defining the result set */
  102234. ){
  102235. Vdbe *v = pParse->pVdbe;
  102236. int i, j;
  102237. sqlite3 *db = pParse->db;
  102238. int fullNames, shortNames;
  102239. #ifndef SQLITE_OMIT_EXPLAIN
  102240. /* If this is an EXPLAIN, skip this step */
  102241. if( pParse->explain ){
  102242. return;
  102243. }
  102244. #endif
  102245. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  102246. pParse->colNamesSet = 1;
  102247. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  102248. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  102249. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  102250. for(i=0; i<pEList->nExpr; i++){
  102251. Expr *p;
  102252. p = pEList->a[i].pExpr;
  102253. if( NEVER(p==0) ) continue;
  102254. if( pEList->a[i].zName ){
  102255. char *zName = pEList->a[i].zName;
  102256. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  102257. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  102258. Table *pTab;
  102259. char *zCol;
  102260. int iCol = p->iColumn;
  102261. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  102262. if( pTabList->a[j].iCursor==p->iTable ) break;
  102263. }
  102264. assert( j<pTabList->nSrc );
  102265. pTab = pTabList->a[j].pTab;
  102266. if( iCol<0 ) iCol = pTab->iPKey;
  102267. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  102268. if( iCol<0 ){
  102269. zCol = "rowid";
  102270. }else{
  102271. zCol = pTab->aCol[iCol].zName;
  102272. }
  102273. if( !shortNames && !fullNames ){
  102274. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  102275. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  102276. }else if( fullNames ){
  102277. char *zName = 0;
  102278. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  102279. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  102280. }else{
  102281. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  102282. }
  102283. }else{
  102284. const char *z = pEList->a[i].zSpan;
  102285. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  102286. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  102287. }
  102288. }
  102289. generateColumnTypes(pParse, pTabList, pEList);
  102290. }
  102291. /*
  102292. ** Given an expression list (which is really the list of expressions
  102293. ** that form the result set of a SELECT statement) compute appropriate
  102294. ** column names for a table that would hold the expression list.
  102295. **
  102296. ** All column names will be unique.
  102297. **
  102298. ** Only the column names are computed. Column.zType, Column.zColl,
  102299. ** and other fields of Column are zeroed.
  102300. **
  102301. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  102302. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  102303. */
  102304. static int selectColumnsFromExprList(
  102305. Parse *pParse, /* Parsing context */
  102306. ExprList *pEList, /* Expr list from which to derive column names */
  102307. i16 *pnCol, /* Write the number of columns here */
  102308. Column **paCol /* Write the new column list here */
  102309. ){
  102310. sqlite3 *db = pParse->db; /* Database connection */
  102311. int i, j; /* Loop counters */
  102312. int cnt; /* Index added to make the name unique */
  102313. Column *aCol, *pCol; /* For looping over result columns */
  102314. int nCol; /* Number of columns in the result set */
  102315. Expr *p; /* Expression for a single result column */
  102316. char *zName; /* Column name */
  102317. int nName; /* Size of name in zName[] */
  102318. if( pEList ){
  102319. nCol = pEList->nExpr;
  102320. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  102321. testcase( aCol==0 );
  102322. }else{
  102323. nCol = 0;
  102324. aCol = 0;
  102325. }
  102326. *pnCol = nCol;
  102327. *paCol = aCol;
  102328. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  102329. /* Get an appropriate name for the column
  102330. */
  102331. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  102332. if( (zName = pEList->a[i].zName)!=0 ){
  102333. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  102334. zName = sqlite3DbStrDup(db, zName);
  102335. }else{
  102336. Expr *pColExpr = p; /* The expression that is the result column name */
  102337. Table *pTab; /* Table associated with this expression */
  102338. while( pColExpr->op==TK_DOT ){
  102339. pColExpr = pColExpr->pRight;
  102340. assert( pColExpr!=0 );
  102341. }
  102342. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  102343. /* For columns use the column name name */
  102344. int iCol = pColExpr->iColumn;
  102345. pTab = pColExpr->pTab;
  102346. if( iCol<0 ) iCol = pTab->iPKey;
  102347. zName = sqlite3MPrintf(db, "%s",
  102348. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  102349. }else if( pColExpr->op==TK_ID ){
  102350. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  102351. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  102352. }else{
  102353. /* Use the original text of the column expression as its name */
  102354. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  102355. }
  102356. }
  102357. if( db->mallocFailed ){
  102358. sqlite3DbFree(db, zName);
  102359. break;
  102360. }
  102361. /* Make sure the column name is unique. If the name is not unique,
  102362. ** append an integer to the name so that it becomes unique.
  102363. */
  102364. nName = sqlite3Strlen30(zName);
  102365. for(j=cnt=0; j<i; j++){
  102366. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  102367. char *zNewName;
  102368. int k;
  102369. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  102370. if( k>=0 && zName[k]==':' ) nName = k;
  102371. zName[nName] = 0;
  102372. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  102373. sqlite3DbFree(db, zName);
  102374. zName = zNewName;
  102375. j = -1;
  102376. if( zName==0 ) break;
  102377. }
  102378. }
  102379. pCol->zName = zName;
  102380. }
  102381. if( db->mallocFailed ){
  102382. for(j=0; j<i; j++){
  102383. sqlite3DbFree(db, aCol[j].zName);
  102384. }
  102385. sqlite3DbFree(db, aCol);
  102386. *paCol = 0;
  102387. *pnCol = 0;
  102388. return SQLITE_NOMEM;
  102389. }
  102390. return SQLITE_OK;
  102391. }
  102392. /*
  102393. ** Add type and collation information to a column list based on
  102394. ** a SELECT statement.
  102395. **
  102396. ** The column list presumably came from selectColumnNamesFromExprList().
  102397. ** The column list has only names, not types or collations. This
  102398. ** routine goes through and adds the types and collations.
  102399. **
  102400. ** This routine requires that all identifiers in the SELECT
  102401. ** statement be resolved.
  102402. */
  102403. static void selectAddColumnTypeAndCollation(
  102404. Parse *pParse, /* Parsing contexts */
  102405. Table *pTab, /* Add column type information to this table */
  102406. Select *pSelect /* SELECT used to determine types and collations */
  102407. ){
  102408. sqlite3 *db = pParse->db;
  102409. NameContext sNC;
  102410. Column *pCol;
  102411. CollSeq *pColl;
  102412. int i;
  102413. Expr *p;
  102414. struct ExprList_item *a;
  102415. u64 szAll = 0;
  102416. assert( pSelect!=0 );
  102417. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  102418. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  102419. if( db->mallocFailed ) return;
  102420. memset(&sNC, 0, sizeof(sNC));
  102421. sNC.pSrcList = pSelect->pSrc;
  102422. a = pSelect->pEList->a;
  102423. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  102424. p = a[i].pExpr;
  102425. if( pCol->zType==0 ){
  102426. pCol->zType = sqlite3DbStrDup(db,
  102427. columnType(&sNC, p,0,0,0, &pCol->szEst));
  102428. }
  102429. szAll += pCol->szEst;
  102430. pCol->affinity = sqlite3ExprAffinity(p);
  102431. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
  102432. pColl = sqlite3ExprCollSeq(pParse, p);
  102433. if( pColl && pCol->zColl==0 ){
  102434. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  102435. }
  102436. }
  102437. pTab->szTabRow = sqlite3LogEst(szAll*4);
  102438. }
  102439. /*
  102440. ** Given a SELECT statement, generate a Table structure that describes
  102441. ** the result set of that SELECT.
  102442. */
  102443. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  102444. Table *pTab;
  102445. sqlite3 *db = pParse->db;
  102446. int savedFlags;
  102447. savedFlags = db->flags;
  102448. db->flags &= ~SQLITE_FullColNames;
  102449. db->flags |= SQLITE_ShortColNames;
  102450. sqlite3SelectPrep(pParse, pSelect, 0);
  102451. if( pParse->nErr ) return 0;
  102452. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  102453. db->flags = savedFlags;
  102454. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  102455. if( pTab==0 ){
  102456. return 0;
  102457. }
  102458. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  102459. ** is disabled */
  102460. assert( db->lookaside.bEnabled==0 );
  102461. pTab->nRef = 1;
  102462. pTab->zName = 0;
  102463. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  102464. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  102465. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  102466. pTab->iPKey = -1;
  102467. if( db->mallocFailed ){
  102468. sqlite3DeleteTable(db, pTab);
  102469. return 0;
  102470. }
  102471. return pTab;
  102472. }
  102473. /*
  102474. ** Get a VDBE for the given parser context. Create a new one if necessary.
  102475. ** If an error occurs, return NULL and leave a message in pParse.
  102476. */
  102477. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  102478. Vdbe *v = pParse->pVdbe;
  102479. if( v==0 ){
  102480. v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  102481. if( v ) sqlite3VdbeAddOp0(v, OP_Init);
  102482. if( pParse->pToplevel==0
  102483. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  102484. ){
  102485. pParse->okConstFactor = 1;
  102486. }
  102487. }
  102488. return v;
  102489. }
  102490. /*
  102491. ** Compute the iLimit and iOffset fields of the SELECT based on the
  102492. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  102493. ** that appear in the original SQL statement after the LIMIT and OFFSET
  102494. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  102495. ** are the integer memory register numbers for counters used to compute
  102496. ** the limit and offset. If there is no limit and/or offset, then
  102497. ** iLimit and iOffset are negative.
  102498. **
  102499. ** This routine changes the values of iLimit and iOffset only if
  102500. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  102501. ** iOffset should have been preset to appropriate default values (zero)
  102502. ** prior to calling this routine.
  102503. **
  102504. ** The iOffset register (if it exists) is initialized to the value
  102505. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  102506. ** iOffset+1 is initialized to LIMIT+OFFSET.
  102507. **
  102508. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  102509. ** redefined. The UNION ALL operator uses this property to force
  102510. ** the reuse of the same limit and offset registers across multiple
  102511. ** SELECT statements.
  102512. */
  102513. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  102514. Vdbe *v = 0;
  102515. int iLimit = 0;
  102516. int iOffset;
  102517. int addr1, n;
  102518. if( p->iLimit ) return;
  102519. /*
  102520. ** "LIMIT -1" always shows all rows. There is some
  102521. ** controversy about what the correct behavior should be.
  102522. ** The current implementation interprets "LIMIT 0" to mean
  102523. ** no rows.
  102524. */
  102525. sqlite3ExprCacheClear(pParse);
  102526. assert( p->pOffset==0 || p->pLimit!=0 );
  102527. if( p->pLimit ){
  102528. p->iLimit = iLimit = ++pParse->nMem;
  102529. v = sqlite3GetVdbe(pParse);
  102530. assert( v!=0 );
  102531. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  102532. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  102533. VdbeComment((v, "LIMIT counter"));
  102534. if( n==0 ){
  102535. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  102536. }else if( n>=0 && p->nSelectRow>(u64)n ){
  102537. p->nSelectRow = n;
  102538. }
  102539. }else{
  102540. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  102541. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  102542. VdbeComment((v, "LIMIT counter"));
  102543. sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
  102544. }
  102545. if( p->pOffset ){
  102546. p->iOffset = iOffset = ++pParse->nMem;
  102547. pParse->nMem++; /* Allocate an extra register for limit+offset */
  102548. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  102549. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  102550. VdbeComment((v, "OFFSET counter"));
  102551. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
  102552. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  102553. sqlite3VdbeJumpHere(v, addr1);
  102554. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  102555. VdbeComment((v, "LIMIT+OFFSET"));
  102556. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
  102557. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  102558. sqlite3VdbeJumpHere(v, addr1);
  102559. }
  102560. }
  102561. }
  102562. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  102563. /*
  102564. ** Return the appropriate collating sequence for the iCol-th column of
  102565. ** the result set for the compound-select statement "p". Return NULL if
  102566. ** the column has no default collating sequence.
  102567. **
  102568. ** The collating sequence for the compound select is taken from the
  102569. ** left-most term of the select that has a collating sequence.
  102570. */
  102571. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  102572. CollSeq *pRet;
  102573. if( p->pPrior ){
  102574. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  102575. }else{
  102576. pRet = 0;
  102577. }
  102578. assert( iCol>=0 );
  102579. /* iCol must be less than p->pEList->nExpr. Otherwise an error would
  102580. ** have been thrown during name resolution and we would not have gotten
  102581. ** this far */
  102582. if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
  102583. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  102584. }
  102585. return pRet;
  102586. }
  102587. /*
  102588. ** The select statement passed as the second parameter is a compound SELECT
  102589. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  102590. ** structure suitable for implementing the ORDER BY.
  102591. **
  102592. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  102593. ** function is responsible for ensuring that this structure is eventually
  102594. ** freed.
  102595. */
  102596. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  102597. ExprList *pOrderBy = p->pOrderBy;
  102598. int nOrderBy = p->pOrderBy->nExpr;
  102599. sqlite3 *db = pParse->db;
  102600. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  102601. if( pRet ){
  102602. int i;
  102603. for(i=0; i<nOrderBy; i++){
  102604. struct ExprList_item *pItem = &pOrderBy->a[i];
  102605. Expr *pTerm = pItem->pExpr;
  102606. CollSeq *pColl;
  102607. if( pTerm->flags & EP_Collate ){
  102608. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  102609. }else{
  102610. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  102611. if( pColl==0 ) pColl = db->pDfltColl;
  102612. pOrderBy->a[i].pExpr =
  102613. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  102614. }
  102615. assert( sqlite3KeyInfoIsWriteable(pRet) );
  102616. pRet->aColl[i] = pColl;
  102617. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  102618. }
  102619. }
  102620. return pRet;
  102621. }
  102622. #ifndef SQLITE_OMIT_CTE
  102623. /*
  102624. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  102625. ** query of the form:
  102626. **
  102627. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  102628. ** \___________/ \_______________/
  102629. ** p->pPrior p
  102630. **
  102631. **
  102632. ** There is exactly one reference to the recursive-table in the FROM clause
  102633. ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
  102634. **
  102635. ** The setup-query runs once to generate an initial set of rows that go
  102636. ** into a Queue table. Rows are extracted from the Queue table one by
  102637. ** one. Each row extracted from Queue is output to pDest. Then the single
  102638. ** extracted row (now in the iCurrent table) becomes the content of the
  102639. ** recursive-table for a recursive-query run. The output of the recursive-query
  102640. ** is added back into the Queue table. Then another row is extracted from Queue
  102641. ** and the iteration continues until the Queue table is empty.
  102642. **
  102643. ** If the compound query operator is UNION then no duplicate rows are ever
  102644. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  102645. ** that have ever been inserted into Queue and causes duplicates to be
  102646. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  102647. **
  102648. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  102649. ** ORDER BY order and the first entry is extracted for each cycle. Without
  102650. ** an ORDER BY, the Queue table is just a FIFO.
  102651. **
  102652. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  102653. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  102654. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  102655. ** with a positive value, then the first OFFSET outputs are discarded rather
  102656. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  102657. ** rows have been skipped.
  102658. */
  102659. static void generateWithRecursiveQuery(
  102660. Parse *pParse, /* Parsing context */
  102661. Select *p, /* The recursive SELECT to be coded */
  102662. SelectDest *pDest /* What to do with query results */
  102663. ){
  102664. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  102665. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  102666. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  102667. Select *pSetup = p->pPrior; /* The setup query */
  102668. int addrTop; /* Top of the loop */
  102669. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  102670. int iCurrent = 0; /* The Current table */
  102671. int regCurrent; /* Register holding Current table */
  102672. int iQueue; /* The Queue table */
  102673. int iDistinct = 0; /* To ensure unique results if UNION */
  102674. int eDest = SRT_Fifo; /* How to write to Queue */
  102675. SelectDest destQueue; /* SelectDest targetting the Queue table */
  102676. int i; /* Loop counter */
  102677. int rc; /* Result code */
  102678. ExprList *pOrderBy; /* The ORDER BY clause */
  102679. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  102680. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  102681. /* Obtain authorization to do a recursive query */
  102682. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  102683. /* Process the LIMIT and OFFSET clauses, if they exist */
  102684. addrBreak = sqlite3VdbeMakeLabel(v);
  102685. computeLimitRegisters(pParse, p, addrBreak);
  102686. pLimit = p->pLimit;
  102687. pOffset = p->pOffset;
  102688. regLimit = p->iLimit;
  102689. regOffset = p->iOffset;
  102690. p->pLimit = p->pOffset = 0;
  102691. p->iLimit = p->iOffset = 0;
  102692. pOrderBy = p->pOrderBy;
  102693. /* Locate the cursor number of the Current table */
  102694. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  102695. if( pSrc->a[i].isRecursive ){
  102696. iCurrent = pSrc->a[i].iCursor;
  102697. break;
  102698. }
  102699. }
  102700. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  102701. ** the Distinct table must be exactly one greater than Queue in order
  102702. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  102703. iQueue = pParse->nTab++;
  102704. if( p->op==TK_UNION ){
  102705. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  102706. iDistinct = pParse->nTab++;
  102707. }else{
  102708. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  102709. }
  102710. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  102711. /* Allocate cursors for Current, Queue, and Distinct. */
  102712. regCurrent = ++pParse->nMem;
  102713. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  102714. if( pOrderBy ){
  102715. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  102716. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  102717. (char*)pKeyInfo, P4_KEYINFO);
  102718. destQueue.pOrderBy = pOrderBy;
  102719. }else{
  102720. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  102721. }
  102722. VdbeComment((v, "Queue table"));
  102723. if( iDistinct ){
  102724. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  102725. p->selFlags |= SF_UsesEphemeral;
  102726. }
  102727. /* Detach the ORDER BY clause from the compound SELECT */
  102728. p->pOrderBy = 0;
  102729. /* Store the results of the setup-query in Queue. */
  102730. pSetup->pNext = 0;
  102731. rc = sqlite3Select(pParse, pSetup, &destQueue);
  102732. pSetup->pNext = p;
  102733. if( rc ) goto end_of_recursive_query;
  102734. /* Find the next row in the Queue and output that row */
  102735. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  102736. /* Transfer the next row in Queue over to Current */
  102737. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  102738. if( pOrderBy ){
  102739. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  102740. }else{
  102741. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  102742. }
  102743. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  102744. /* Output the single row in Current */
  102745. addrCont = sqlite3VdbeMakeLabel(v);
  102746. codeOffset(v, regOffset, addrCont);
  102747. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  102748. 0, 0, pDest, addrCont, addrBreak);
  102749. if( regLimit ){
  102750. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
  102751. VdbeCoverage(v);
  102752. }
  102753. sqlite3VdbeResolveLabel(v, addrCont);
  102754. /* Execute the recursive SELECT taking the single row in Current as
  102755. ** the value for the recursive-table. Store the results in the Queue.
  102756. */
  102757. if( p->selFlags & SF_Aggregate ){
  102758. sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
  102759. }else{
  102760. p->pPrior = 0;
  102761. sqlite3Select(pParse, p, &destQueue);
  102762. assert( p->pPrior==0 );
  102763. p->pPrior = pSetup;
  102764. }
  102765. /* Keep running the loop until the Queue is empty */
  102766. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  102767. sqlite3VdbeResolveLabel(v, addrBreak);
  102768. end_of_recursive_query:
  102769. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  102770. p->pOrderBy = pOrderBy;
  102771. p->pLimit = pLimit;
  102772. p->pOffset = pOffset;
  102773. return;
  102774. }
  102775. #endif /* SQLITE_OMIT_CTE */
  102776. /* Forward references */
  102777. static int multiSelectOrderBy(
  102778. Parse *pParse, /* Parsing context */
  102779. Select *p, /* The right-most of SELECTs to be coded */
  102780. SelectDest *pDest /* What to do with query results */
  102781. );
  102782. /*
  102783. ** Handle the special case of a compound-select that originates from a
  102784. ** VALUES clause. By handling this as a special case, we avoid deep
  102785. ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
  102786. ** on a VALUES clause.
  102787. **
  102788. ** Because the Select object originates from a VALUES clause:
  102789. ** (1) It has no LIMIT or OFFSET
  102790. ** (2) All terms are UNION ALL
  102791. ** (3) There is no ORDER BY clause
  102792. */
  102793. static int multiSelectValues(
  102794. Parse *pParse, /* Parsing context */
  102795. Select *p, /* The right-most of SELECTs to be coded */
  102796. SelectDest *pDest /* What to do with query results */
  102797. ){
  102798. Select *pPrior;
  102799. int nRow = 1;
  102800. int rc = 0;
  102801. assert( p->selFlags & SF_MultiValue );
  102802. do{
  102803. assert( p->selFlags & SF_Values );
  102804. assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
  102805. assert( p->pLimit==0 );
  102806. assert( p->pOffset==0 );
  102807. assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
  102808. if( p->pPrior==0 ) break;
  102809. assert( p->pPrior->pNext==p );
  102810. p = p->pPrior;
  102811. nRow++;
  102812. }while(1);
  102813. while( p ){
  102814. pPrior = p->pPrior;
  102815. p->pPrior = 0;
  102816. rc = sqlite3Select(pParse, p, pDest);
  102817. p->pPrior = pPrior;
  102818. if( rc ) break;
  102819. p->nSelectRow = nRow;
  102820. p = p->pNext;
  102821. }
  102822. return rc;
  102823. }
  102824. /*
  102825. ** This routine is called to process a compound query form from
  102826. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  102827. ** INTERSECT
  102828. **
  102829. ** "p" points to the right-most of the two queries. the query on the
  102830. ** left is p->pPrior. The left query could also be a compound query
  102831. ** in which case this routine will be called recursively.
  102832. **
  102833. ** The results of the total query are to be written into a destination
  102834. ** of type eDest with parameter iParm.
  102835. **
  102836. ** Example 1: Consider a three-way compound SQL statement.
  102837. **
  102838. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  102839. **
  102840. ** This statement is parsed up as follows:
  102841. **
  102842. ** SELECT c FROM t3
  102843. ** |
  102844. ** `-----> SELECT b FROM t2
  102845. ** |
  102846. ** `------> SELECT a FROM t1
  102847. **
  102848. ** The arrows in the diagram above represent the Select.pPrior pointer.
  102849. ** So if this routine is called with p equal to the t3 query, then
  102850. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  102851. **
  102852. ** Notice that because of the way SQLite parses compound SELECTs, the
  102853. ** individual selects always group from left to right.
  102854. */
  102855. static int multiSelect(
  102856. Parse *pParse, /* Parsing context */
  102857. Select *p, /* The right-most of SELECTs to be coded */
  102858. SelectDest *pDest /* What to do with query results */
  102859. ){
  102860. int rc = SQLITE_OK; /* Success code from a subroutine */
  102861. Select *pPrior; /* Another SELECT immediately to our left */
  102862. Vdbe *v; /* Generate code to this VDBE */
  102863. SelectDest dest; /* Alternative data destination */
  102864. Select *pDelete = 0; /* Chain of simple selects to delete */
  102865. sqlite3 *db; /* Database connection */
  102866. #ifndef SQLITE_OMIT_EXPLAIN
  102867. int iSub1 = 0; /* EQP id of left-hand query */
  102868. int iSub2 = 0; /* EQP id of right-hand query */
  102869. #endif
  102870. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  102871. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  102872. */
  102873. assert( p && p->pPrior ); /* Calling function guarantees this much */
  102874. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  102875. db = pParse->db;
  102876. pPrior = p->pPrior;
  102877. dest = *pDest;
  102878. if( pPrior->pOrderBy ){
  102879. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  102880. selectOpName(p->op));
  102881. rc = 1;
  102882. goto multi_select_end;
  102883. }
  102884. if( pPrior->pLimit ){
  102885. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  102886. selectOpName(p->op));
  102887. rc = 1;
  102888. goto multi_select_end;
  102889. }
  102890. v = sqlite3GetVdbe(pParse);
  102891. assert( v!=0 ); /* The VDBE already created by calling function */
  102892. /* Create the destination temporary table if necessary
  102893. */
  102894. if( dest.eDest==SRT_EphemTab ){
  102895. assert( p->pEList );
  102896. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  102897. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  102898. dest.eDest = SRT_Table;
  102899. }
  102900. /* Special handling for a compound-select that originates as a VALUES clause.
  102901. */
  102902. if( p->selFlags & SF_MultiValue ){
  102903. rc = multiSelectValues(pParse, p, &dest);
  102904. goto multi_select_end;
  102905. }
  102906. /* Make sure all SELECTs in the statement have the same number of elements
  102907. ** in their result sets.
  102908. */
  102909. assert( p->pEList && pPrior->pEList );
  102910. assert( p->pEList->nExpr==pPrior->pEList->nExpr );
  102911. #ifndef SQLITE_OMIT_CTE
  102912. if( p->selFlags & SF_Recursive ){
  102913. generateWithRecursiveQuery(pParse, p, &dest);
  102914. }else
  102915. #endif
  102916. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  102917. */
  102918. if( p->pOrderBy ){
  102919. return multiSelectOrderBy(pParse, p, pDest);
  102920. }else
  102921. /* Generate code for the left and right SELECT statements.
  102922. */
  102923. switch( p->op ){
  102924. case TK_ALL: {
  102925. int addr = 0;
  102926. int nLimit;
  102927. assert( !pPrior->pLimit );
  102928. pPrior->iLimit = p->iLimit;
  102929. pPrior->iOffset = p->iOffset;
  102930. pPrior->pLimit = p->pLimit;
  102931. pPrior->pOffset = p->pOffset;
  102932. explainSetInteger(iSub1, pParse->iNextSelectId);
  102933. rc = sqlite3Select(pParse, pPrior, &dest);
  102934. p->pLimit = 0;
  102935. p->pOffset = 0;
  102936. if( rc ){
  102937. goto multi_select_end;
  102938. }
  102939. p->pPrior = 0;
  102940. p->iLimit = pPrior->iLimit;
  102941. p->iOffset = pPrior->iOffset;
  102942. if( p->iLimit ){
  102943. addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
  102944. VdbeComment((v, "Jump ahead if LIMIT reached"));
  102945. }
  102946. explainSetInteger(iSub2, pParse->iNextSelectId);
  102947. rc = sqlite3Select(pParse, p, &dest);
  102948. testcase( rc!=SQLITE_OK );
  102949. pDelete = p->pPrior;
  102950. p->pPrior = pPrior;
  102951. p->nSelectRow += pPrior->nSelectRow;
  102952. if( pPrior->pLimit
  102953. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  102954. && nLimit>0 && p->nSelectRow > (u64)nLimit
  102955. ){
  102956. p->nSelectRow = nLimit;
  102957. }
  102958. if( addr ){
  102959. sqlite3VdbeJumpHere(v, addr);
  102960. }
  102961. break;
  102962. }
  102963. case TK_EXCEPT:
  102964. case TK_UNION: {
  102965. int unionTab; /* Cursor number of the temporary table holding result */
  102966. u8 op = 0; /* One of the SRT_ operations to apply to self */
  102967. int priorOp; /* The SRT_ operation to apply to prior selects */
  102968. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  102969. int addr;
  102970. SelectDest uniondest;
  102971. testcase( p->op==TK_EXCEPT );
  102972. testcase( p->op==TK_UNION );
  102973. priorOp = SRT_Union;
  102974. if( dest.eDest==priorOp ){
  102975. /* We can reuse a temporary table generated by a SELECT to our
  102976. ** right.
  102977. */
  102978. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  102979. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  102980. unionTab = dest.iSDParm;
  102981. }else{
  102982. /* We will need to create our own temporary table to hold the
  102983. ** intermediate results.
  102984. */
  102985. unionTab = pParse->nTab++;
  102986. assert( p->pOrderBy==0 );
  102987. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  102988. assert( p->addrOpenEphm[0] == -1 );
  102989. p->addrOpenEphm[0] = addr;
  102990. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  102991. assert( p->pEList );
  102992. }
  102993. /* Code the SELECT statements to our left
  102994. */
  102995. assert( !pPrior->pOrderBy );
  102996. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  102997. explainSetInteger(iSub1, pParse->iNextSelectId);
  102998. rc = sqlite3Select(pParse, pPrior, &uniondest);
  102999. if( rc ){
  103000. goto multi_select_end;
  103001. }
  103002. /* Code the current SELECT statement
  103003. */
  103004. if( p->op==TK_EXCEPT ){
  103005. op = SRT_Except;
  103006. }else{
  103007. assert( p->op==TK_UNION );
  103008. op = SRT_Union;
  103009. }
  103010. p->pPrior = 0;
  103011. pLimit = p->pLimit;
  103012. p->pLimit = 0;
  103013. pOffset = p->pOffset;
  103014. p->pOffset = 0;
  103015. uniondest.eDest = op;
  103016. explainSetInteger(iSub2, pParse->iNextSelectId);
  103017. rc = sqlite3Select(pParse, p, &uniondest);
  103018. testcase( rc!=SQLITE_OK );
  103019. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  103020. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  103021. sqlite3ExprListDelete(db, p->pOrderBy);
  103022. pDelete = p->pPrior;
  103023. p->pPrior = pPrior;
  103024. p->pOrderBy = 0;
  103025. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  103026. sqlite3ExprDelete(db, p->pLimit);
  103027. p->pLimit = pLimit;
  103028. p->pOffset = pOffset;
  103029. p->iLimit = 0;
  103030. p->iOffset = 0;
  103031. /* Convert the data in the temporary table into whatever form
  103032. ** it is that we currently need.
  103033. */
  103034. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  103035. if( dest.eDest!=priorOp ){
  103036. int iCont, iBreak, iStart;
  103037. assert( p->pEList );
  103038. if( dest.eDest==SRT_Output ){
  103039. Select *pFirst = p;
  103040. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  103041. generateColumnNames(pParse, 0, pFirst->pEList);
  103042. }
  103043. iBreak = sqlite3VdbeMakeLabel(v);
  103044. iCont = sqlite3VdbeMakeLabel(v);
  103045. computeLimitRegisters(pParse, p, iBreak);
  103046. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  103047. iStart = sqlite3VdbeCurrentAddr(v);
  103048. selectInnerLoop(pParse, p, p->pEList, unionTab,
  103049. 0, 0, &dest, iCont, iBreak);
  103050. sqlite3VdbeResolveLabel(v, iCont);
  103051. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  103052. sqlite3VdbeResolveLabel(v, iBreak);
  103053. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  103054. }
  103055. break;
  103056. }
  103057. default: assert( p->op==TK_INTERSECT ); {
  103058. int tab1, tab2;
  103059. int iCont, iBreak, iStart;
  103060. Expr *pLimit, *pOffset;
  103061. int addr;
  103062. SelectDest intersectdest;
  103063. int r1;
  103064. /* INTERSECT is different from the others since it requires
  103065. ** two temporary tables. Hence it has its own case. Begin
  103066. ** by allocating the tables we will need.
  103067. */
  103068. tab1 = pParse->nTab++;
  103069. tab2 = pParse->nTab++;
  103070. assert( p->pOrderBy==0 );
  103071. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  103072. assert( p->addrOpenEphm[0] == -1 );
  103073. p->addrOpenEphm[0] = addr;
  103074. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  103075. assert( p->pEList );
  103076. /* Code the SELECTs to our left into temporary table "tab1".
  103077. */
  103078. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  103079. explainSetInteger(iSub1, pParse->iNextSelectId);
  103080. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  103081. if( rc ){
  103082. goto multi_select_end;
  103083. }
  103084. /* Code the current SELECT into temporary table "tab2"
  103085. */
  103086. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  103087. assert( p->addrOpenEphm[1] == -1 );
  103088. p->addrOpenEphm[1] = addr;
  103089. p->pPrior = 0;
  103090. pLimit = p->pLimit;
  103091. p->pLimit = 0;
  103092. pOffset = p->pOffset;
  103093. p->pOffset = 0;
  103094. intersectdest.iSDParm = tab2;
  103095. explainSetInteger(iSub2, pParse->iNextSelectId);
  103096. rc = sqlite3Select(pParse, p, &intersectdest);
  103097. testcase( rc!=SQLITE_OK );
  103098. pDelete = p->pPrior;
  103099. p->pPrior = pPrior;
  103100. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  103101. sqlite3ExprDelete(db, p->pLimit);
  103102. p->pLimit = pLimit;
  103103. p->pOffset = pOffset;
  103104. /* Generate code to take the intersection of the two temporary
  103105. ** tables.
  103106. */
  103107. assert( p->pEList );
  103108. if( dest.eDest==SRT_Output ){
  103109. Select *pFirst = p;
  103110. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  103111. generateColumnNames(pParse, 0, pFirst->pEList);
  103112. }
  103113. iBreak = sqlite3VdbeMakeLabel(v);
  103114. iCont = sqlite3VdbeMakeLabel(v);
  103115. computeLimitRegisters(pParse, p, iBreak);
  103116. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  103117. r1 = sqlite3GetTempReg(pParse);
  103118. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  103119. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  103120. sqlite3ReleaseTempReg(pParse, r1);
  103121. selectInnerLoop(pParse, p, p->pEList, tab1,
  103122. 0, 0, &dest, iCont, iBreak);
  103123. sqlite3VdbeResolveLabel(v, iCont);
  103124. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  103125. sqlite3VdbeResolveLabel(v, iBreak);
  103126. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  103127. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  103128. break;
  103129. }
  103130. }
  103131. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  103132. /* Compute collating sequences used by
  103133. ** temporary tables needed to implement the compound select.
  103134. ** Attach the KeyInfo structure to all temporary tables.
  103135. **
  103136. ** This section is run by the right-most SELECT statement only.
  103137. ** SELECT statements to the left always skip this part. The right-most
  103138. ** SELECT might also skip this part if it has no ORDER BY clause and
  103139. ** no temp tables are required.
  103140. */
  103141. if( p->selFlags & SF_UsesEphemeral ){
  103142. int i; /* Loop counter */
  103143. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  103144. Select *pLoop; /* For looping through SELECT statements */
  103145. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  103146. int nCol; /* Number of columns in result set */
  103147. assert( p->pNext==0 );
  103148. nCol = p->pEList->nExpr;
  103149. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  103150. if( !pKeyInfo ){
  103151. rc = SQLITE_NOMEM;
  103152. goto multi_select_end;
  103153. }
  103154. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  103155. *apColl = multiSelectCollSeq(pParse, p, i);
  103156. if( 0==*apColl ){
  103157. *apColl = db->pDfltColl;
  103158. }
  103159. }
  103160. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  103161. for(i=0; i<2; i++){
  103162. int addr = pLoop->addrOpenEphm[i];
  103163. if( addr<0 ){
  103164. /* If [0] is unused then [1] is also unused. So we can
  103165. ** always safely abort as soon as the first unused slot is found */
  103166. assert( pLoop->addrOpenEphm[1]<0 );
  103167. break;
  103168. }
  103169. sqlite3VdbeChangeP2(v, addr, nCol);
  103170. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  103171. P4_KEYINFO);
  103172. pLoop->addrOpenEphm[i] = -1;
  103173. }
  103174. }
  103175. sqlite3KeyInfoUnref(pKeyInfo);
  103176. }
  103177. multi_select_end:
  103178. pDest->iSdst = dest.iSdst;
  103179. pDest->nSdst = dest.nSdst;
  103180. sqlite3SelectDelete(db, pDelete);
  103181. return rc;
  103182. }
  103183. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  103184. /*
  103185. ** Error message for when two or more terms of a compound select have different
  103186. ** size result sets.
  103187. */
  103188. SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
  103189. if( p->selFlags & SF_Values ){
  103190. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  103191. }else{
  103192. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  103193. " do not have the same number of result columns", selectOpName(p->op));
  103194. }
  103195. }
  103196. /*
  103197. ** Code an output subroutine for a coroutine implementation of a
  103198. ** SELECT statment.
  103199. **
  103200. ** The data to be output is contained in pIn->iSdst. There are
  103201. ** pIn->nSdst columns to be output. pDest is where the output should
  103202. ** be sent.
  103203. **
  103204. ** regReturn is the number of the register holding the subroutine
  103205. ** return address.
  103206. **
  103207. ** If regPrev>0 then it is the first register in a vector that
  103208. ** records the previous output. mem[regPrev] is a flag that is false
  103209. ** if there has been no previous output. If regPrev>0 then code is
  103210. ** generated to suppress duplicates. pKeyInfo is used for comparing
  103211. ** keys.
  103212. **
  103213. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  103214. ** iBreak.
  103215. */
  103216. static int generateOutputSubroutine(
  103217. Parse *pParse, /* Parsing context */
  103218. Select *p, /* The SELECT statement */
  103219. SelectDest *pIn, /* Coroutine supplying data */
  103220. SelectDest *pDest, /* Where to send the data */
  103221. int regReturn, /* The return address register */
  103222. int regPrev, /* Previous result register. No uniqueness if 0 */
  103223. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  103224. int iBreak /* Jump here if we hit the LIMIT */
  103225. ){
  103226. Vdbe *v = pParse->pVdbe;
  103227. int iContinue;
  103228. int addr;
  103229. addr = sqlite3VdbeCurrentAddr(v);
  103230. iContinue = sqlite3VdbeMakeLabel(v);
  103231. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  103232. */
  103233. if( regPrev ){
  103234. int j1, j2;
  103235. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  103236. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  103237. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  103238. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
  103239. sqlite3VdbeJumpHere(v, j1);
  103240. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  103241. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  103242. }
  103243. if( pParse->db->mallocFailed ) return 0;
  103244. /* Suppress the first OFFSET entries if there is an OFFSET clause
  103245. */
  103246. codeOffset(v, p->iOffset, iContinue);
  103247. assert( pDest->eDest!=SRT_Exists );
  103248. assert( pDest->eDest!=SRT_Table );
  103249. switch( pDest->eDest ){
  103250. /* Store the result as data using a unique key.
  103251. */
  103252. case SRT_EphemTab: {
  103253. int r1 = sqlite3GetTempReg(pParse);
  103254. int r2 = sqlite3GetTempReg(pParse);
  103255. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  103256. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  103257. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  103258. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  103259. sqlite3ReleaseTempReg(pParse, r2);
  103260. sqlite3ReleaseTempReg(pParse, r1);
  103261. break;
  103262. }
  103263. #ifndef SQLITE_OMIT_SUBQUERY
  103264. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  103265. ** then there should be a single item on the stack. Write this
  103266. ** item into the set table with bogus data.
  103267. */
  103268. case SRT_Set: {
  103269. int r1;
  103270. assert( pIn->nSdst==1 || pParse->nErr>0 );
  103271. pDest->affSdst =
  103272. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  103273. r1 = sqlite3GetTempReg(pParse);
  103274. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  103275. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  103276. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  103277. sqlite3ReleaseTempReg(pParse, r1);
  103278. break;
  103279. }
  103280. /* If this is a scalar select that is part of an expression, then
  103281. ** store the results in the appropriate memory cell and break out
  103282. ** of the scan loop.
  103283. */
  103284. case SRT_Mem: {
  103285. assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
  103286. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  103287. /* The LIMIT clause will jump out of the loop for us */
  103288. break;
  103289. }
  103290. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  103291. /* The results are stored in a sequence of registers
  103292. ** starting at pDest->iSdst. Then the co-routine yields.
  103293. */
  103294. case SRT_Coroutine: {
  103295. if( pDest->iSdst==0 ){
  103296. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  103297. pDest->nSdst = pIn->nSdst;
  103298. }
  103299. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
  103300. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  103301. break;
  103302. }
  103303. /* If none of the above, then the result destination must be
  103304. ** SRT_Output. This routine is never called with any other
  103305. ** destination other than the ones handled above or SRT_Output.
  103306. **
  103307. ** For SRT_Output, results are stored in a sequence of registers.
  103308. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  103309. ** return the next row of result.
  103310. */
  103311. default: {
  103312. assert( pDest->eDest==SRT_Output );
  103313. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  103314. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  103315. break;
  103316. }
  103317. }
  103318. /* Jump to the end of the loop if the LIMIT is reached.
  103319. */
  103320. if( p->iLimit ){
  103321. sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
  103322. }
  103323. /* Generate the subroutine return
  103324. */
  103325. sqlite3VdbeResolveLabel(v, iContinue);
  103326. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  103327. return addr;
  103328. }
  103329. /*
  103330. ** Alternative compound select code generator for cases when there
  103331. ** is an ORDER BY clause.
  103332. **
  103333. ** We assume a query of the following form:
  103334. **
  103335. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  103336. **
  103337. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  103338. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  103339. ** co-routines. Then run the co-routines in parallel and merge the results
  103340. ** into the output. In addition to the two coroutines (called selectA and
  103341. ** selectB) there are 7 subroutines:
  103342. **
  103343. ** outA: Move the output of the selectA coroutine into the output
  103344. ** of the compound query.
  103345. **
  103346. ** outB: Move the output of the selectB coroutine into the output
  103347. ** of the compound query. (Only generated for UNION and
  103348. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  103349. ** appears only in B.)
  103350. **
  103351. ** AltB: Called when there is data from both coroutines and A<B.
  103352. **
  103353. ** AeqB: Called when there is data from both coroutines and A==B.
  103354. **
  103355. ** AgtB: Called when there is data from both coroutines and A>B.
  103356. **
  103357. ** EofA: Called when data is exhausted from selectA.
  103358. **
  103359. ** EofB: Called when data is exhausted from selectB.
  103360. **
  103361. ** The implementation of the latter five subroutines depend on which
  103362. ** <operator> is used:
  103363. **
  103364. **
  103365. ** UNION ALL UNION EXCEPT INTERSECT
  103366. ** ------------- ----------------- -------------- -----------------
  103367. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  103368. **
  103369. ** AeqB: outA, nextA nextA nextA outA, nextA
  103370. **
  103371. ** AgtB: outB, nextB outB, nextB nextB nextB
  103372. **
  103373. ** EofA: outB, nextB outB, nextB halt halt
  103374. **
  103375. ** EofB: outA, nextA outA, nextA outA, nextA halt
  103376. **
  103377. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  103378. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  103379. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  103380. ** following nextX causes a jump to the end of the select processing.
  103381. **
  103382. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  103383. ** within the output subroutine. The regPrev register set holds the previously
  103384. ** output value. A comparison is made against this value and the output
  103385. ** is skipped if the next results would be the same as the previous.
  103386. **
  103387. ** The implementation plan is to implement the two coroutines and seven
  103388. ** subroutines first, then put the control logic at the bottom. Like this:
  103389. **
  103390. ** goto Init
  103391. ** coA: coroutine for left query (A)
  103392. ** coB: coroutine for right query (B)
  103393. ** outA: output one row of A
  103394. ** outB: output one row of B (UNION and UNION ALL only)
  103395. ** EofA: ...
  103396. ** EofB: ...
  103397. ** AltB: ...
  103398. ** AeqB: ...
  103399. ** AgtB: ...
  103400. ** Init: initialize coroutine registers
  103401. ** yield coA
  103402. ** if eof(A) goto EofA
  103403. ** yield coB
  103404. ** if eof(B) goto EofB
  103405. ** Cmpr: Compare A, B
  103406. ** Jump AltB, AeqB, AgtB
  103407. ** End: ...
  103408. **
  103409. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  103410. ** actually called using Gosub and they do not Return. EofA and EofB loop
  103411. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  103412. ** and AgtB jump to either L2 or to one of EofA or EofB.
  103413. */
  103414. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  103415. static int multiSelectOrderBy(
  103416. Parse *pParse, /* Parsing context */
  103417. Select *p, /* The right-most of SELECTs to be coded */
  103418. SelectDest *pDest /* What to do with query results */
  103419. ){
  103420. int i, j; /* Loop counters */
  103421. Select *pPrior; /* Another SELECT immediately to our left */
  103422. Vdbe *v; /* Generate code to this VDBE */
  103423. SelectDest destA; /* Destination for coroutine A */
  103424. SelectDest destB; /* Destination for coroutine B */
  103425. int regAddrA; /* Address register for select-A coroutine */
  103426. int regAddrB; /* Address register for select-B coroutine */
  103427. int addrSelectA; /* Address of the select-A coroutine */
  103428. int addrSelectB; /* Address of the select-B coroutine */
  103429. int regOutA; /* Address register for the output-A subroutine */
  103430. int regOutB; /* Address register for the output-B subroutine */
  103431. int addrOutA; /* Address of the output-A subroutine */
  103432. int addrOutB = 0; /* Address of the output-B subroutine */
  103433. int addrEofA; /* Address of the select-A-exhausted subroutine */
  103434. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  103435. int addrEofB; /* Address of the select-B-exhausted subroutine */
  103436. int addrAltB; /* Address of the A<B subroutine */
  103437. int addrAeqB; /* Address of the A==B subroutine */
  103438. int addrAgtB; /* Address of the A>B subroutine */
  103439. int regLimitA; /* Limit register for select-A */
  103440. int regLimitB; /* Limit register for select-A */
  103441. int regPrev; /* A range of registers to hold previous output */
  103442. int savedLimit; /* Saved value of p->iLimit */
  103443. int savedOffset; /* Saved value of p->iOffset */
  103444. int labelCmpr; /* Label for the start of the merge algorithm */
  103445. int labelEnd; /* Label for the end of the overall SELECT stmt */
  103446. int j1; /* Jump instructions that get retargetted */
  103447. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  103448. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  103449. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  103450. sqlite3 *db; /* Database connection */
  103451. ExprList *pOrderBy; /* The ORDER BY clause */
  103452. int nOrderBy; /* Number of terms in the ORDER BY clause */
  103453. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  103454. #ifndef SQLITE_OMIT_EXPLAIN
  103455. int iSub1; /* EQP id of left-hand query */
  103456. int iSub2; /* EQP id of right-hand query */
  103457. #endif
  103458. assert( p->pOrderBy!=0 );
  103459. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  103460. db = pParse->db;
  103461. v = pParse->pVdbe;
  103462. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  103463. labelEnd = sqlite3VdbeMakeLabel(v);
  103464. labelCmpr = sqlite3VdbeMakeLabel(v);
  103465. /* Patch up the ORDER BY clause
  103466. */
  103467. op = p->op;
  103468. pPrior = p->pPrior;
  103469. assert( pPrior->pOrderBy==0 );
  103470. pOrderBy = p->pOrderBy;
  103471. assert( pOrderBy );
  103472. nOrderBy = pOrderBy->nExpr;
  103473. /* For operators other than UNION ALL we have to make sure that
  103474. ** the ORDER BY clause covers every term of the result set. Add
  103475. ** terms to the ORDER BY clause as necessary.
  103476. */
  103477. if( op!=TK_ALL ){
  103478. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  103479. struct ExprList_item *pItem;
  103480. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  103481. assert( pItem->u.x.iOrderByCol>0 );
  103482. if( pItem->u.x.iOrderByCol==i ) break;
  103483. }
  103484. if( j==nOrderBy ){
  103485. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  103486. if( pNew==0 ) return SQLITE_NOMEM;
  103487. pNew->flags |= EP_IntValue;
  103488. pNew->u.iValue = i;
  103489. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  103490. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  103491. }
  103492. }
  103493. }
  103494. /* Compute the comparison permutation and keyinfo that is used with
  103495. ** the permutation used to determine if the next
  103496. ** row of results comes from selectA or selectB. Also add explicit
  103497. ** collations to the ORDER BY clause terms so that when the subqueries
  103498. ** to the right and the left are evaluated, they use the correct
  103499. ** collation.
  103500. */
  103501. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  103502. if( aPermute ){
  103503. struct ExprList_item *pItem;
  103504. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  103505. assert( pItem->u.x.iOrderByCol>0 );
  103506. assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  103507. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  103508. }
  103509. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  103510. }else{
  103511. pKeyMerge = 0;
  103512. }
  103513. /* Reattach the ORDER BY clause to the query.
  103514. */
  103515. p->pOrderBy = pOrderBy;
  103516. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  103517. /* Allocate a range of temporary registers and the KeyInfo needed
  103518. ** for the logic that removes duplicate result rows when the
  103519. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  103520. */
  103521. if( op==TK_ALL ){
  103522. regPrev = 0;
  103523. }else{
  103524. int nExpr = p->pEList->nExpr;
  103525. assert( nOrderBy>=nExpr || db->mallocFailed );
  103526. regPrev = pParse->nMem+1;
  103527. pParse->nMem += nExpr+1;
  103528. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  103529. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  103530. if( pKeyDup ){
  103531. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  103532. for(i=0; i<nExpr; i++){
  103533. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  103534. pKeyDup->aSortOrder[i] = 0;
  103535. }
  103536. }
  103537. }
  103538. /* Separate the left and the right query from one another
  103539. */
  103540. p->pPrior = 0;
  103541. pPrior->pNext = 0;
  103542. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  103543. if( pPrior->pPrior==0 ){
  103544. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  103545. }
  103546. /* Compute the limit registers */
  103547. computeLimitRegisters(pParse, p, labelEnd);
  103548. if( p->iLimit && op==TK_ALL ){
  103549. regLimitA = ++pParse->nMem;
  103550. regLimitB = ++pParse->nMem;
  103551. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  103552. regLimitA);
  103553. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  103554. }else{
  103555. regLimitA = regLimitB = 0;
  103556. }
  103557. sqlite3ExprDelete(db, p->pLimit);
  103558. p->pLimit = 0;
  103559. sqlite3ExprDelete(db, p->pOffset);
  103560. p->pOffset = 0;
  103561. regAddrA = ++pParse->nMem;
  103562. regAddrB = ++pParse->nMem;
  103563. regOutA = ++pParse->nMem;
  103564. regOutB = ++pParse->nMem;
  103565. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  103566. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  103567. /* Generate a coroutine to evaluate the SELECT statement to the
  103568. ** left of the compound operator - the "A" select.
  103569. */
  103570. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  103571. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  103572. VdbeComment((v, "left SELECT"));
  103573. pPrior->iLimit = regLimitA;
  103574. explainSetInteger(iSub1, pParse->iNextSelectId);
  103575. sqlite3Select(pParse, pPrior, &destA);
  103576. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
  103577. sqlite3VdbeJumpHere(v, j1);
  103578. /* Generate a coroutine to evaluate the SELECT statement on
  103579. ** the right - the "B" select
  103580. */
  103581. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  103582. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  103583. VdbeComment((v, "right SELECT"));
  103584. savedLimit = p->iLimit;
  103585. savedOffset = p->iOffset;
  103586. p->iLimit = regLimitB;
  103587. p->iOffset = 0;
  103588. explainSetInteger(iSub2, pParse->iNextSelectId);
  103589. sqlite3Select(pParse, p, &destB);
  103590. p->iLimit = savedLimit;
  103591. p->iOffset = savedOffset;
  103592. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
  103593. /* Generate a subroutine that outputs the current row of the A
  103594. ** select as the next output row of the compound select.
  103595. */
  103596. VdbeNoopComment((v, "Output routine for A"));
  103597. addrOutA = generateOutputSubroutine(pParse,
  103598. p, &destA, pDest, regOutA,
  103599. regPrev, pKeyDup, labelEnd);
  103600. /* Generate a subroutine that outputs the current row of the B
  103601. ** select as the next output row of the compound select.
  103602. */
  103603. if( op==TK_ALL || op==TK_UNION ){
  103604. VdbeNoopComment((v, "Output routine for B"));
  103605. addrOutB = generateOutputSubroutine(pParse,
  103606. p, &destB, pDest, regOutB,
  103607. regPrev, pKeyDup, labelEnd);
  103608. }
  103609. sqlite3KeyInfoUnref(pKeyDup);
  103610. /* Generate a subroutine to run when the results from select A
  103611. ** are exhausted and only data in select B remains.
  103612. */
  103613. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  103614. addrEofA_noB = addrEofA = labelEnd;
  103615. }else{
  103616. VdbeNoopComment((v, "eof-A subroutine"));
  103617. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  103618. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  103619. VdbeCoverage(v);
  103620. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  103621. p->nSelectRow += pPrior->nSelectRow;
  103622. }
  103623. /* Generate a subroutine to run when the results from select B
  103624. ** are exhausted and only data in select A remains.
  103625. */
  103626. if( op==TK_INTERSECT ){
  103627. addrEofB = addrEofA;
  103628. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  103629. }else{
  103630. VdbeNoopComment((v, "eof-B subroutine"));
  103631. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  103632. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  103633. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  103634. }
  103635. /* Generate code to handle the case of A<B
  103636. */
  103637. VdbeNoopComment((v, "A-lt-B subroutine"));
  103638. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  103639. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  103640. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  103641. /* Generate code to handle the case of A==B
  103642. */
  103643. if( op==TK_ALL ){
  103644. addrAeqB = addrAltB;
  103645. }else if( op==TK_INTERSECT ){
  103646. addrAeqB = addrAltB;
  103647. addrAltB++;
  103648. }else{
  103649. VdbeNoopComment((v, "A-eq-B subroutine"));
  103650. addrAeqB =
  103651. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  103652. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  103653. }
  103654. /* Generate code to handle the case of A>B
  103655. */
  103656. VdbeNoopComment((v, "A-gt-B subroutine"));
  103657. addrAgtB = sqlite3VdbeCurrentAddr(v);
  103658. if( op==TK_ALL || op==TK_UNION ){
  103659. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  103660. }
  103661. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  103662. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  103663. /* This code runs once to initialize everything.
  103664. */
  103665. sqlite3VdbeJumpHere(v, j1);
  103666. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  103667. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  103668. /* Implement the main merge loop
  103669. */
  103670. sqlite3VdbeResolveLabel(v, labelCmpr);
  103671. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  103672. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  103673. (char*)pKeyMerge, P4_KEYINFO);
  103674. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  103675. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  103676. /* Jump to the this point in order to terminate the query.
  103677. */
  103678. sqlite3VdbeResolveLabel(v, labelEnd);
  103679. /* Set the number of output columns
  103680. */
  103681. if( pDest->eDest==SRT_Output ){
  103682. Select *pFirst = pPrior;
  103683. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  103684. generateColumnNames(pParse, 0, pFirst->pEList);
  103685. }
  103686. /* Reassembly the compound query so that it will be freed correctly
  103687. ** by the calling function */
  103688. if( p->pPrior ){
  103689. sqlite3SelectDelete(db, p->pPrior);
  103690. }
  103691. p->pPrior = pPrior;
  103692. pPrior->pNext = p;
  103693. /*** TBD: Insert subroutine calls to close cursors on incomplete
  103694. **** subqueries ****/
  103695. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  103696. return pParse->nErr!=0;
  103697. }
  103698. #endif
  103699. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  103700. /* Forward Declarations */
  103701. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  103702. static void substSelect(sqlite3*, Select *, int, ExprList *);
  103703. /*
  103704. ** Scan through the expression pExpr. Replace every reference to
  103705. ** a column in table number iTable with a copy of the iColumn-th
  103706. ** entry in pEList. (But leave references to the ROWID column
  103707. ** unchanged.)
  103708. **
  103709. ** This routine is part of the flattening procedure. A subquery
  103710. ** whose result set is defined by pEList appears as entry in the
  103711. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  103712. ** FORM clause entry is iTable. This routine make the necessary
  103713. ** changes to pExpr so that it refers directly to the source table
  103714. ** of the subquery rather the result set of the subquery.
  103715. */
  103716. static Expr *substExpr(
  103717. sqlite3 *db, /* Report malloc errors to this connection */
  103718. Expr *pExpr, /* Expr in which substitution occurs */
  103719. int iTable, /* Table to be substituted */
  103720. ExprList *pEList /* Substitute expressions */
  103721. ){
  103722. if( pExpr==0 ) return 0;
  103723. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  103724. if( pExpr->iColumn<0 ){
  103725. pExpr->op = TK_NULL;
  103726. }else{
  103727. Expr *pNew;
  103728. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  103729. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  103730. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  103731. sqlite3ExprDelete(db, pExpr);
  103732. pExpr = pNew;
  103733. }
  103734. }else{
  103735. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  103736. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  103737. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  103738. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  103739. }else{
  103740. substExprList(db, pExpr->x.pList, iTable, pEList);
  103741. }
  103742. }
  103743. return pExpr;
  103744. }
  103745. static void substExprList(
  103746. sqlite3 *db, /* Report malloc errors here */
  103747. ExprList *pList, /* List to scan and in which to make substitutes */
  103748. int iTable, /* Table to be substituted */
  103749. ExprList *pEList /* Substitute values */
  103750. ){
  103751. int i;
  103752. if( pList==0 ) return;
  103753. for(i=0; i<pList->nExpr; i++){
  103754. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  103755. }
  103756. }
  103757. static void substSelect(
  103758. sqlite3 *db, /* Report malloc errors here */
  103759. Select *p, /* SELECT statement in which to make substitutions */
  103760. int iTable, /* Table to be replaced */
  103761. ExprList *pEList /* Substitute values */
  103762. ){
  103763. SrcList *pSrc;
  103764. struct SrcList_item *pItem;
  103765. int i;
  103766. if( !p ) return;
  103767. substExprList(db, p->pEList, iTable, pEList);
  103768. substExprList(db, p->pGroupBy, iTable, pEList);
  103769. substExprList(db, p->pOrderBy, iTable, pEList);
  103770. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  103771. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  103772. substSelect(db, p->pPrior, iTable, pEList);
  103773. pSrc = p->pSrc;
  103774. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  103775. if( ALWAYS(pSrc) ){
  103776. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  103777. substSelect(db, pItem->pSelect, iTable, pEList);
  103778. }
  103779. }
  103780. }
  103781. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  103782. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  103783. /*
  103784. ** This routine attempts to flatten subqueries as a performance optimization.
  103785. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  103786. **
  103787. ** To understand the concept of flattening, consider the following
  103788. ** query:
  103789. **
  103790. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  103791. **
  103792. ** The default way of implementing this query is to execute the
  103793. ** subquery first and store the results in a temporary table, then
  103794. ** run the outer query on that temporary table. This requires two
  103795. ** passes over the data. Furthermore, because the temporary table
  103796. ** has no indices, the WHERE clause on the outer query cannot be
  103797. ** optimized.
  103798. **
  103799. ** This routine attempts to rewrite queries such as the above into
  103800. ** a single flat select, like this:
  103801. **
  103802. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  103803. **
  103804. ** The code generated for this simplification gives the same result
  103805. ** but only has to scan the data once. And because indices might
  103806. ** exist on the table t1, a complete scan of the data might be
  103807. ** avoided.
  103808. **
  103809. ** Flattening is only attempted if all of the following are true:
  103810. **
  103811. ** (1) The subquery and the outer query do not both use aggregates.
  103812. **
  103813. ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
  103814. ** and (2b) the outer query does not use subqueries other than the one
  103815. ** FROM-clause subquery that is a candidate for flattening. (2b is
  103816. ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
  103817. **
  103818. ** (3) The subquery is not the right operand of a left outer join
  103819. ** (Originally ticket #306. Strengthened by ticket #3300)
  103820. **
  103821. ** (4) The subquery is not DISTINCT.
  103822. **
  103823. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  103824. ** sub-queries that were excluded from this optimization. Restriction
  103825. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  103826. **
  103827. ** (6) The subquery does not use aggregates or the outer query is not
  103828. ** DISTINCT.
  103829. **
  103830. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  103831. ** A FROM clause, consider adding a FROM close with the special
  103832. ** table sqlite_once that consists of a single row containing a
  103833. ** single NULL.
  103834. **
  103835. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  103836. **
  103837. ** (9) The subquery does not use LIMIT or the outer query does not use
  103838. ** aggregates.
  103839. **
  103840. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  103841. ** accidently carried the comment forward until 2014-09-15. Original
  103842. ** text: "The subquery does not use aggregates or the outer query
  103843. ** does not use LIMIT."
  103844. **
  103845. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  103846. **
  103847. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  103848. ** a separate restriction deriving from ticket #350.
  103849. **
  103850. ** (13) The subquery and outer query do not both use LIMIT.
  103851. **
  103852. ** (14) The subquery does not use OFFSET.
  103853. **
  103854. ** (15) The outer query is not part of a compound select or the
  103855. ** subquery does not have a LIMIT clause.
  103856. ** (See ticket #2339 and ticket [02a8e81d44]).
  103857. **
  103858. ** (16) The outer query is not an aggregate or the subquery does
  103859. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  103860. ** until we introduced the group_concat() function.
  103861. **
  103862. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  103863. ** compound clause made up entirely of non-aggregate queries, and
  103864. ** the parent query:
  103865. **
  103866. ** * is not itself part of a compound select,
  103867. ** * is not an aggregate or DISTINCT query, and
  103868. ** * is not a join
  103869. **
  103870. ** The parent and sub-query may contain WHERE clauses. Subject to
  103871. ** rules (11), (13) and (14), they may also contain ORDER BY,
  103872. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  103873. ** operator other than UNION ALL because all the other compound
  103874. ** operators have an implied DISTINCT which is disallowed by
  103875. ** restriction (4).
  103876. **
  103877. ** Also, each component of the sub-query must return the same number
  103878. ** of result columns. This is actually a requirement for any compound
  103879. ** SELECT statement, but all the code here does is make sure that no
  103880. ** such (illegal) sub-query is flattened. The caller will detect the
  103881. ** syntax error and return a detailed message.
  103882. **
  103883. ** (18) If the sub-query is a compound select, then all terms of the
  103884. ** ORDER by clause of the parent must be simple references to
  103885. ** columns of the sub-query.
  103886. **
  103887. ** (19) The subquery does not use LIMIT or the outer query does not
  103888. ** have a WHERE clause.
  103889. **
  103890. ** (20) If the sub-query is a compound select, then it must not use
  103891. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  103892. ** somewhat by saying that the terms of the ORDER BY clause must
  103893. ** appear as unmodified result columns in the outer query. But we
  103894. ** have other optimizations in mind to deal with that case.
  103895. **
  103896. ** (21) The subquery does not use LIMIT or the outer query is not
  103897. ** DISTINCT. (See ticket [752e1646fc]).
  103898. **
  103899. ** (22) The subquery is not a recursive CTE.
  103900. **
  103901. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  103902. ** compound query. This restriction is because transforming the
  103903. ** parent to a compound query confuses the code that handles
  103904. ** recursive queries in multiSelect().
  103905. **
  103906. ** (24) The subquery is not an aggregate that uses the built-in min() or
  103907. ** or max() functions. (Without this restriction, a query like:
  103908. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  103909. ** return the value X for which Y was maximal.)
  103910. **
  103911. **
  103912. ** In this routine, the "p" parameter is a pointer to the outer query.
  103913. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  103914. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  103915. **
  103916. ** If flattening is not attempted, this routine is a no-op and returns 0.
  103917. ** If flattening is attempted this routine returns 1.
  103918. **
  103919. ** All of the expression analysis must occur on both the outer query and
  103920. ** the subquery before this routine runs.
  103921. */
  103922. static int flattenSubquery(
  103923. Parse *pParse, /* Parsing context */
  103924. Select *p, /* The parent or outer SELECT statement */
  103925. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  103926. int isAgg, /* True if outer SELECT uses aggregate functions */
  103927. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  103928. ){
  103929. const char *zSavedAuthContext = pParse->zAuthContext;
  103930. Select *pParent;
  103931. Select *pSub; /* The inner query or "subquery" */
  103932. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  103933. SrcList *pSrc; /* The FROM clause of the outer query */
  103934. SrcList *pSubSrc; /* The FROM clause of the subquery */
  103935. ExprList *pList; /* The result set of the outer query */
  103936. int iParent; /* VDBE cursor number of the pSub result set temp table */
  103937. int i; /* Loop counter */
  103938. Expr *pWhere; /* The WHERE clause */
  103939. struct SrcList_item *pSubitem; /* The subquery */
  103940. sqlite3 *db = pParse->db;
  103941. /* Check to see if flattening is permitted. Return 0 if not.
  103942. */
  103943. assert( p!=0 );
  103944. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  103945. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  103946. pSrc = p->pSrc;
  103947. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  103948. pSubitem = &pSrc->a[iFrom];
  103949. iParent = pSubitem->iCursor;
  103950. pSub = pSubitem->pSelect;
  103951. assert( pSub!=0 );
  103952. if( subqueryIsAgg ){
  103953. if( isAgg ) return 0; /* Restriction (1) */
  103954. if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
  103955. if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
  103956. || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
  103957. || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
  103958. ){
  103959. return 0; /* Restriction (2b) */
  103960. }
  103961. }
  103962. pSubSrc = pSub->pSrc;
  103963. assert( pSubSrc );
  103964. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  103965. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  103966. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  103967. ** became arbitrary expressions, we were forced to add restrictions (13)
  103968. ** and (14). */
  103969. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  103970. if( pSub->pOffset ) return 0; /* Restriction (14) */
  103971. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  103972. return 0; /* Restriction (15) */
  103973. }
  103974. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  103975. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  103976. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  103977. return 0; /* Restrictions (8)(9) */
  103978. }
  103979. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  103980. return 0; /* Restriction (6) */
  103981. }
  103982. if( p->pOrderBy && pSub->pOrderBy ){
  103983. return 0; /* Restriction (11) */
  103984. }
  103985. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  103986. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  103987. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  103988. return 0; /* Restriction (21) */
  103989. }
  103990. testcase( pSub->selFlags & SF_Recursive );
  103991. testcase( pSub->selFlags & SF_MinMaxAgg );
  103992. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  103993. return 0; /* Restrictions (22) and (24) */
  103994. }
  103995. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  103996. return 0; /* Restriction (23) */
  103997. }
  103998. /* OBSOLETE COMMENT 1:
  103999. ** Restriction 3: If the subquery is a join, make sure the subquery is
  104000. ** not used as the right operand of an outer join. Examples of why this
  104001. ** is not allowed:
  104002. **
  104003. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  104004. **
  104005. ** If we flatten the above, we would get
  104006. **
  104007. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  104008. **
  104009. ** which is not at all the same thing.
  104010. **
  104011. ** OBSOLETE COMMENT 2:
  104012. ** Restriction 12: If the subquery is the right operand of a left outer
  104013. ** join, make sure the subquery has no WHERE clause.
  104014. ** An examples of why this is not allowed:
  104015. **
  104016. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  104017. **
  104018. ** If we flatten the above, we would get
  104019. **
  104020. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  104021. **
  104022. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  104023. ** effectively converts the OUTER JOIN into an INNER JOIN.
  104024. **
  104025. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  104026. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  104027. ** is fraught with danger. Best to avoid the whole thing. If the
  104028. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  104029. */
  104030. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  104031. return 0;
  104032. }
  104033. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  104034. ** use only the UNION ALL operator. And none of the simple select queries
  104035. ** that make up the compound SELECT are allowed to be aggregate or distinct
  104036. ** queries.
  104037. */
  104038. if( pSub->pPrior ){
  104039. if( pSub->pOrderBy ){
  104040. return 0; /* Restriction 20 */
  104041. }
  104042. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  104043. return 0;
  104044. }
  104045. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  104046. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  104047. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  104048. assert( pSub->pSrc!=0 );
  104049. assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
  104050. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  104051. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  104052. || pSub1->pSrc->nSrc<1
  104053. ){
  104054. return 0;
  104055. }
  104056. testcase( pSub1->pSrc->nSrc>1 );
  104057. }
  104058. /* Restriction 18. */
  104059. if( p->pOrderBy ){
  104060. int ii;
  104061. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  104062. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  104063. }
  104064. }
  104065. }
  104066. /***** If we reach this point, flattening is permitted. *****/
  104067. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  104068. pSub->zSelName, pSub, iFrom));
  104069. /* Authorize the subquery */
  104070. pParse->zAuthContext = pSubitem->zName;
  104071. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  104072. testcase( i==SQLITE_DENY );
  104073. pParse->zAuthContext = zSavedAuthContext;
  104074. /* If the sub-query is a compound SELECT statement, then (by restrictions
  104075. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  104076. ** be of the form:
  104077. **
  104078. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  104079. **
  104080. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  104081. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  104082. ** OFFSET clauses and joins them to the left-hand-side of the original
  104083. ** using UNION ALL operators. In this case N is the number of simple
  104084. ** select statements in the compound sub-query.
  104085. **
  104086. ** Example:
  104087. **
  104088. ** SELECT a+1 FROM (
  104089. ** SELECT x FROM tab
  104090. ** UNION ALL
  104091. ** SELECT y FROM tab
  104092. ** UNION ALL
  104093. ** SELECT abs(z*2) FROM tab2
  104094. ** ) WHERE a!=5 ORDER BY 1
  104095. **
  104096. ** Transformed into:
  104097. **
  104098. ** SELECT x+1 FROM tab WHERE x+1!=5
  104099. ** UNION ALL
  104100. ** SELECT y+1 FROM tab WHERE y+1!=5
  104101. ** UNION ALL
  104102. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  104103. ** ORDER BY 1
  104104. **
  104105. ** We call this the "compound-subquery flattening".
  104106. */
  104107. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  104108. Select *pNew;
  104109. ExprList *pOrderBy = p->pOrderBy;
  104110. Expr *pLimit = p->pLimit;
  104111. Expr *pOffset = p->pOffset;
  104112. Select *pPrior = p->pPrior;
  104113. p->pOrderBy = 0;
  104114. p->pSrc = 0;
  104115. p->pPrior = 0;
  104116. p->pLimit = 0;
  104117. p->pOffset = 0;
  104118. pNew = sqlite3SelectDup(db, p, 0);
  104119. sqlite3SelectSetName(pNew, pSub->zSelName);
  104120. p->pOffset = pOffset;
  104121. p->pLimit = pLimit;
  104122. p->pOrderBy = pOrderBy;
  104123. p->pSrc = pSrc;
  104124. p->op = TK_ALL;
  104125. if( pNew==0 ){
  104126. p->pPrior = pPrior;
  104127. }else{
  104128. pNew->pPrior = pPrior;
  104129. if( pPrior ) pPrior->pNext = pNew;
  104130. pNew->pNext = p;
  104131. p->pPrior = pNew;
  104132. SELECTTRACE(2,pParse,p,
  104133. ("compound-subquery flattener creates %s.%p as peer\n",
  104134. pNew->zSelName, pNew));
  104135. }
  104136. if( db->mallocFailed ) return 1;
  104137. }
  104138. /* Begin flattening the iFrom-th entry of the FROM clause
  104139. ** in the outer query.
  104140. */
  104141. pSub = pSub1 = pSubitem->pSelect;
  104142. /* Delete the transient table structure associated with the
  104143. ** subquery
  104144. */
  104145. sqlite3DbFree(db, pSubitem->zDatabase);
  104146. sqlite3DbFree(db, pSubitem->zName);
  104147. sqlite3DbFree(db, pSubitem->zAlias);
  104148. pSubitem->zDatabase = 0;
  104149. pSubitem->zName = 0;
  104150. pSubitem->zAlias = 0;
  104151. pSubitem->pSelect = 0;
  104152. /* Defer deleting the Table object associated with the
  104153. ** subquery until code generation is
  104154. ** complete, since there may still exist Expr.pTab entries that
  104155. ** refer to the subquery even after flattening. Ticket #3346.
  104156. **
  104157. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  104158. */
  104159. if( ALWAYS(pSubitem->pTab!=0) ){
  104160. Table *pTabToDel = pSubitem->pTab;
  104161. if( pTabToDel->nRef==1 ){
  104162. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  104163. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  104164. pToplevel->pZombieTab = pTabToDel;
  104165. }else{
  104166. pTabToDel->nRef--;
  104167. }
  104168. pSubitem->pTab = 0;
  104169. }
  104170. /* The following loop runs once for each term in a compound-subquery
  104171. ** flattening (as described above). If we are doing a different kind
  104172. ** of flattening - a flattening other than a compound-subquery flattening -
  104173. ** then this loop only runs once.
  104174. **
  104175. ** This loop moves all of the FROM elements of the subquery into the
  104176. ** the FROM clause of the outer query. Before doing this, remember
  104177. ** the cursor number for the original outer query FROM element in
  104178. ** iParent. The iParent cursor will never be used. Subsequent code
  104179. ** will scan expressions looking for iParent references and replace
  104180. ** those references with expressions that resolve to the subquery FROM
  104181. ** elements we are now copying in.
  104182. */
  104183. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  104184. int nSubSrc;
  104185. u8 jointype = 0;
  104186. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  104187. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  104188. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  104189. if( pSrc ){
  104190. assert( pParent==p ); /* First time through the loop */
  104191. jointype = pSubitem->jointype;
  104192. }else{
  104193. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  104194. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  104195. if( pSrc==0 ){
  104196. assert( db->mallocFailed );
  104197. break;
  104198. }
  104199. }
  104200. /* The subquery uses a single slot of the FROM clause of the outer
  104201. ** query. If the subquery has more than one element in its FROM clause,
  104202. ** then expand the outer query to make space for it to hold all elements
  104203. ** of the subquery.
  104204. **
  104205. ** Example:
  104206. **
  104207. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  104208. **
  104209. ** The outer query has 3 slots in its FROM clause. One slot of the
  104210. ** outer query (the middle slot) is used by the subquery. The next
  104211. ** block of code will expand the out query to 4 slots. The middle
  104212. ** slot is expanded to two slots in order to make space for the
  104213. ** two elements in the FROM clause of the subquery.
  104214. */
  104215. if( nSubSrc>1 ){
  104216. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  104217. if( db->mallocFailed ){
  104218. break;
  104219. }
  104220. }
  104221. /* Transfer the FROM clause terms from the subquery into the
  104222. ** outer query.
  104223. */
  104224. for(i=0; i<nSubSrc; i++){
  104225. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  104226. pSrc->a[i+iFrom] = pSubSrc->a[i];
  104227. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  104228. }
  104229. pSrc->a[iFrom].jointype = jointype;
  104230. /* Now begin substituting subquery result set expressions for
  104231. ** references to the iParent in the outer query.
  104232. **
  104233. ** Example:
  104234. **
  104235. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  104236. ** \ \_____________ subquery __________/ /
  104237. ** \_____________________ outer query ______________________________/
  104238. **
  104239. ** We look at every expression in the outer query and every place we see
  104240. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  104241. */
  104242. pList = pParent->pEList;
  104243. for(i=0; i<pList->nExpr; i++){
  104244. if( pList->a[i].zName==0 ){
  104245. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  104246. sqlite3Dequote(zName);
  104247. pList->a[i].zName = zName;
  104248. }
  104249. }
  104250. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  104251. if( isAgg ){
  104252. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  104253. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  104254. }
  104255. if( pSub->pOrderBy ){
  104256. /* At this point, any non-zero iOrderByCol values indicate that the
  104257. ** ORDER BY column expression is identical to the iOrderByCol'th
  104258. ** expression returned by SELECT statement pSub. Since these values
  104259. ** do not necessarily correspond to columns in SELECT statement pParent,
  104260. ** zero them before transfering the ORDER BY clause.
  104261. **
  104262. ** Not doing this may cause an error if a subsequent call to this
  104263. ** function attempts to flatten a compound sub-query into pParent
  104264. ** (the only way this can happen is if the compound sub-query is
  104265. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  104266. ExprList *pOrderBy = pSub->pOrderBy;
  104267. for(i=0; i<pOrderBy->nExpr; i++){
  104268. pOrderBy->a[i].u.x.iOrderByCol = 0;
  104269. }
  104270. assert( pParent->pOrderBy==0 );
  104271. assert( pSub->pPrior==0 );
  104272. pParent->pOrderBy = pOrderBy;
  104273. pSub->pOrderBy = 0;
  104274. }else if( pParent->pOrderBy ){
  104275. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  104276. }
  104277. if( pSub->pWhere ){
  104278. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  104279. }else{
  104280. pWhere = 0;
  104281. }
  104282. if( subqueryIsAgg ){
  104283. assert( pParent->pHaving==0 );
  104284. pParent->pHaving = pParent->pWhere;
  104285. pParent->pWhere = pWhere;
  104286. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  104287. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  104288. sqlite3ExprDup(db, pSub->pHaving, 0));
  104289. assert( pParent->pGroupBy==0 );
  104290. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  104291. }else{
  104292. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  104293. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  104294. }
  104295. /* The flattened query is distinct if either the inner or the
  104296. ** outer query is distinct.
  104297. */
  104298. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  104299. /*
  104300. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  104301. **
  104302. ** One is tempted to try to add a and b to combine the limits. But this
  104303. ** does not work if either limit is negative.
  104304. */
  104305. if( pSub->pLimit ){
  104306. pParent->pLimit = pSub->pLimit;
  104307. pSub->pLimit = 0;
  104308. }
  104309. }
  104310. /* Finially, delete what is left of the subquery and return
  104311. ** success.
  104312. */
  104313. sqlite3SelectDelete(db, pSub1);
  104314. #if SELECTTRACE_ENABLED
  104315. if( sqlite3SelectTrace & 0x100 ){
  104316. SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
  104317. sqlite3TreeViewSelect(0, p, 0);
  104318. }
  104319. #endif
  104320. return 1;
  104321. }
  104322. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  104323. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  104324. /*
  104325. ** Make copies of relevant WHERE clause terms of the outer query into
  104326. ** the WHERE clause of subquery. Example:
  104327. **
  104328. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
  104329. **
  104330. ** Transformed into:
  104331. **
  104332. ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
  104333. ** WHERE x=5 AND y=10;
  104334. **
  104335. ** The hope is that the terms added to the inner query will make it more
  104336. ** efficient.
  104337. **
  104338. ** Do not attempt this optimization if:
  104339. **
  104340. ** (1) The inner query is an aggregate. (In that case, we'd really want
  104341. ** to copy the outer WHERE-clause terms onto the HAVING clause of the
  104342. ** inner query. But they probably won't help there so do not bother.)
  104343. **
  104344. ** (2) The inner query is the recursive part of a common table expression.
  104345. **
  104346. ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
  104347. ** close would change the meaning of the LIMIT).
  104348. **
  104349. ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
  104350. ** enforces this restriction since this routine does not have enough
  104351. ** information to know.)
  104352. **
  104353. ** Return 0 if no changes are made and non-zero if one or more WHERE clause
  104354. ** terms are duplicated into the subquery.
  104355. */
  104356. static int pushDownWhereTerms(
  104357. sqlite3 *db, /* The database connection (for malloc()) */
  104358. Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
  104359. Expr *pWhere, /* The WHERE clause of the outer query */
  104360. int iCursor /* Cursor number of the subquery */
  104361. ){
  104362. Expr *pNew;
  104363. int nChng = 0;
  104364. if( pWhere==0 ) return 0;
  104365. if( (pSubq->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
  104366. return 0; /* restrictions (1) and (2) */
  104367. }
  104368. if( pSubq->pLimit!=0 ){
  104369. return 0; /* restriction (3) */
  104370. }
  104371. while( pWhere->op==TK_AND ){
  104372. nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
  104373. pWhere = pWhere->pLeft;
  104374. }
  104375. if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
  104376. nChng++;
  104377. while( pSubq ){
  104378. pNew = sqlite3ExprDup(db, pWhere, 0);
  104379. pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
  104380. pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
  104381. pSubq = pSubq->pPrior;
  104382. }
  104383. }
  104384. return nChng;
  104385. }
  104386. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  104387. /*
  104388. ** Based on the contents of the AggInfo structure indicated by the first
  104389. ** argument, this function checks if the following are true:
  104390. **
  104391. ** * the query contains just a single aggregate function,
  104392. ** * the aggregate function is either min() or max(), and
  104393. ** * the argument to the aggregate function is a column value.
  104394. **
  104395. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  104396. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  104397. ** list of arguments passed to the aggregate before returning.
  104398. **
  104399. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  104400. ** WHERE_ORDERBY_NORMAL is returned.
  104401. */
  104402. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  104403. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  104404. *ppMinMax = 0;
  104405. if( pAggInfo->nFunc==1 ){
  104406. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  104407. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  104408. assert( pExpr->op==TK_AGG_FUNCTION );
  104409. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  104410. const char *zFunc = pExpr->u.zToken;
  104411. if( sqlite3StrICmp(zFunc, "min")==0 ){
  104412. eRet = WHERE_ORDERBY_MIN;
  104413. *ppMinMax = pEList;
  104414. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  104415. eRet = WHERE_ORDERBY_MAX;
  104416. *ppMinMax = pEList;
  104417. }
  104418. }
  104419. }
  104420. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  104421. return eRet;
  104422. }
  104423. /*
  104424. ** The select statement passed as the first argument is an aggregate query.
  104425. ** The second argument is the associated aggregate-info object. This
  104426. ** function tests if the SELECT is of the form:
  104427. **
  104428. ** SELECT count(*) FROM <tbl>
  104429. **
  104430. ** where table is a database table, not a sub-select or view. If the query
  104431. ** does match this pattern, then a pointer to the Table object representing
  104432. ** <tbl> is returned. Otherwise, 0 is returned.
  104433. */
  104434. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  104435. Table *pTab;
  104436. Expr *pExpr;
  104437. assert( !p->pGroupBy );
  104438. if( p->pWhere || p->pEList->nExpr!=1
  104439. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  104440. ){
  104441. return 0;
  104442. }
  104443. pTab = p->pSrc->a[0].pTab;
  104444. pExpr = p->pEList->a[0].pExpr;
  104445. assert( pTab && !pTab->pSelect && pExpr );
  104446. if( IsVirtual(pTab) ) return 0;
  104447. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  104448. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  104449. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  104450. if( pExpr->flags&EP_Distinct ) return 0;
  104451. return pTab;
  104452. }
  104453. /*
  104454. ** If the source-list item passed as an argument was augmented with an
  104455. ** INDEXED BY clause, then try to locate the specified index. If there
  104456. ** was such a clause and the named index cannot be found, return
  104457. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  104458. ** pFrom->pIndex and return SQLITE_OK.
  104459. */
  104460. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  104461. if( pFrom->pTab && pFrom->zIndexedBy ){
  104462. Table *pTab = pFrom->pTab;
  104463. char *zIndexedBy = pFrom->zIndexedBy;
  104464. Index *pIdx;
  104465. for(pIdx=pTab->pIndex;
  104466. pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
  104467. pIdx=pIdx->pNext
  104468. );
  104469. if( !pIdx ){
  104470. sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
  104471. pParse->checkSchema = 1;
  104472. return SQLITE_ERROR;
  104473. }
  104474. pFrom->pIndex = pIdx;
  104475. }
  104476. return SQLITE_OK;
  104477. }
  104478. /*
  104479. ** Detect compound SELECT statements that use an ORDER BY clause with
  104480. ** an alternative collating sequence.
  104481. **
  104482. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  104483. **
  104484. ** These are rewritten as a subquery:
  104485. **
  104486. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  104487. ** ORDER BY ... COLLATE ...
  104488. **
  104489. ** This transformation is necessary because the multiSelectOrderBy() routine
  104490. ** above that generates the code for a compound SELECT with an ORDER BY clause
  104491. ** uses a merge algorithm that requires the same collating sequence on the
  104492. ** result columns as on the ORDER BY clause. See ticket
  104493. ** http://www.sqlite.org/src/info/6709574d2a
  104494. **
  104495. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  104496. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  104497. ** there are COLLATE terms in the ORDER BY.
  104498. */
  104499. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  104500. int i;
  104501. Select *pNew;
  104502. Select *pX;
  104503. sqlite3 *db;
  104504. struct ExprList_item *a;
  104505. SrcList *pNewSrc;
  104506. Parse *pParse;
  104507. Token dummy;
  104508. if( p->pPrior==0 ) return WRC_Continue;
  104509. if( p->pOrderBy==0 ) return WRC_Continue;
  104510. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  104511. if( pX==0 ) return WRC_Continue;
  104512. a = p->pOrderBy->a;
  104513. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  104514. if( a[i].pExpr->flags & EP_Collate ) break;
  104515. }
  104516. if( i<0 ) return WRC_Continue;
  104517. /* If we reach this point, that means the transformation is required. */
  104518. pParse = pWalker->pParse;
  104519. db = pParse->db;
  104520. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  104521. if( pNew==0 ) return WRC_Abort;
  104522. memset(&dummy, 0, sizeof(dummy));
  104523. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  104524. if( pNewSrc==0 ) return WRC_Abort;
  104525. *pNew = *p;
  104526. p->pSrc = pNewSrc;
  104527. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  104528. p->op = TK_SELECT;
  104529. p->pWhere = 0;
  104530. pNew->pGroupBy = 0;
  104531. pNew->pHaving = 0;
  104532. pNew->pOrderBy = 0;
  104533. p->pPrior = 0;
  104534. p->pNext = 0;
  104535. p->pWith = 0;
  104536. p->selFlags &= ~SF_Compound;
  104537. assert( (p->selFlags & SF_Converted)==0 );
  104538. p->selFlags |= SF_Converted;
  104539. assert( pNew->pPrior!=0 );
  104540. pNew->pPrior->pNext = pNew;
  104541. pNew->pLimit = 0;
  104542. pNew->pOffset = 0;
  104543. return WRC_Continue;
  104544. }
  104545. #ifndef SQLITE_OMIT_CTE
  104546. /*
  104547. ** Argument pWith (which may be NULL) points to a linked list of nested
  104548. ** WITH contexts, from inner to outermost. If the table identified by
  104549. ** FROM clause element pItem is really a common-table-expression (CTE)
  104550. ** then return a pointer to the CTE definition for that table. Otherwise
  104551. ** return NULL.
  104552. **
  104553. ** If a non-NULL value is returned, set *ppContext to point to the With
  104554. ** object that the returned CTE belongs to.
  104555. */
  104556. static struct Cte *searchWith(
  104557. With *pWith, /* Current outermost WITH clause */
  104558. struct SrcList_item *pItem, /* FROM clause element to resolve */
  104559. With **ppContext /* OUT: WITH clause return value belongs to */
  104560. ){
  104561. const char *zName;
  104562. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  104563. With *p;
  104564. for(p=pWith; p; p=p->pOuter){
  104565. int i;
  104566. for(i=0; i<p->nCte; i++){
  104567. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  104568. *ppContext = p;
  104569. return &p->a[i];
  104570. }
  104571. }
  104572. }
  104573. }
  104574. return 0;
  104575. }
  104576. /* The code generator maintains a stack of active WITH clauses
  104577. ** with the inner-most WITH clause being at the top of the stack.
  104578. **
  104579. ** This routine pushes the WITH clause passed as the second argument
  104580. ** onto the top of the stack. If argument bFree is true, then this
  104581. ** WITH clause will never be popped from the stack. In this case it
  104582. ** should be freed along with the Parse object. In other cases, when
  104583. ** bFree==0, the With object will be freed along with the SELECT
  104584. ** statement with which it is associated.
  104585. */
  104586. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  104587. assert( bFree==0 || pParse->pWith==0 );
  104588. if( pWith ){
  104589. pWith->pOuter = pParse->pWith;
  104590. pParse->pWith = pWith;
  104591. pParse->bFreeWith = bFree;
  104592. }
  104593. }
  104594. /*
  104595. ** This function checks if argument pFrom refers to a CTE declared by
  104596. ** a WITH clause on the stack currently maintained by the parser. And,
  104597. ** if currently processing a CTE expression, if it is a recursive
  104598. ** reference to the current CTE.
  104599. **
  104600. ** If pFrom falls into either of the two categories above, pFrom->pTab
  104601. ** and other fields are populated accordingly. The caller should check
  104602. ** (pFrom->pTab!=0) to determine whether or not a successful match
  104603. ** was found.
  104604. **
  104605. ** Whether or not a match is found, SQLITE_OK is returned if no error
  104606. ** occurs. If an error does occur, an error message is stored in the
  104607. ** parser and some error code other than SQLITE_OK returned.
  104608. */
  104609. static int withExpand(
  104610. Walker *pWalker,
  104611. struct SrcList_item *pFrom
  104612. ){
  104613. Parse *pParse = pWalker->pParse;
  104614. sqlite3 *db = pParse->db;
  104615. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  104616. With *pWith; /* WITH clause that pCte belongs to */
  104617. assert( pFrom->pTab==0 );
  104618. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  104619. if( pCte ){
  104620. Table *pTab;
  104621. ExprList *pEList;
  104622. Select *pSel;
  104623. Select *pLeft; /* Left-most SELECT statement */
  104624. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  104625. With *pSavedWith; /* Initial value of pParse->pWith */
  104626. /* If pCte->zErr is non-NULL at this point, then this is an illegal
  104627. ** recursive reference to CTE pCte. Leave an error in pParse and return
  104628. ** early. If pCte->zErr is NULL, then this is not a recursive reference.
  104629. ** In this case, proceed. */
  104630. if( pCte->zErr ){
  104631. sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
  104632. return SQLITE_ERROR;
  104633. }
  104634. assert( pFrom->pTab==0 );
  104635. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  104636. if( pTab==0 ) return WRC_Abort;
  104637. pTab->nRef = 1;
  104638. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  104639. pTab->iPKey = -1;
  104640. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  104641. pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
  104642. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  104643. if( db->mallocFailed ) return SQLITE_NOMEM;
  104644. assert( pFrom->pSelect );
  104645. /* Check if this is a recursive CTE. */
  104646. pSel = pFrom->pSelect;
  104647. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  104648. if( bMayRecursive ){
  104649. int i;
  104650. SrcList *pSrc = pFrom->pSelect->pSrc;
  104651. for(i=0; i<pSrc->nSrc; i++){
  104652. struct SrcList_item *pItem = &pSrc->a[i];
  104653. if( pItem->zDatabase==0
  104654. && pItem->zName!=0
  104655. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  104656. ){
  104657. pItem->pTab = pTab;
  104658. pItem->isRecursive = 1;
  104659. pTab->nRef++;
  104660. pSel->selFlags |= SF_Recursive;
  104661. }
  104662. }
  104663. }
  104664. /* Only one recursive reference is permitted. */
  104665. if( pTab->nRef>2 ){
  104666. sqlite3ErrorMsg(
  104667. pParse, "multiple references to recursive table: %s", pCte->zName
  104668. );
  104669. return SQLITE_ERROR;
  104670. }
  104671. assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
  104672. pCte->zErr = "circular reference: %s";
  104673. pSavedWith = pParse->pWith;
  104674. pParse->pWith = pWith;
  104675. sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
  104676. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  104677. pEList = pLeft->pEList;
  104678. if( pCte->pCols ){
  104679. if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
  104680. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  104681. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  104682. );
  104683. pParse->pWith = pSavedWith;
  104684. return SQLITE_ERROR;
  104685. }
  104686. pEList = pCte->pCols;
  104687. }
  104688. selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  104689. if( bMayRecursive ){
  104690. if( pSel->selFlags & SF_Recursive ){
  104691. pCte->zErr = "multiple recursive references: %s";
  104692. }else{
  104693. pCte->zErr = "recursive reference in a subquery: %s";
  104694. }
  104695. sqlite3WalkSelect(pWalker, pSel);
  104696. }
  104697. pCte->zErr = 0;
  104698. pParse->pWith = pSavedWith;
  104699. }
  104700. return SQLITE_OK;
  104701. }
  104702. #endif
  104703. #ifndef SQLITE_OMIT_CTE
  104704. /*
  104705. ** If the SELECT passed as the second argument has an associated WITH
  104706. ** clause, pop it from the stack stored as part of the Parse object.
  104707. **
  104708. ** This function is used as the xSelectCallback2() callback by
  104709. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  104710. ** names and other FROM clause elements.
  104711. */
  104712. static void selectPopWith(Walker *pWalker, Select *p){
  104713. Parse *pParse = pWalker->pParse;
  104714. With *pWith = findRightmost(p)->pWith;
  104715. if( pWith!=0 ){
  104716. assert( pParse->pWith==pWith );
  104717. pParse->pWith = pWith->pOuter;
  104718. }
  104719. }
  104720. #else
  104721. #define selectPopWith 0
  104722. #endif
  104723. /*
  104724. ** This routine is a Walker callback for "expanding" a SELECT statement.
  104725. ** "Expanding" means to do the following:
  104726. **
  104727. ** (1) Make sure VDBE cursor numbers have been assigned to every
  104728. ** element of the FROM clause.
  104729. **
  104730. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  104731. ** defines FROM clause. When views appear in the FROM clause,
  104732. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  104733. ** that implements the view. A copy is made of the view's SELECT
  104734. ** statement so that we can freely modify or delete that statement
  104735. ** without worrying about messing up the persistent representation
  104736. ** of the view.
  104737. **
  104738. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  104739. ** on joins and the ON and USING clause of joins.
  104740. **
  104741. ** (4) Scan the list of columns in the result set (pEList) looking
  104742. ** for instances of the "*" operator or the TABLE.* operator.
  104743. ** If found, expand each "*" to be every column in every table
  104744. ** and TABLE.* to be every column in TABLE.
  104745. **
  104746. */
  104747. static int selectExpander(Walker *pWalker, Select *p){
  104748. Parse *pParse = pWalker->pParse;
  104749. int i, j, k;
  104750. SrcList *pTabList;
  104751. ExprList *pEList;
  104752. struct SrcList_item *pFrom;
  104753. sqlite3 *db = pParse->db;
  104754. Expr *pE, *pRight, *pExpr;
  104755. u16 selFlags = p->selFlags;
  104756. p->selFlags |= SF_Expanded;
  104757. if( db->mallocFailed ){
  104758. return WRC_Abort;
  104759. }
  104760. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  104761. return WRC_Prune;
  104762. }
  104763. pTabList = p->pSrc;
  104764. pEList = p->pEList;
  104765. if( pWalker->xSelectCallback2==selectPopWith ){
  104766. sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
  104767. }
  104768. /* Make sure cursor numbers have been assigned to all entries in
  104769. ** the FROM clause of the SELECT statement.
  104770. */
  104771. sqlite3SrcListAssignCursors(pParse, pTabList);
  104772. /* Look up every table named in the FROM clause of the select. If
  104773. ** an entry of the FROM clause is a subquery instead of a table or view,
  104774. ** then create a transient table structure to describe the subquery.
  104775. */
  104776. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  104777. Table *pTab;
  104778. assert( pFrom->isRecursive==0 || pFrom->pTab );
  104779. if( pFrom->isRecursive ) continue;
  104780. if( pFrom->pTab!=0 ){
  104781. /* This statement has already been prepared. There is no need
  104782. ** to go further. */
  104783. assert( i==0 );
  104784. #ifndef SQLITE_OMIT_CTE
  104785. selectPopWith(pWalker, p);
  104786. #endif
  104787. return WRC_Prune;
  104788. }
  104789. #ifndef SQLITE_OMIT_CTE
  104790. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  104791. if( pFrom->pTab ) {} else
  104792. #endif
  104793. if( pFrom->zName==0 ){
  104794. #ifndef SQLITE_OMIT_SUBQUERY
  104795. Select *pSel = pFrom->pSelect;
  104796. /* A sub-query in the FROM clause of a SELECT */
  104797. assert( pSel!=0 );
  104798. assert( pFrom->pTab==0 );
  104799. if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
  104800. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  104801. if( pTab==0 ) return WRC_Abort;
  104802. pTab->nRef = 1;
  104803. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  104804. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  104805. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  104806. pTab->iPKey = -1;
  104807. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  104808. pTab->tabFlags |= TF_Ephemeral;
  104809. #endif
  104810. }else{
  104811. /* An ordinary table or view name in the FROM clause */
  104812. assert( pFrom->pTab==0 );
  104813. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  104814. if( pTab==0 ) return WRC_Abort;
  104815. if( pTab->nRef==0xffff ){
  104816. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  104817. pTab->zName);
  104818. pFrom->pTab = 0;
  104819. return WRC_Abort;
  104820. }
  104821. pTab->nRef++;
  104822. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  104823. if( pTab->pSelect || IsVirtual(pTab) ){
  104824. /* We reach here if the named table is a really a view */
  104825. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  104826. assert( pFrom->pSelect==0 );
  104827. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  104828. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  104829. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  104830. }
  104831. #endif
  104832. }
  104833. /* Locate the index named by the INDEXED BY clause, if any. */
  104834. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  104835. return WRC_Abort;
  104836. }
  104837. }
  104838. /* Process NATURAL keywords, and ON and USING clauses of joins.
  104839. */
  104840. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  104841. return WRC_Abort;
  104842. }
  104843. /* For every "*" that occurs in the column list, insert the names of
  104844. ** all columns in all tables. And for every TABLE.* insert the names
  104845. ** of all columns in TABLE. The parser inserted a special expression
  104846. ** with the TK_ALL operator for each "*" that it found in the column list.
  104847. ** The following code just has to locate the TK_ALL expressions and expand
  104848. ** each one to the list of all columns in all tables.
  104849. **
  104850. ** The first loop just checks to see if there are any "*" operators
  104851. ** that need expanding.
  104852. */
  104853. for(k=0; k<pEList->nExpr; k++){
  104854. pE = pEList->a[k].pExpr;
  104855. if( pE->op==TK_ALL ) break;
  104856. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  104857. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  104858. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  104859. }
  104860. if( k<pEList->nExpr ){
  104861. /*
  104862. ** If we get here it means the result set contains one or more "*"
  104863. ** operators that need to be expanded. Loop through each expression
  104864. ** in the result set and expand them one by one.
  104865. */
  104866. struct ExprList_item *a = pEList->a;
  104867. ExprList *pNew = 0;
  104868. int flags = pParse->db->flags;
  104869. int longNames = (flags & SQLITE_FullColNames)!=0
  104870. && (flags & SQLITE_ShortColNames)==0;
  104871. for(k=0; k<pEList->nExpr; k++){
  104872. pE = a[k].pExpr;
  104873. pRight = pE->pRight;
  104874. assert( pE->op!=TK_DOT || pRight!=0 );
  104875. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  104876. /* This particular expression does not need to be expanded.
  104877. */
  104878. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  104879. if( pNew ){
  104880. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  104881. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  104882. a[k].zName = 0;
  104883. a[k].zSpan = 0;
  104884. }
  104885. a[k].pExpr = 0;
  104886. }else{
  104887. /* This expression is a "*" or a "TABLE.*" and needs to be
  104888. ** expanded. */
  104889. int tableSeen = 0; /* Set to 1 when TABLE matches */
  104890. char *zTName = 0; /* text of name of TABLE */
  104891. if( pE->op==TK_DOT ){
  104892. assert( pE->pLeft!=0 );
  104893. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  104894. zTName = pE->pLeft->u.zToken;
  104895. }
  104896. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  104897. Table *pTab = pFrom->pTab;
  104898. Select *pSub = pFrom->pSelect;
  104899. char *zTabName = pFrom->zAlias;
  104900. const char *zSchemaName = 0;
  104901. int iDb;
  104902. if( zTabName==0 ){
  104903. zTabName = pTab->zName;
  104904. }
  104905. if( db->mallocFailed ) break;
  104906. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  104907. pSub = 0;
  104908. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  104909. continue;
  104910. }
  104911. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  104912. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  104913. }
  104914. for(j=0; j<pTab->nCol; j++){
  104915. char *zName = pTab->aCol[j].zName;
  104916. char *zColname; /* The computed column name */
  104917. char *zToFree; /* Malloced string that needs to be freed */
  104918. Token sColname; /* Computed column name as a token */
  104919. assert( zName );
  104920. if( zTName && pSub
  104921. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  104922. ){
  104923. continue;
  104924. }
  104925. /* If a column is marked as 'hidden' (currently only possible
  104926. ** for virtual tables), do not include it in the expanded
  104927. ** result-set list.
  104928. */
  104929. if( IsHiddenColumn(&pTab->aCol[j]) ){
  104930. assert(IsVirtual(pTab));
  104931. continue;
  104932. }
  104933. tableSeen = 1;
  104934. if( i>0 && zTName==0 ){
  104935. if( (pFrom->jointype & JT_NATURAL)!=0
  104936. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  104937. ){
  104938. /* In a NATURAL join, omit the join columns from the
  104939. ** table to the right of the join */
  104940. continue;
  104941. }
  104942. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  104943. /* In a join with a USING clause, omit columns in the
  104944. ** using clause from the table on the right. */
  104945. continue;
  104946. }
  104947. }
  104948. pRight = sqlite3Expr(db, TK_ID, zName);
  104949. zColname = zName;
  104950. zToFree = 0;
  104951. if( longNames || pTabList->nSrc>1 ){
  104952. Expr *pLeft;
  104953. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  104954. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  104955. if( zSchemaName ){
  104956. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  104957. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  104958. }
  104959. if( longNames ){
  104960. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  104961. zToFree = zColname;
  104962. }
  104963. }else{
  104964. pExpr = pRight;
  104965. }
  104966. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  104967. sColname.z = zColname;
  104968. sColname.n = sqlite3Strlen30(zColname);
  104969. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  104970. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  104971. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  104972. if( pSub ){
  104973. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  104974. testcase( pX->zSpan==0 );
  104975. }else{
  104976. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  104977. zSchemaName, zTabName, zColname);
  104978. testcase( pX->zSpan==0 );
  104979. }
  104980. pX->bSpanIsTab = 1;
  104981. }
  104982. sqlite3DbFree(db, zToFree);
  104983. }
  104984. }
  104985. if( !tableSeen ){
  104986. if( zTName ){
  104987. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  104988. }else{
  104989. sqlite3ErrorMsg(pParse, "no tables specified");
  104990. }
  104991. }
  104992. }
  104993. }
  104994. sqlite3ExprListDelete(db, pEList);
  104995. p->pEList = pNew;
  104996. }
  104997. #if SQLITE_MAX_COLUMN
  104998. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  104999. sqlite3ErrorMsg(pParse, "too many columns in result set");
  105000. }
  105001. #endif
  105002. return WRC_Continue;
  105003. }
  105004. /*
  105005. ** No-op routine for the parse-tree walker.
  105006. **
  105007. ** When this routine is the Walker.xExprCallback then expression trees
  105008. ** are walked without any actions being taken at each node. Presumably,
  105009. ** when this routine is used for Walker.xExprCallback then
  105010. ** Walker.xSelectCallback is set to do something useful for every
  105011. ** subquery in the parser tree.
  105012. */
  105013. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  105014. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  105015. return WRC_Continue;
  105016. }
  105017. /*
  105018. ** This routine "expands" a SELECT statement and all of its subqueries.
  105019. ** For additional information on what it means to "expand" a SELECT
  105020. ** statement, see the comment on the selectExpand worker callback above.
  105021. **
  105022. ** Expanding a SELECT statement is the first step in processing a
  105023. ** SELECT statement. The SELECT statement must be expanded before
  105024. ** name resolution is performed.
  105025. **
  105026. ** If anything goes wrong, an error message is written into pParse.
  105027. ** The calling function can detect the problem by looking at pParse->nErr
  105028. ** and/or pParse->db->mallocFailed.
  105029. */
  105030. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  105031. Walker w;
  105032. memset(&w, 0, sizeof(w));
  105033. w.xExprCallback = exprWalkNoop;
  105034. w.pParse = pParse;
  105035. if( pParse->hasCompound ){
  105036. w.xSelectCallback = convertCompoundSelectToSubquery;
  105037. sqlite3WalkSelect(&w, pSelect);
  105038. }
  105039. w.xSelectCallback = selectExpander;
  105040. if( (pSelect->selFlags & SF_MultiValue)==0 ){
  105041. w.xSelectCallback2 = selectPopWith;
  105042. }
  105043. sqlite3WalkSelect(&w, pSelect);
  105044. }
  105045. #ifndef SQLITE_OMIT_SUBQUERY
  105046. /*
  105047. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  105048. ** interface.
  105049. **
  105050. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  105051. ** information to the Table structure that represents the result set
  105052. ** of that subquery.
  105053. **
  105054. ** The Table structure that represents the result set was constructed
  105055. ** by selectExpander() but the type and collation information was omitted
  105056. ** at that point because identifiers had not yet been resolved. This
  105057. ** routine is called after identifier resolution.
  105058. */
  105059. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  105060. Parse *pParse;
  105061. int i;
  105062. SrcList *pTabList;
  105063. struct SrcList_item *pFrom;
  105064. assert( p->selFlags & SF_Resolved );
  105065. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  105066. p->selFlags |= SF_HasTypeInfo;
  105067. pParse = pWalker->pParse;
  105068. pTabList = p->pSrc;
  105069. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  105070. Table *pTab = pFrom->pTab;
  105071. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  105072. /* A sub-query in the FROM clause of a SELECT */
  105073. Select *pSel = pFrom->pSelect;
  105074. if( pSel ){
  105075. while( pSel->pPrior ) pSel = pSel->pPrior;
  105076. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  105077. }
  105078. }
  105079. }
  105080. }
  105081. }
  105082. #endif
  105083. /*
  105084. ** This routine adds datatype and collating sequence information to
  105085. ** the Table structures of all FROM-clause subqueries in a
  105086. ** SELECT statement.
  105087. **
  105088. ** Use this routine after name resolution.
  105089. */
  105090. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  105091. #ifndef SQLITE_OMIT_SUBQUERY
  105092. Walker w;
  105093. memset(&w, 0, sizeof(w));
  105094. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  105095. w.xExprCallback = exprWalkNoop;
  105096. w.pParse = pParse;
  105097. sqlite3WalkSelect(&w, pSelect);
  105098. #endif
  105099. }
  105100. /*
  105101. ** This routine sets up a SELECT statement for processing. The
  105102. ** following is accomplished:
  105103. **
  105104. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  105105. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  105106. ** * ON and USING clauses are shifted into WHERE statements
  105107. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  105108. ** * Identifiers in expression are matched to tables.
  105109. **
  105110. ** This routine acts recursively on all subqueries within the SELECT.
  105111. */
  105112. SQLITE_PRIVATE void sqlite3SelectPrep(
  105113. Parse *pParse, /* The parser context */
  105114. Select *p, /* The SELECT statement being coded. */
  105115. NameContext *pOuterNC /* Name context for container */
  105116. ){
  105117. sqlite3 *db;
  105118. if( NEVER(p==0) ) return;
  105119. db = pParse->db;
  105120. if( db->mallocFailed ) return;
  105121. if( p->selFlags & SF_HasTypeInfo ) return;
  105122. sqlite3SelectExpand(pParse, p);
  105123. if( pParse->nErr || db->mallocFailed ) return;
  105124. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  105125. if( pParse->nErr || db->mallocFailed ) return;
  105126. sqlite3SelectAddTypeInfo(pParse, p);
  105127. }
  105128. /*
  105129. ** Reset the aggregate accumulator.
  105130. **
  105131. ** The aggregate accumulator is a set of memory cells that hold
  105132. ** intermediate results while calculating an aggregate. This
  105133. ** routine generates code that stores NULLs in all of those memory
  105134. ** cells.
  105135. */
  105136. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  105137. Vdbe *v = pParse->pVdbe;
  105138. int i;
  105139. struct AggInfo_func *pFunc;
  105140. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  105141. if( nReg==0 ) return;
  105142. #ifdef SQLITE_DEBUG
  105143. /* Verify that all AggInfo registers are within the range specified by
  105144. ** AggInfo.mnReg..AggInfo.mxReg */
  105145. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  105146. for(i=0; i<pAggInfo->nColumn; i++){
  105147. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  105148. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  105149. }
  105150. for(i=0; i<pAggInfo->nFunc; i++){
  105151. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  105152. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  105153. }
  105154. #endif
  105155. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  105156. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  105157. if( pFunc->iDistinct>=0 ){
  105158. Expr *pE = pFunc->pExpr;
  105159. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  105160. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  105161. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  105162. "argument");
  105163. pFunc->iDistinct = -1;
  105164. }else{
  105165. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  105166. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  105167. (char*)pKeyInfo, P4_KEYINFO);
  105168. }
  105169. }
  105170. }
  105171. }
  105172. /*
  105173. ** Invoke the OP_AggFinalize opcode for every aggregate function
  105174. ** in the AggInfo structure.
  105175. */
  105176. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  105177. Vdbe *v = pParse->pVdbe;
  105178. int i;
  105179. struct AggInfo_func *pF;
  105180. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  105181. ExprList *pList = pF->pExpr->x.pList;
  105182. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  105183. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  105184. (void*)pF->pFunc, P4_FUNCDEF);
  105185. }
  105186. }
  105187. /*
  105188. ** Update the accumulator memory cells for an aggregate based on
  105189. ** the current cursor position.
  105190. */
  105191. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  105192. Vdbe *v = pParse->pVdbe;
  105193. int i;
  105194. int regHit = 0;
  105195. int addrHitTest = 0;
  105196. struct AggInfo_func *pF;
  105197. struct AggInfo_col *pC;
  105198. pAggInfo->directMode = 1;
  105199. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  105200. int nArg;
  105201. int addrNext = 0;
  105202. int regAgg;
  105203. ExprList *pList = pF->pExpr->x.pList;
  105204. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  105205. if( pList ){
  105206. nArg = pList->nExpr;
  105207. regAgg = sqlite3GetTempRange(pParse, nArg);
  105208. sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
  105209. }else{
  105210. nArg = 0;
  105211. regAgg = 0;
  105212. }
  105213. if( pF->iDistinct>=0 ){
  105214. addrNext = sqlite3VdbeMakeLabel(v);
  105215. testcase( nArg==0 ); /* Error condition */
  105216. testcase( nArg>1 ); /* Also an error */
  105217. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  105218. }
  105219. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  105220. CollSeq *pColl = 0;
  105221. struct ExprList_item *pItem;
  105222. int j;
  105223. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  105224. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  105225. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  105226. }
  105227. if( !pColl ){
  105228. pColl = pParse->db->pDfltColl;
  105229. }
  105230. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  105231. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  105232. }
  105233. sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
  105234. (void*)pF->pFunc, P4_FUNCDEF);
  105235. sqlite3VdbeChangeP5(v, (u8)nArg);
  105236. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  105237. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  105238. if( addrNext ){
  105239. sqlite3VdbeResolveLabel(v, addrNext);
  105240. sqlite3ExprCacheClear(pParse);
  105241. }
  105242. }
  105243. /* Before populating the accumulator registers, clear the column cache.
  105244. ** Otherwise, if any of the required column values are already present
  105245. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  105246. ** to pC->iMem. But by the time the value is used, the original register
  105247. ** may have been used, invalidating the underlying buffer holding the
  105248. ** text or blob value. See ticket [883034dcb5].
  105249. **
  105250. ** Another solution would be to change the OP_SCopy used to copy cached
  105251. ** values to an OP_Copy.
  105252. */
  105253. if( regHit ){
  105254. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  105255. }
  105256. sqlite3ExprCacheClear(pParse);
  105257. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  105258. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  105259. }
  105260. pAggInfo->directMode = 0;
  105261. sqlite3ExprCacheClear(pParse);
  105262. if( addrHitTest ){
  105263. sqlite3VdbeJumpHere(v, addrHitTest);
  105264. }
  105265. }
  105266. /*
  105267. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  105268. ** count(*) query ("SELECT count(*) FROM pTab").
  105269. */
  105270. #ifndef SQLITE_OMIT_EXPLAIN
  105271. static void explainSimpleCount(
  105272. Parse *pParse, /* Parse context */
  105273. Table *pTab, /* Table being queried */
  105274. Index *pIdx /* Index used to optimize scan, or NULL */
  105275. ){
  105276. if( pParse->explain==2 ){
  105277. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  105278. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  105279. pTab->zName,
  105280. bCover ? " USING COVERING INDEX " : "",
  105281. bCover ? pIdx->zName : ""
  105282. );
  105283. sqlite3VdbeAddOp4(
  105284. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  105285. );
  105286. }
  105287. }
  105288. #else
  105289. # define explainSimpleCount(a,b,c)
  105290. #endif
  105291. /*
  105292. ** Generate code for the SELECT statement given in the p argument.
  105293. **
  105294. ** The results are returned according to the SelectDest structure.
  105295. ** See comments in sqliteInt.h for further information.
  105296. **
  105297. ** This routine returns the number of errors. If any errors are
  105298. ** encountered, then an appropriate error message is left in
  105299. ** pParse->zErrMsg.
  105300. **
  105301. ** This routine does NOT free the Select structure passed in. The
  105302. ** calling function needs to do that.
  105303. */
  105304. SQLITE_PRIVATE int sqlite3Select(
  105305. Parse *pParse, /* The parser context */
  105306. Select *p, /* The SELECT statement being coded. */
  105307. SelectDest *pDest /* What to do with the query results */
  105308. ){
  105309. int i, j; /* Loop counters */
  105310. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  105311. Vdbe *v; /* The virtual machine under construction */
  105312. int isAgg; /* True for select lists like "count(*)" */
  105313. ExprList *pEList = 0; /* List of columns to extract. */
  105314. SrcList *pTabList; /* List of tables to select from */
  105315. Expr *pWhere; /* The WHERE clause. May be NULL */
  105316. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  105317. Expr *pHaving; /* The HAVING clause. May be NULL */
  105318. int rc = 1; /* Value to return from this function */
  105319. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  105320. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  105321. AggInfo sAggInfo; /* Information used by aggregate queries */
  105322. int iEnd; /* Address of the end of the query */
  105323. sqlite3 *db; /* The database connection */
  105324. #ifndef SQLITE_OMIT_EXPLAIN
  105325. int iRestoreSelectId = pParse->iSelectId;
  105326. pParse->iSelectId = pParse->iNextSelectId++;
  105327. #endif
  105328. db = pParse->db;
  105329. if( p==0 || db->mallocFailed || pParse->nErr ){
  105330. return 1;
  105331. }
  105332. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  105333. memset(&sAggInfo, 0, sizeof(sAggInfo));
  105334. #if SELECTTRACE_ENABLED
  105335. pParse->nSelectIndent++;
  105336. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  105337. if( sqlite3SelectTrace & 0x100 ){
  105338. sqlite3TreeViewSelect(0, p, 0);
  105339. }
  105340. #endif
  105341. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  105342. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  105343. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  105344. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  105345. if( IgnorableOrderby(pDest) ){
  105346. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  105347. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  105348. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  105349. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  105350. /* If ORDER BY makes no difference in the output then neither does
  105351. ** DISTINCT so it can be removed too. */
  105352. sqlite3ExprListDelete(db, p->pOrderBy);
  105353. p->pOrderBy = 0;
  105354. p->selFlags &= ~SF_Distinct;
  105355. }
  105356. sqlite3SelectPrep(pParse, p, 0);
  105357. memset(&sSort, 0, sizeof(sSort));
  105358. sSort.pOrderBy = p->pOrderBy;
  105359. pTabList = p->pSrc;
  105360. if( pParse->nErr || db->mallocFailed ){
  105361. goto select_end;
  105362. }
  105363. assert( p->pEList!=0 );
  105364. isAgg = (p->selFlags & SF_Aggregate)!=0;
  105365. #if SELECTTRACE_ENABLED
  105366. if( sqlite3SelectTrace & 0x100 ){
  105367. SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
  105368. sqlite3TreeViewSelect(0, p, 0);
  105369. }
  105370. #endif
  105371. /* If writing to memory or generating a set
  105372. ** only a single column may be output.
  105373. */
  105374. #ifndef SQLITE_OMIT_SUBQUERY
  105375. if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
  105376. goto select_end;
  105377. }
  105378. #endif
  105379. /* Try to flatten subqueries in the FROM clause up into the main query
  105380. */
  105381. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  105382. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  105383. struct SrcList_item *pItem = &pTabList->a[i];
  105384. Select *pSub = pItem->pSelect;
  105385. int isAggSub;
  105386. if( pSub==0 ) continue;
  105387. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  105388. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  105389. /* This subquery can be absorbed into its parent. */
  105390. if( isAggSub ){
  105391. isAgg = 1;
  105392. p->selFlags |= SF_Aggregate;
  105393. }
  105394. i = -1;
  105395. }
  105396. pTabList = p->pSrc;
  105397. if( db->mallocFailed ) goto select_end;
  105398. if( !IgnorableOrderby(pDest) ){
  105399. sSort.pOrderBy = p->pOrderBy;
  105400. }
  105401. }
  105402. #endif
  105403. /* Get a pointer the VDBE under construction, allocating a new VDBE if one
  105404. ** does not already exist */
  105405. v = sqlite3GetVdbe(pParse);
  105406. if( v==0 ) goto select_end;
  105407. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  105408. /* Handle compound SELECT statements using the separate multiSelect()
  105409. ** procedure.
  105410. */
  105411. if( p->pPrior ){
  105412. rc = multiSelect(pParse, p, pDest);
  105413. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  105414. #if SELECTTRACE_ENABLED
  105415. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  105416. pParse->nSelectIndent--;
  105417. #endif
  105418. return rc;
  105419. }
  105420. #endif
  105421. /* Generate code for all sub-queries in the FROM clause
  105422. */
  105423. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  105424. for(i=0; i<pTabList->nSrc; i++){
  105425. struct SrcList_item *pItem = &pTabList->a[i];
  105426. SelectDest dest;
  105427. Select *pSub = pItem->pSelect;
  105428. if( pSub==0 ) continue;
  105429. /* Sometimes the code for a subquery will be generated more than
  105430. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  105431. ** for example. In that case, do not regenerate the code to manifest
  105432. ** a view or the co-routine to implement a view. The first instance
  105433. ** is sufficient, though the subroutine to manifest the view does need
  105434. ** to be invoked again. */
  105435. if( pItem->addrFillSub ){
  105436. if( pItem->viaCoroutine==0 ){
  105437. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  105438. }
  105439. continue;
  105440. }
  105441. /* Increment Parse.nHeight by the height of the largest expression
  105442. ** tree referred to by this, the parent select. The child select
  105443. ** may contain expression trees of at most
  105444. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  105445. ** more conservative than necessary, but much easier than enforcing
  105446. ** an exact limit.
  105447. */
  105448. pParse->nHeight += sqlite3SelectExprHeight(p);
  105449. /* Make copies of constant WHERE-clause terms in the outer query down
  105450. ** inside the subquery. This can help the subquery to run more efficiently.
  105451. */
  105452. if( (pItem->jointype & JT_OUTER)==0
  105453. && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
  105454. ){
  105455. #if SELECTTRACE_ENABLED
  105456. if( sqlite3SelectTrace & 0x100 ){
  105457. SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
  105458. sqlite3TreeViewSelect(0, p, 0);
  105459. }
  105460. #endif
  105461. }
  105462. /* Generate code to implement the subquery
  105463. */
  105464. if( pTabList->nSrc==1
  105465. && (p->selFlags & SF_All)==0
  105466. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  105467. ){
  105468. /* Implement a co-routine that will return a single row of the result
  105469. ** set on each invocation.
  105470. */
  105471. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  105472. pItem->regReturn = ++pParse->nMem;
  105473. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  105474. VdbeComment((v, "%s", pItem->pTab->zName));
  105475. pItem->addrFillSub = addrTop;
  105476. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  105477. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  105478. sqlite3Select(pParse, pSub, &dest);
  105479. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  105480. pItem->viaCoroutine = 1;
  105481. pItem->regResult = dest.iSdst;
  105482. sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
  105483. sqlite3VdbeJumpHere(v, addrTop-1);
  105484. sqlite3ClearTempRegCache(pParse);
  105485. }else{
  105486. /* Generate a subroutine that will fill an ephemeral table with
  105487. ** the content of this subquery. pItem->addrFillSub will point
  105488. ** to the address of the generated subroutine. pItem->regReturn
  105489. ** is a register allocated to hold the subroutine return address
  105490. */
  105491. int topAddr;
  105492. int onceAddr = 0;
  105493. int retAddr;
  105494. assert( pItem->addrFillSub==0 );
  105495. pItem->regReturn = ++pParse->nMem;
  105496. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  105497. pItem->addrFillSub = topAddr+1;
  105498. if( pItem->isCorrelated==0 ){
  105499. /* If the subquery is not correlated and if we are not inside of
  105500. ** a trigger, then we only need to compute the value of the subquery
  105501. ** once. */
  105502. onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  105503. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  105504. }else{
  105505. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  105506. }
  105507. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  105508. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  105509. sqlite3Select(pParse, pSub, &dest);
  105510. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  105511. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  105512. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  105513. VdbeComment((v, "end %s", pItem->pTab->zName));
  105514. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  105515. sqlite3ClearTempRegCache(pParse);
  105516. }
  105517. if( db->mallocFailed ) goto select_end;
  105518. pParse->nHeight -= sqlite3SelectExprHeight(p);
  105519. }
  105520. #endif
  105521. /* Various elements of the SELECT copied into local variables for
  105522. ** convenience */
  105523. pEList = p->pEList;
  105524. pWhere = p->pWhere;
  105525. pGroupBy = p->pGroupBy;
  105526. pHaving = p->pHaving;
  105527. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  105528. #if SELECTTRACE_ENABLED
  105529. if( sqlite3SelectTrace & 0x400 ){
  105530. SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
  105531. sqlite3TreeViewSelect(0, p, 0);
  105532. }
  105533. #endif
  105534. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  105535. ** if the select-list is the same as the ORDER BY list, then this query
  105536. ** can be rewritten as a GROUP BY. In other words, this:
  105537. **
  105538. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  105539. **
  105540. ** is transformed to:
  105541. **
  105542. ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
  105543. **
  105544. ** The second form is preferred as a single index (or temp-table) may be
  105545. ** used for both the ORDER BY and DISTINCT processing. As originally
  105546. ** written the query must use a temp-table for at least one of the ORDER
  105547. ** BY and DISTINCT, and an index or separate temp-table for the other.
  105548. */
  105549. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  105550. && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
  105551. ){
  105552. p->selFlags &= ~SF_Distinct;
  105553. pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
  105554. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  105555. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  105556. ** original setting of the SF_Distinct flag, not the current setting */
  105557. assert( sDistinct.isTnct );
  105558. }
  105559. /* If there is an ORDER BY clause, then create an ephemeral index to
  105560. ** do the sorting. But this sorting ephemeral index might end up
  105561. ** being unused if the data can be extracted in pre-sorted order.
  105562. ** If that is the case, then the OP_OpenEphemeral instruction will be
  105563. ** changed to an OP_Noop once we figure out that the sorting index is
  105564. ** not needed. The sSort.addrSortIndex variable is used to facilitate
  105565. ** that change.
  105566. */
  105567. if( sSort.pOrderBy ){
  105568. KeyInfo *pKeyInfo;
  105569. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
  105570. sSort.iECursor = pParse->nTab++;
  105571. sSort.addrSortIndex =
  105572. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  105573. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  105574. (char*)pKeyInfo, P4_KEYINFO
  105575. );
  105576. }else{
  105577. sSort.addrSortIndex = -1;
  105578. }
  105579. /* If the output is destined for a temporary table, open that table.
  105580. */
  105581. if( pDest->eDest==SRT_EphemTab ){
  105582. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  105583. }
  105584. /* Set the limiter.
  105585. */
  105586. iEnd = sqlite3VdbeMakeLabel(v);
  105587. p->nSelectRow = LARGEST_INT64;
  105588. computeLimitRegisters(pParse, p, iEnd);
  105589. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  105590. sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
  105591. sSort.sortFlags |= SORTFLAG_UseSorter;
  105592. }
  105593. /* Open an ephemeral index to use for the distinct set.
  105594. */
  105595. if( p->selFlags & SF_Distinct ){
  105596. sDistinct.tabTnct = pParse->nTab++;
  105597. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  105598. sDistinct.tabTnct, 0, 0,
  105599. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  105600. P4_KEYINFO);
  105601. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  105602. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  105603. }else{
  105604. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  105605. }
  105606. if( !isAgg && pGroupBy==0 ){
  105607. /* No aggregate functions and no GROUP BY clause */
  105608. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  105609. /* Begin the database scan. */
  105610. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  105611. p->pEList, wctrlFlags, 0);
  105612. if( pWInfo==0 ) goto select_end;
  105613. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  105614. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  105615. }
  105616. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  105617. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  105618. }
  105619. if( sSort.pOrderBy ){
  105620. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  105621. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  105622. sSort.pOrderBy = 0;
  105623. }
  105624. }
  105625. /* If sorting index that was created by a prior OP_OpenEphemeral
  105626. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  105627. ** into an OP_Noop.
  105628. */
  105629. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  105630. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  105631. }
  105632. /* Use the standard inner loop. */
  105633. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  105634. sqlite3WhereContinueLabel(pWInfo),
  105635. sqlite3WhereBreakLabel(pWInfo));
  105636. /* End the database scan loop.
  105637. */
  105638. sqlite3WhereEnd(pWInfo);
  105639. }else{
  105640. /* This case when there exist aggregate functions or a GROUP BY clause
  105641. ** or both */
  105642. NameContext sNC; /* Name context for processing aggregate information */
  105643. int iAMem; /* First Mem address for storing current GROUP BY */
  105644. int iBMem; /* First Mem address for previous GROUP BY */
  105645. int iUseFlag; /* Mem address holding flag indicating that at least
  105646. ** one row of the input to the aggregator has been
  105647. ** processed */
  105648. int iAbortFlag; /* Mem address which causes query abort if positive */
  105649. int groupBySort; /* Rows come from source in GROUP BY order */
  105650. int addrEnd; /* End of processing for this SELECT */
  105651. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  105652. int sortOut = 0; /* Output register from the sorter */
  105653. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  105654. /* Remove any and all aliases between the result set and the
  105655. ** GROUP BY clause.
  105656. */
  105657. if( pGroupBy ){
  105658. int k; /* Loop counter */
  105659. struct ExprList_item *pItem; /* For looping over expression in a list */
  105660. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  105661. pItem->u.x.iAlias = 0;
  105662. }
  105663. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  105664. pItem->u.x.iAlias = 0;
  105665. }
  105666. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  105667. }else{
  105668. p->nSelectRow = 1;
  105669. }
  105670. /* If there is both a GROUP BY and an ORDER BY clause and they are
  105671. ** identical, then it may be possible to disable the ORDER BY clause
  105672. ** on the grounds that the GROUP BY will cause elements to come out
  105673. ** in the correct order. It also may not - the GROUP BY might use a
  105674. ** database index that causes rows to be grouped together as required
  105675. ** but not actually sorted. Either way, record the fact that the
  105676. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  105677. ** variable. */
  105678. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  105679. orderByGrp = 1;
  105680. }
  105681. /* Create a label to jump to when we want to abort the query */
  105682. addrEnd = sqlite3VdbeMakeLabel(v);
  105683. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  105684. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  105685. ** SELECT statement.
  105686. */
  105687. memset(&sNC, 0, sizeof(sNC));
  105688. sNC.pParse = pParse;
  105689. sNC.pSrcList = pTabList;
  105690. sNC.pAggInfo = &sAggInfo;
  105691. sAggInfo.mnReg = pParse->nMem+1;
  105692. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  105693. sAggInfo.pGroupBy = pGroupBy;
  105694. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  105695. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  105696. if( pHaving ){
  105697. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  105698. }
  105699. sAggInfo.nAccumulator = sAggInfo.nColumn;
  105700. for(i=0; i<sAggInfo.nFunc; i++){
  105701. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  105702. sNC.ncFlags |= NC_InAggFunc;
  105703. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  105704. sNC.ncFlags &= ~NC_InAggFunc;
  105705. }
  105706. sAggInfo.mxReg = pParse->nMem;
  105707. if( db->mallocFailed ) goto select_end;
  105708. /* Processing for aggregates with GROUP BY is very different and
  105709. ** much more complex than aggregates without a GROUP BY.
  105710. */
  105711. if( pGroupBy ){
  105712. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  105713. int j1; /* A-vs-B comparision jump */
  105714. int addrOutputRow; /* Start of subroutine that outputs a result row */
  105715. int regOutputRow; /* Return address register for output subroutine */
  105716. int addrSetAbort; /* Set the abort flag and return */
  105717. int addrTopOfLoop; /* Top of the input loop */
  105718. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  105719. int addrReset; /* Subroutine for resetting the accumulator */
  105720. int regReset; /* Return address register for reset subroutine */
  105721. /* If there is a GROUP BY clause we might need a sorting index to
  105722. ** implement it. Allocate that sorting index now. If it turns out
  105723. ** that we do not need it after all, the OP_SorterOpen instruction
  105724. ** will be converted into a Noop.
  105725. */
  105726. sAggInfo.sortingIdx = pParse->nTab++;
  105727. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
  105728. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  105729. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  105730. 0, (char*)pKeyInfo, P4_KEYINFO);
  105731. /* Initialize memory locations used by GROUP BY aggregate processing
  105732. */
  105733. iUseFlag = ++pParse->nMem;
  105734. iAbortFlag = ++pParse->nMem;
  105735. regOutputRow = ++pParse->nMem;
  105736. addrOutputRow = sqlite3VdbeMakeLabel(v);
  105737. regReset = ++pParse->nMem;
  105738. addrReset = sqlite3VdbeMakeLabel(v);
  105739. iAMem = pParse->nMem + 1;
  105740. pParse->nMem += pGroupBy->nExpr;
  105741. iBMem = pParse->nMem + 1;
  105742. pParse->nMem += pGroupBy->nExpr;
  105743. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  105744. VdbeComment((v, "clear abort flag"));
  105745. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  105746. VdbeComment((v, "indicate accumulator empty"));
  105747. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  105748. /* Begin a loop that will extract all source rows in GROUP BY order.
  105749. ** This might involve two separate loops with an OP_Sort in between, or
  105750. ** it might be a single loop that uses an index to extract information
  105751. ** in the right order to begin with.
  105752. */
  105753. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  105754. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  105755. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  105756. );
  105757. if( pWInfo==0 ) goto select_end;
  105758. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  105759. /* The optimizer is able to deliver rows in group by order so
  105760. ** we do not have to sort. The OP_OpenEphemeral table will be
  105761. ** cancelled later because we still need to use the pKeyInfo
  105762. */
  105763. groupBySort = 0;
  105764. }else{
  105765. /* Rows are coming out in undetermined order. We have to push
  105766. ** each row into a sorting index, terminate the first loop,
  105767. ** then loop over the sorting index in order to get the output
  105768. ** in sorted order
  105769. */
  105770. int regBase;
  105771. int regRecord;
  105772. int nCol;
  105773. int nGroupBy;
  105774. explainTempTable(pParse,
  105775. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  105776. "DISTINCT" : "GROUP BY");
  105777. groupBySort = 1;
  105778. nGroupBy = pGroupBy->nExpr;
  105779. nCol = nGroupBy;
  105780. j = nGroupBy;
  105781. for(i=0; i<sAggInfo.nColumn; i++){
  105782. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  105783. nCol++;
  105784. j++;
  105785. }
  105786. }
  105787. regBase = sqlite3GetTempRange(pParse, nCol);
  105788. sqlite3ExprCacheClear(pParse);
  105789. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  105790. j = nGroupBy;
  105791. for(i=0; i<sAggInfo.nColumn; i++){
  105792. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  105793. if( pCol->iSorterColumn>=j ){
  105794. int r1 = j + regBase;
  105795. int r2;
  105796. r2 = sqlite3ExprCodeGetColumn(pParse,
  105797. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  105798. if( r1!=r2 ){
  105799. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  105800. }
  105801. j++;
  105802. }
  105803. }
  105804. regRecord = sqlite3GetTempReg(pParse);
  105805. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  105806. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  105807. sqlite3ReleaseTempReg(pParse, regRecord);
  105808. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  105809. sqlite3WhereEnd(pWInfo);
  105810. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  105811. sortOut = sqlite3GetTempReg(pParse);
  105812. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  105813. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  105814. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  105815. sAggInfo.useSortingIdx = 1;
  105816. sqlite3ExprCacheClear(pParse);
  105817. }
  105818. /* If the index or temporary table used by the GROUP BY sort
  105819. ** will naturally deliver rows in the order required by the ORDER BY
  105820. ** clause, cancel the ephemeral table open coded earlier.
  105821. **
  105822. ** This is an optimization - the correct answer should result regardless.
  105823. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  105824. ** disable this optimization for testing purposes. */
  105825. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  105826. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  105827. ){
  105828. sSort.pOrderBy = 0;
  105829. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  105830. }
  105831. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  105832. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  105833. ** Then compare the current GROUP BY terms against the GROUP BY terms
  105834. ** from the previous row currently stored in a0, a1, a2...
  105835. */
  105836. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  105837. sqlite3ExprCacheClear(pParse);
  105838. if( groupBySort ){
  105839. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx,
  105840. sortOut, sortPTab);
  105841. }
  105842. for(j=0; j<pGroupBy->nExpr; j++){
  105843. if( groupBySort ){
  105844. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  105845. }else{
  105846. sAggInfo.directMode = 1;
  105847. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  105848. }
  105849. }
  105850. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  105851. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  105852. j1 = sqlite3VdbeCurrentAddr(v);
  105853. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
  105854. /* Generate code that runs whenever the GROUP BY changes.
  105855. ** Changes in the GROUP BY are detected by the previous code
  105856. ** block. If there were no changes, this block is skipped.
  105857. **
  105858. ** This code copies current group by terms in b0,b1,b2,...
  105859. ** over to a0,a1,a2. It then calls the output subroutine
  105860. ** and resets the aggregate accumulator registers in preparation
  105861. ** for the next GROUP BY batch.
  105862. */
  105863. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  105864. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  105865. VdbeComment((v, "output one row"));
  105866. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  105867. VdbeComment((v, "check abort flag"));
  105868. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  105869. VdbeComment((v, "reset accumulator"));
  105870. /* Update the aggregate accumulators based on the content of
  105871. ** the current row
  105872. */
  105873. sqlite3VdbeJumpHere(v, j1);
  105874. updateAccumulator(pParse, &sAggInfo);
  105875. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  105876. VdbeComment((v, "indicate data in accumulator"));
  105877. /* End of the loop
  105878. */
  105879. if( groupBySort ){
  105880. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  105881. VdbeCoverage(v);
  105882. }else{
  105883. sqlite3WhereEnd(pWInfo);
  105884. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  105885. }
  105886. /* Output the final row of result
  105887. */
  105888. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  105889. VdbeComment((v, "output final row"));
  105890. /* Jump over the subroutines
  105891. */
  105892. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  105893. /* Generate a subroutine that outputs a single row of the result
  105894. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  105895. ** is less than or equal to zero, the subroutine is a no-op. If
  105896. ** the processing calls for the query to abort, this subroutine
  105897. ** increments the iAbortFlag memory location before returning in
  105898. ** order to signal the caller to abort.
  105899. */
  105900. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  105901. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  105902. VdbeComment((v, "set abort flag"));
  105903. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  105904. sqlite3VdbeResolveLabel(v, addrOutputRow);
  105905. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  105906. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  105907. VdbeCoverage(v);
  105908. VdbeComment((v, "Groupby result generator entry point"));
  105909. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  105910. finalizeAggFunctions(pParse, &sAggInfo);
  105911. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  105912. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  105913. &sDistinct, pDest,
  105914. addrOutputRow+1, addrSetAbort);
  105915. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  105916. VdbeComment((v, "end groupby result generator"));
  105917. /* Generate a subroutine that will reset the group-by accumulator
  105918. */
  105919. sqlite3VdbeResolveLabel(v, addrReset);
  105920. resetAccumulator(pParse, &sAggInfo);
  105921. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  105922. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  105923. else {
  105924. ExprList *pDel = 0;
  105925. #ifndef SQLITE_OMIT_BTREECOUNT
  105926. Table *pTab;
  105927. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  105928. /* If isSimpleCount() returns a pointer to a Table structure, then
  105929. ** the SQL statement is of the form:
  105930. **
  105931. ** SELECT count(*) FROM <tbl>
  105932. **
  105933. ** where the Table structure returned represents table <tbl>.
  105934. **
  105935. ** This statement is so common that it is optimized specially. The
  105936. ** OP_Count instruction is executed either on the intkey table that
  105937. ** contains the data for table <tbl> or on one of its indexes. It
  105938. ** is better to execute the op on an index, as indexes are almost
  105939. ** always spread across less pages than their corresponding tables.
  105940. */
  105941. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  105942. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  105943. Index *pIdx; /* Iterator variable */
  105944. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  105945. Index *pBest = 0; /* Best index found so far */
  105946. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  105947. sqlite3CodeVerifySchema(pParse, iDb);
  105948. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  105949. /* Search for the index that has the lowest scan cost.
  105950. **
  105951. ** (2011-04-15) Do not do a full scan of an unordered index.
  105952. **
  105953. ** (2013-10-03) Do not count the entries in a partial index.
  105954. **
  105955. ** In practice the KeyInfo structure will not be used. It is only
  105956. ** passed to keep OP_OpenRead happy.
  105957. */
  105958. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  105959. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  105960. if( pIdx->bUnordered==0
  105961. && pIdx->szIdxRow<pTab->szTabRow
  105962. && pIdx->pPartIdxWhere==0
  105963. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  105964. ){
  105965. pBest = pIdx;
  105966. }
  105967. }
  105968. if( pBest ){
  105969. iRoot = pBest->tnum;
  105970. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  105971. }
  105972. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  105973. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  105974. if( pKeyInfo ){
  105975. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  105976. }
  105977. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  105978. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  105979. explainSimpleCount(pParse, pTab, pBest);
  105980. }else
  105981. #endif /* SQLITE_OMIT_BTREECOUNT */
  105982. {
  105983. /* Check if the query is of one of the following forms:
  105984. **
  105985. ** SELECT min(x) FROM ...
  105986. ** SELECT max(x) FROM ...
  105987. **
  105988. ** If it is, then ask the code in where.c to attempt to sort results
  105989. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  105990. ** If where.c is able to produce results sorted in this order, then
  105991. ** add vdbe code to break out of the processing loop after the
  105992. ** first iteration (since the first iteration of the loop is
  105993. ** guaranteed to operate on the row with the minimum or maximum
  105994. ** value of x, the only row required).
  105995. **
  105996. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  105997. ** modify behavior as follows:
  105998. **
  105999. ** + If the query is a "SELECT min(x)", then the loop coded by
  106000. ** where.c should not iterate over any values with a NULL value
  106001. ** for x.
  106002. **
  106003. ** + The optimizer code in where.c (the thing that decides which
  106004. ** index or indices to use) should place a different priority on
  106005. ** satisfying the 'ORDER BY' clause than it does in other cases.
  106006. ** Refer to code and comments in where.c for details.
  106007. */
  106008. ExprList *pMinMax = 0;
  106009. u8 flag = WHERE_ORDERBY_NORMAL;
  106010. assert( p->pGroupBy==0 );
  106011. assert( flag==0 );
  106012. if( p->pHaving==0 ){
  106013. flag = minMaxQuery(&sAggInfo, &pMinMax);
  106014. }
  106015. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  106016. if( flag ){
  106017. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  106018. pDel = pMinMax;
  106019. if( pMinMax && !db->mallocFailed ){
  106020. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  106021. pMinMax->a[0].pExpr->op = TK_COLUMN;
  106022. }
  106023. }
  106024. /* This case runs if the aggregate has no GROUP BY clause. The
  106025. ** processing is much simpler since there is only a single row
  106026. ** of output.
  106027. */
  106028. resetAccumulator(pParse, &sAggInfo);
  106029. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  106030. if( pWInfo==0 ){
  106031. sqlite3ExprListDelete(db, pDel);
  106032. goto select_end;
  106033. }
  106034. updateAccumulator(pParse, &sAggInfo);
  106035. assert( pMinMax==0 || pMinMax->nExpr==1 );
  106036. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  106037. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  106038. VdbeComment((v, "%s() by index",
  106039. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  106040. }
  106041. sqlite3WhereEnd(pWInfo);
  106042. finalizeAggFunctions(pParse, &sAggInfo);
  106043. }
  106044. sSort.pOrderBy = 0;
  106045. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  106046. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  106047. pDest, addrEnd, addrEnd);
  106048. sqlite3ExprListDelete(db, pDel);
  106049. }
  106050. sqlite3VdbeResolveLabel(v, addrEnd);
  106051. } /* endif aggregate query */
  106052. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  106053. explainTempTable(pParse, "DISTINCT");
  106054. }
  106055. /* If there is an ORDER BY clause, then we need to sort the results
  106056. ** and send them to the callback one by one.
  106057. */
  106058. if( sSort.pOrderBy ){
  106059. explainTempTable(pParse,
  106060. sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  106061. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  106062. }
  106063. /* Jump here to skip this query
  106064. */
  106065. sqlite3VdbeResolveLabel(v, iEnd);
  106066. /* The SELECT has been coded. If there is an error in the Parse structure,
  106067. ** set the return code to 1. Otherwise 0. */
  106068. rc = (pParse->nErr>0);
  106069. /* Control jumps to here if an error is encountered above, or upon
  106070. ** successful coding of the SELECT.
  106071. */
  106072. select_end:
  106073. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  106074. /* Identify column names if results of the SELECT are to be output.
  106075. */
  106076. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  106077. generateColumnNames(pParse, pTabList, pEList);
  106078. }
  106079. sqlite3DbFree(db, sAggInfo.aCol);
  106080. sqlite3DbFree(db, sAggInfo.aFunc);
  106081. #if SELECTTRACE_ENABLED
  106082. SELECTTRACE(1,pParse,p,("end processing\n"));
  106083. pParse->nSelectIndent--;
  106084. #endif
  106085. return rc;
  106086. }
  106087. /************** End of select.c **********************************************/
  106088. /************** Begin file table.c *******************************************/
  106089. /*
  106090. ** 2001 September 15
  106091. **
  106092. ** The author disclaims copyright to this source code. In place of
  106093. ** a legal notice, here is a blessing:
  106094. **
  106095. ** May you do good and not evil.
  106096. ** May you find forgiveness for yourself and forgive others.
  106097. ** May you share freely, never taking more than you give.
  106098. **
  106099. *************************************************************************
  106100. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  106101. ** interface routines. These are just wrappers around the main
  106102. ** interface routine of sqlite3_exec().
  106103. **
  106104. ** These routines are in a separate files so that they will not be linked
  106105. ** if they are not used.
  106106. */
  106107. /* #include "sqliteInt.h" */
  106108. /* #include <stdlib.h> */
  106109. /* #include <string.h> */
  106110. #ifndef SQLITE_OMIT_GET_TABLE
  106111. /*
  106112. ** This structure is used to pass data from sqlite3_get_table() through
  106113. ** to the callback function is uses to build the result.
  106114. */
  106115. typedef struct TabResult {
  106116. char **azResult; /* Accumulated output */
  106117. char *zErrMsg; /* Error message text, if an error occurs */
  106118. u32 nAlloc; /* Slots allocated for azResult[] */
  106119. u32 nRow; /* Number of rows in the result */
  106120. u32 nColumn; /* Number of columns in the result */
  106121. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  106122. int rc; /* Return code from sqlite3_exec() */
  106123. } TabResult;
  106124. /*
  106125. ** This routine is called once for each row in the result table. Its job
  106126. ** is to fill in the TabResult structure appropriately, allocating new
  106127. ** memory as necessary.
  106128. */
  106129. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  106130. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  106131. int need; /* Slots needed in p->azResult[] */
  106132. int i; /* Loop counter */
  106133. char *z; /* A single column of result */
  106134. /* Make sure there is enough space in p->azResult to hold everything
  106135. ** we need to remember from this invocation of the callback.
  106136. */
  106137. if( p->nRow==0 && argv!=0 ){
  106138. need = nCol*2;
  106139. }else{
  106140. need = nCol;
  106141. }
  106142. if( p->nData + need > p->nAlloc ){
  106143. char **azNew;
  106144. p->nAlloc = p->nAlloc*2 + need;
  106145. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  106146. if( azNew==0 ) goto malloc_failed;
  106147. p->azResult = azNew;
  106148. }
  106149. /* If this is the first row, then generate an extra row containing
  106150. ** the names of all columns.
  106151. */
  106152. if( p->nRow==0 ){
  106153. p->nColumn = nCol;
  106154. for(i=0; i<nCol; i++){
  106155. z = sqlite3_mprintf("%s", colv[i]);
  106156. if( z==0 ) goto malloc_failed;
  106157. p->azResult[p->nData++] = z;
  106158. }
  106159. }else if( (int)p->nColumn!=nCol ){
  106160. sqlite3_free(p->zErrMsg);
  106161. p->zErrMsg = sqlite3_mprintf(
  106162. "sqlite3_get_table() called with two or more incompatible queries"
  106163. );
  106164. p->rc = SQLITE_ERROR;
  106165. return 1;
  106166. }
  106167. /* Copy over the row data
  106168. */
  106169. if( argv!=0 ){
  106170. for(i=0; i<nCol; i++){
  106171. if( argv[i]==0 ){
  106172. z = 0;
  106173. }else{
  106174. int n = sqlite3Strlen30(argv[i])+1;
  106175. z = sqlite3_malloc64( n );
  106176. if( z==0 ) goto malloc_failed;
  106177. memcpy(z, argv[i], n);
  106178. }
  106179. p->azResult[p->nData++] = z;
  106180. }
  106181. p->nRow++;
  106182. }
  106183. return 0;
  106184. malloc_failed:
  106185. p->rc = SQLITE_NOMEM;
  106186. return 1;
  106187. }
  106188. /*
  106189. ** Query the database. But instead of invoking a callback for each row,
  106190. ** malloc() for space to hold the result and return the entire results
  106191. ** at the conclusion of the call.
  106192. **
  106193. ** The result that is written to ***pazResult is held in memory obtained
  106194. ** from malloc(). But the caller cannot free this memory directly.
  106195. ** Instead, the entire table should be passed to sqlite3_free_table() when
  106196. ** the calling procedure is finished using it.
  106197. */
  106198. SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
  106199. sqlite3 *db, /* The database on which the SQL executes */
  106200. const char *zSql, /* The SQL to be executed */
  106201. char ***pazResult, /* Write the result table here */
  106202. int *pnRow, /* Write the number of rows in the result here */
  106203. int *pnColumn, /* Write the number of columns of result here */
  106204. char **pzErrMsg /* Write error messages here */
  106205. ){
  106206. int rc;
  106207. TabResult res;
  106208. #ifdef SQLITE_ENABLE_API_ARMOR
  106209. if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
  106210. #endif
  106211. *pazResult = 0;
  106212. if( pnColumn ) *pnColumn = 0;
  106213. if( pnRow ) *pnRow = 0;
  106214. if( pzErrMsg ) *pzErrMsg = 0;
  106215. res.zErrMsg = 0;
  106216. res.nRow = 0;
  106217. res.nColumn = 0;
  106218. res.nData = 1;
  106219. res.nAlloc = 20;
  106220. res.rc = SQLITE_OK;
  106221. res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
  106222. if( res.azResult==0 ){
  106223. db->errCode = SQLITE_NOMEM;
  106224. return SQLITE_NOMEM;
  106225. }
  106226. res.azResult[0] = 0;
  106227. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  106228. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  106229. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  106230. if( (rc&0xff)==SQLITE_ABORT ){
  106231. sqlite3_free_table(&res.azResult[1]);
  106232. if( res.zErrMsg ){
  106233. if( pzErrMsg ){
  106234. sqlite3_free(*pzErrMsg);
  106235. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  106236. }
  106237. sqlite3_free(res.zErrMsg);
  106238. }
  106239. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  106240. return res.rc;
  106241. }
  106242. sqlite3_free(res.zErrMsg);
  106243. if( rc!=SQLITE_OK ){
  106244. sqlite3_free_table(&res.azResult[1]);
  106245. return rc;
  106246. }
  106247. if( res.nAlloc>res.nData ){
  106248. char **azNew;
  106249. azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
  106250. if( azNew==0 ){
  106251. sqlite3_free_table(&res.azResult[1]);
  106252. db->errCode = SQLITE_NOMEM;
  106253. return SQLITE_NOMEM;
  106254. }
  106255. res.azResult = azNew;
  106256. }
  106257. *pazResult = &res.azResult[1];
  106258. if( pnColumn ) *pnColumn = res.nColumn;
  106259. if( pnRow ) *pnRow = res.nRow;
  106260. return rc;
  106261. }
  106262. /*
  106263. ** This routine frees the space the sqlite3_get_table() malloced.
  106264. */
  106265. SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
  106266. char **azResult /* Result returned from sqlite3_get_table() */
  106267. ){
  106268. if( azResult ){
  106269. int i, n;
  106270. azResult--;
  106271. assert( azResult!=0 );
  106272. n = SQLITE_PTR_TO_INT(azResult[0]);
  106273. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  106274. sqlite3_free(azResult);
  106275. }
  106276. }
  106277. #endif /* SQLITE_OMIT_GET_TABLE */
  106278. /************** End of table.c ***********************************************/
  106279. /************** Begin file trigger.c *****************************************/
  106280. /*
  106281. **
  106282. ** The author disclaims copyright to this source code. In place of
  106283. ** a legal notice, here is a blessing:
  106284. **
  106285. ** May you do good and not evil.
  106286. ** May you find forgiveness for yourself and forgive others.
  106287. ** May you share freely, never taking more than you give.
  106288. **
  106289. *************************************************************************
  106290. ** This file contains the implementation for TRIGGERs
  106291. */
  106292. /* #include "sqliteInt.h" */
  106293. #ifndef SQLITE_OMIT_TRIGGER
  106294. /*
  106295. ** Delete a linked list of TriggerStep structures.
  106296. */
  106297. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  106298. while( pTriggerStep ){
  106299. TriggerStep * pTmp = pTriggerStep;
  106300. pTriggerStep = pTriggerStep->pNext;
  106301. sqlite3ExprDelete(db, pTmp->pWhere);
  106302. sqlite3ExprListDelete(db, pTmp->pExprList);
  106303. sqlite3SelectDelete(db, pTmp->pSelect);
  106304. sqlite3IdListDelete(db, pTmp->pIdList);
  106305. sqlite3DbFree(db, pTmp);
  106306. }
  106307. }
  106308. /*
  106309. ** Given table pTab, return a list of all the triggers attached to
  106310. ** the table. The list is connected by Trigger.pNext pointers.
  106311. **
  106312. ** All of the triggers on pTab that are in the same database as pTab
  106313. ** are already attached to pTab->pTrigger. But there might be additional
  106314. ** triggers on pTab in the TEMP schema. This routine prepends all
  106315. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  106316. ** and returns the combined list.
  106317. **
  106318. ** To state it another way: This routine returns a list of all triggers
  106319. ** that fire off of pTab. The list will include any TEMP triggers on
  106320. ** pTab as well as the triggers lised in pTab->pTrigger.
  106321. */
  106322. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  106323. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  106324. Trigger *pList = 0; /* List of triggers to return */
  106325. if( pParse->disableTriggers ){
  106326. return 0;
  106327. }
  106328. if( pTmpSchema!=pTab->pSchema ){
  106329. HashElem *p;
  106330. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  106331. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  106332. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  106333. if( pTrig->pTabSchema==pTab->pSchema
  106334. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  106335. ){
  106336. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  106337. pList = pTrig;
  106338. }
  106339. }
  106340. }
  106341. return (pList ? pList : pTab->pTrigger);
  106342. }
  106343. /*
  106344. ** This is called by the parser when it sees a CREATE TRIGGER statement
  106345. ** up to the point of the BEGIN before the trigger actions. A Trigger
  106346. ** structure is generated based on the information available and stored
  106347. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  106348. ** sqlite3FinishTrigger() function is called to complete the trigger
  106349. ** construction process.
  106350. */
  106351. SQLITE_PRIVATE void sqlite3BeginTrigger(
  106352. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  106353. Token *pName1, /* The name of the trigger */
  106354. Token *pName2, /* The name of the trigger */
  106355. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  106356. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  106357. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  106358. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  106359. Expr *pWhen, /* WHEN clause */
  106360. int isTemp, /* True if the TEMPORARY keyword is present */
  106361. int noErr /* Suppress errors if the trigger already exists */
  106362. ){
  106363. Trigger *pTrigger = 0; /* The new trigger */
  106364. Table *pTab; /* Table that the trigger fires off of */
  106365. char *zName = 0; /* Name of the trigger */
  106366. sqlite3 *db = pParse->db; /* The database connection */
  106367. int iDb; /* The database to store the trigger in */
  106368. Token *pName; /* The unqualified db name */
  106369. DbFixer sFix; /* State vector for the DB fixer */
  106370. int iTabDb; /* Index of the database holding pTab */
  106371. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  106372. assert( pName2!=0 );
  106373. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  106374. assert( op>0 && op<0xff );
  106375. if( isTemp ){
  106376. /* If TEMP was specified, then the trigger name may not be qualified. */
  106377. if( pName2->n>0 ){
  106378. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  106379. goto trigger_cleanup;
  106380. }
  106381. iDb = 1;
  106382. pName = pName1;
  106383. }else{
  106384. /* Figure out the db that the trigger will be created in */
  106385. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  106386. if( iDb<0 ){
  106387. goto trigger_cleanup;
  106388. }
  106389. }
  106390. if( !pTableName || db->mallocFailed ){
  106391. goto trigger_cleanup;
  106392. }
  106393. /* A long-standing parser bug is that this syntax was allowed:
  106394. **
  106395. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  106396. ** ^^^^^^^^
  106397. **
  106398. ** To maintain backwards compatibility, ignore the database
  106399. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  106400. */
  106401. if( db->init.busy && iDb!=1 ){
  106402. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  106403. pTableName->a[0].zDatabase = 0;
  106404. }
  106405. /* If the trigger name was unqualified, and the table is a temp table,
  106406. ** then set iDb to 1 to create the trigger in the temporary database.
  106407. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  106408. ** exist, the error is caught by the block below.
  106409. */
  106410. pTab = sqlite3SrcListLookup(pParse, pTableName);
  106411. if( db->init.busy==0 && pName2->n==0 && pTab
  106412. && pTab->pSchema==db->aDb[1].pSchema ){
  106413. iDb = 1;
  106414. }
  106415. /* Ensure the table name matches database name and that the table exists */
  106416. if( db->mallocFailed ) goto trigger_cleanup;
  106417. assert( pTableName->nSrc==1 );
  106418. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  106419. if( sqlite3FixSrcList(&sFix, pTableName) ){
  106420. goto trigger_cleanup;
  106421. }
  106422. pTab = sqlite3SrcListLookup(pParse, pTableName);
  106423. if( !pTab ){
  106424. /* The table does not exist. */
  106425. if( db->init.iDb==1 ){
  106426. /* Ticket #3810.
  106427. ** Normally, whenever a table is dropped, all associated triggers are
  106428. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  106429. ** and the table is dropped by a different database connection, the
  106430. ** trigger is not visible to the database connection that does the
  106431. ** drop so the trigger cannot be dropped. This results in an
  106432. ** "orphaned trigger" - a trigger whose associated table is missing.
  106433. */
  106434. db->init.orphanTrigger = 1;
  106435. }
  106436. goto trigger_cleanup;
  106437. }
  106438. if( IsVirtual(pTab) ){
  106439. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  106440. goto trigger_cleanup;
  106441. }
  106442. /* Check that the trigger name is not reserved and that no trigger of the
  106443. ** specified name exists */
  106444. zName = sqlite3NameFromToken(db, pName);
  106445. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  106446. goto trigger_cleanup;
  106447. }
  106448. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106449. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  106450. if( !noErr ){
  106451. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  106452. }else{
  106453. assert( !db->init.busy );
  106454. sqlite3CodeVerifySchema(pParse, iDb);
  106455. }
  106456. goto trigger_cleanup;
  106457. }
  106458. /* Do not create a trigger on a system table */
  106459. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  106460. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  106461. goto trigger_cleanup;
  106462. }
  106463. /* INSTEAD of triggers are only for views and views only support INSTEAD
  106464. ** of triggers.
  106465. */
  106466. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  106467. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  106468. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  106469. goto trigger_cleanup;
  106470. }
  106471. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  106472. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  106473. " trigger on table: %S", pTableName, 0);
  106474. goto trigger_cleanup;
  106475. }
  106476. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  106477. #ifndef SQLITE_OMIT_AUTHORIZATION
  106478. {
  106479. int code = SQLITE_CREATE_TRIGGER;
  106480. const char *zDb = db->aDb[iTabDb].zName;
  106481. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  106482. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  106483. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  106484. goto trigger_cleanup;
  106485. }
  106486. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  106487. goto trigger_cleanup;
  106488. }
  106489. }
  106490. #endif
  106491. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  106492. ** cannot appear on views. So we might as well translate every
  106493. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  106494. ** elsewhere.
  106495. */
  106496. if (tr_tm == TK_INSTEAD){
  106497. tr_tm = TK_BEFORE;
  106498. }
  106499. /* Build the Trigger object */
  106500. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  106501. if( pTrigger==0 ) goto trigger_cleanup;
  106502. pTrigger->zName = zName;
  106503. zName = 0;
  106504. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  106505. pTrigger->pSchema = db->aDb[iDb].pSchema;
  106506. pTrigger->pTabSchema = pTab->pSchema;
  106507. pTrigger->op = (u8)op;
  106508. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  106509. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  106510. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  106511. assert( pParse->pNewTrigger==0 );
  106512. pParse->pNewTrigger = pTrigger;
  106513. trigger_cleanup:
  106514. sqlite3DbFree(db, zName);
  106515. sqlite3SrcListDelete(db, pTableName);
  106516. sqlite3IdListDelete(db, pColumns);
  106517. sqlite3ExprDelete(db, pWhen);
  106518. if( !pParse->pNewTrigger ){
  106519. sqlite3DeleteTrigger(db, pTrigger);
  106520. }else{
  106521. assert( pParse->pNewTrigger==pTrigger );
  106522. }
  106523. }
  106524. /*
  106525. ** This routine is called after all of the trigger actions have been parsed
  106526. ** in order to complete the process of building the trigger.
  106527. */
  106528. SQLITE_PRIVATE void sqlite3FinishTrigger(
  106529. Parse *pParse, /* Parser context */
  106530. TriggerStep *pStepList, /* The triggered program */
  106531. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  106532. ){
  106533. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  106534. char *zName; /* Name of trigger */
  106535. sqlite3 *db = pParse->db; /* The database */
  106536. DbFixer sFix; /* Fixer object */
  106537. int iDb; /* Database containing the trigger */
  106538. Token nameToken; /* Trigger name for error reporting */
  106539. pParse->pNewTrigger = 0;
  106540. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  106541. zName = pTrig->zName;
  106542. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  106543. pTrig->step_list = pStepList;
  106544. while( pStepList ){
  106545. pStepList->pTrig = pTrig;
  106546. pStepList = pStepList->pNext;
  106547. }
  106548. nameToken.z = pTrig->zName;
  106549. nameToken.n = sqlite3Strlen30(nameToken.z);
  106550. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  106551. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  106552. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  106553. ){
  106554. goto triggerfinish_cleanup;
  106555. }
  106556. /* if we are not initializing,
  106557. ** build the sqlite_master entry
  106558. */
  106559. if( !db->init.busy ){
  106560. Vdbe *v;
  106561. char *z;
  106562. /* Make an entry in the sqlite_master table */
  106563. v = sqlite3GetVdbe(pParse);
  106564. if( v==0 ) goto triggerfinish_cleanup;
  106565. sqlite3BeginWriteOperation(pParse, 0, iDb);
  106566. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  106567. sqlite3NestedParse(pParse,
  106568. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  106569. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  106570. pTrig->table, z);
  106571. sqlite3DbFree(db, z);
  106572. sqlite3ChangeCookie(pParse, iDb);
  106573. sqlite3VdbeAddParseSchemaOp(v, iDb,
  106574. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  106575. }
  106576. if( db->init.busy ){
  106577. Trigger *pLink = pTrig;
  106578. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  106579. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106580. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  106581. if( pTrig ){
  106582. db->mallocFailed = 1;
  106583. }else if( pLink->pSchema==pLink->pTabSchema ){
  106584. Table *pTab;
  106585. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  106586. assert( pTab!=0 );
  106587. pLink->pNext = pTab->pTrigger;
  106588. pTab->pTrigger = pLink;
  106589. }
  106590. }
  106591. triggerfinish_cleanup:
  106592. sqlite3DeleteTrigger(db, pTrig);
  106593. assert( !pParse->pNewTrigger );
  106594. sqlite3DeleteTriggerStep(db, pStepList);
  106595. }
  106596. /*
  106597. ** Turn a SELECT statement (that the pSelect parameter points to) into
  106598. ** a trigger step. Return a pointer to a TriggerStep structure.
  106599. **
  106600. ** The parser calls this routine when it finds a SELECT statement in
  106601. ** body of a TRIGGER.
  106602. */
  106603. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  106604. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  106605. if( pTriggerStep==0 ) {
  106606. sqlite3SelectDelete(db, pSelect);
  106607. return 0;
  106608. }
  106609. pTriggerStep->op = TK_SELECT;
  106610. pTriggerStep->pSelect = pSelect;
  106611. pTriggerStep->orconf = OE_Default;
  106612. return pTriggerStep;
  106613. }
  106614. /*
  106615. ** Allocate space to hold a new trigger step. The allocated space
  106616. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  106617. **
  106618. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  106619. */
  106620. static TriggerStep *triggerStepAllocate(
  106621. sqlite3 *db, /* Database connection */
  106622. u8 op, /* Trigger opcode */
  106623. Token *pName /* The target name */
  106624. ){
  106625. TriggerStep *pTriggerStep;
  106626. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
  106627. if( pTriggerStep ){
  106628. char *z = (char*)&pTriggerStep[1];
  106629. memcpy(z, pName->z, pName->n);
  106630. sqlite3Dequote(z);
  106631. pTriggerStep->zTarget = z;
  106632. pTriggerStep->op = op;
  106633. }
  106634. return pTriggerStep;
  106635. }
  106636. /*
  106637. ** Build a trigger step out of an INSERT statement. Return a pointer
  106638. ** to the new trigger step.
  106639. **
  106640. ** The parser calls this routine when it sees an INSERT inside the
  106641. ** body of a trigger.
  106642. */
  106643. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  106644. sqlite3 *db, /* The database connection */
  106645. Token *pTableName, /* Name of the table into which we insert */
  106646. IdList *pColumn, /* List of columns in pTableName to insert into */
  106647. Select *pSelect, /* A SELECT statement that supplies values */
  106648. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  106649. ){
  106650. TriggerStep *pTriggerStep;
  106651. assert(pSelect != 0 || db->mallocFailed);
  106652. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  106653. if( pTriggerStep ){
  106654. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  106655. pTriggerStep->pIdList = pColumn;
  106656. pTriggerStep->orconf = orconf;
  106657. }else{
  106658. sqlite3IdListDelete(db, pColumn);
  106659. }
  106660. sqlite3SelectDelete(db, pSelect);
  106661. return pTriggerStep;
  106662. }
  106663. /*
  106664. ** Construct a trigger step that implements an UPDATE statement and return
  106665. ** a pointer to that trigger step. The parser calls this routine when it
  106666. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  106667. */
  106668. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  106669. sqlite3 *db, /* The database connection */
  106670. Token *pTableName, /* Name of the table to be updated */
  106671. ExprList *pEList, /* The SET clause: list of column and new values */
  106672. Expr *pWhere, /* The WHERE clause */
  106673. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  106674. ){
  106675. TriggerStep *pTriggerStep;
  106676. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  106677. if( pTriggerStep ){
  106678. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  106679. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  106680. pTriggerStep->orconf = orconf;
  106681. }
  106682. sqlite3ExprListDelete(db, pEList);
  106683. sqlite3ExprDelete(db, pWhere);
  106684. return pTriggerStep;
  106685. }
  106686. /*
  106687. ** Construct a trigger step that implements a DELETE statement and return
  106688. ** a pointer to that trigger step. The parser calls this routine when it
  106689. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  106690. */
  106691. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  106692. sqlite3 *db, /* Database connection */
  106693. Token *pTableName, /* The table from which rows are deleted */
  106694. Expr *pWhere /* The WHERE clause */
  106695. ){
  106696. TriggerStep *pTriggerStep;
  106697. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  106698. if( pTriggerStep ){
  106699. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  106700. pTriggerStep->orconf = OE_Default;
  106701. }
  106702. sqlite3ExprDelete(db, pWhere);
  106703. return pTriggerStep;
  106704. }
  106705. /*
  106706. ** Recursively delete a Trigger structure
  106707. */
  106708. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  106709. if( pTrigger==0 ) return;
  106710. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  106711. sqlite3DbFree(db, pTrigger->zName);
  106712. sqlite3DbFree(db, pTrigger->table);
  106713. sqlite3ExprDelete(db, pTrigger->pWhen);
  106714. sqlite3IdListDelete(db, pTrigger->pColumns);
  106715. sqlite3DbFree(db, pTrigger);
  106716. }
  106717. /*
  106718. ** This function is called to drop a trigger from the database schema.
  106719. **
  106720. ** This may be called directly from the parser and therefore identifies
  106721. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  106722. ** same job as this routine except it takes a pointer to the trigger
  106723. ** instead of the trigger name.
  106724. **/
  106725. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  106726. Trigger *pTrigger = 0;
  106727. int i;
  106728. const char *zDb;
  106729. const char *zName;
  106730. sqlite3 *db = pParse->db;
  106731. if( db->mallocFailed ) goto drop_trigger_cleanup;
  106732. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  106733. goto drop_trigger_cleanup;
  106734. }
  106735. assert( pName->nSrc==1 );
  106736. zDb = pName->a[0].zDatabase;
  106737. zName = pName->a[0].zName;
  106738. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  106739. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  106740. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  106741. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  106742. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  106743. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  106744. if( pTrigger ) break;
  106745. }
  106746. if( !pTrigger ){
  106747. if( !noErr ){
  106748. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  106749. }else{
  106750. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  106751. }
  106752. pParse->checkSchema = 1;
  106753. goto drop_trigger_cleanup;
  106754. }
  106755. sqlite3DropTriggerPtr(pParse, pTrigger);
  106756. drop_trigger_cleanup:
  106757. sqlite3SrcListDelete(db, pName);
  106758. }
  106759. /*
  106760. ** Return a pointer to the Table structure for the table that a trigger
  106761. ** is set on.
  106762. */
  106763. static Table *tableOfTrigger(Trigger *pTrigger){
  106764. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  106765. }
  106766. /*
  106767. ** Drop a trigger given a pointer to that trigger.
  106768. */
  106769. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  106770. Table *pTable;
  106771. Vdbe *v;
  106772. sqlite3 *db = pParse->db;
  106773. int iDb;
  106774. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  106775. assert( iDb>=0 && iDb<db->nDb );
  106776. pTable = tableOfTrigger(pTrigger);
  106777. assert( pTable );
  106778. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  106779. #ifndef SQLITE_OMIT_AUTHORIZATION
  106780. {
  106781. int code = SQLITE_DROP_TRIGGER;
  106782. const char *zDb = db->aDb[iDb].zName;
  106783. const char *zTab = SCHEMA_TABLE(iDb);
  106784. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  106785. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  106786. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  106787. return;
  106788. }
  106789. }
  106790. #endif
  106791. /* Generate code to destroy the database record of the trigger.
  106792. */
  106793. assert( pTable!=0 );
  106794. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  106795. int base;
  106796. static const int iLn = VDBE_OFFSET_LINENO(2);
  106797. static const VdbeOpList dropTrigger[] = {
  106798. { OP_Rewind, 0, ADDR(9), 0},
  106799. { OP_String8, 0, 1, 0}, /* 1 */
  106800. { OP_Column, 0, 1, 2},
  106801. { OP_Ne, 2, ADDR(8), 1},
  106802. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  106803. { OP_Column, 0, 0, 2},
  106804. { OP_Ne, 2, ADDR(8), 1},
  106805. { OP_Delete, 0, 0, 0},
  106806. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  106807. };
  106808. sqlite3BeginWriteOperation(pParse, 0, iDb);
  106809. sqlite3OpenMasterTable(pParse, iDb);
  106810. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
  106811. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  106812. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  106813. sqlite3ChangeCookie(pParse, iDb);
  106814. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  106815. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  106816. if( pParse->nMem<3 ){
  106817. pParse->nMem = 3;
  106818. }
  106819. }
  106820. }
  106821. /*
  106822. ** Remove a trigger from the hash tables of the sqlite* pointer.
  106823. */
  106824. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  106825. Trigger *pTrigger;
  106826. Hash *pHash;
  106827. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  106828. pHash = &(db->aDb[iDb].pSchema->trigHash);
  106829. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  106830. if( ALWAYS(pTrigger) ){
  106831. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  106832. Table *pTab = tableOfTrigger(pTrigger);
  106833. Trigger **pp;
  106834. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  106835. *pp = (*pp)->pNext;
  106836. }
  106837. sqlite3DeleteTrigger(db, pTrigger);
  106838. db->flags |= SQLITE_InternChanges;
  106839. }
  106840. }
  106841. /*
  106842. ** pEList is the SET clause of an UPDATE statement. Each entry
  106843. ** in pEList is of the format <id>=<expr>. If any of the entries
  106844. ** in pEList have an <id> which matches an identifier in pIdList,
  106845. ** then return TRUE. If pIdList==NULL, then it is considered a
  106846. ** wildcard that matches anything. Likewise if pEList==NULL then
  106847. ** it matches anything so always return true. Return false only
  106848. ** if there is no match.
  106849. */
  106850. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  106851. int e;
  106852. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  106853. for(e=0; e<pEList->nExpr; e++){
  106854. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  106855. }
  106856. return 0;
  106857. }
  106858. /*
  106859. ** Return a list of all triggers on table pTab if there exists at least
  106860. ** one trigger that must be fired when an operation of type 'op' is
  106861. ** performed on the table, and, if that operation is an UPDATE, if at
  106862. ** least one of the columns in pChanges is being modified.
  106863. */
  106864. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  106865. Parse *pParse, /* Parse context */
  106866. Table *pTab, /* The table the contains the triggers */
  106867. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  106868. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  106869. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  106870. ){
  106871. int mask = 0;
  106872. Trigger *pList = 0;
  106873. Trigger *p;
  106874. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  106875. pList = sqlite3TriggerList(pParse, pTab);
  106876. }
  106877. assert( pList==0 || IsVirtual(pTab)==0 );
  106878. for(p=pList; p; p=p->pNext){
  106879. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  106880. mask |= p->tr_tm;
  106881. }
  106882. }
  106883. if( pMask ){
  106884. *pMask = mask;
  106885. }
  106886. return (mask ? pList : 0);
  106887. }
  106888. /*
  106889. ** Convert the pStep->zTarget string into a SrcList and return a pointer
  106890. ** to that SrcList.
  106891. **
  106892. ** This routine adds a specific database name, if needed, to the target when
  106893. ** forming the SrcList. This prevents a trigger in one database from
  106894. ** referring to a target in another database. An exception is when the
  106895. ** trigger is in TEMP in which case it can refer to any other database it
  106896. ** wants.
  106897. */
  106898. static SrcList *targetSrcList(
  106899. Parse *pParse, /* The parsing context */
  106900. TriggerStep *pStep /* The trigger containing the target token */
  106901. ){
  106902. sqlite3 *db = pParse->db;
  106903. int iDb; /* Index of the database to use */
  106904. SrcList *pSrc; /* SrcList to be returned */
  106905. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  106906. if( pSrc ){
  106907. assert( pSrc->nSrc>0 );
  106908. pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
  106909. iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
  106910. if( iDb==0 || iDb>=2 ){
  106911. assert( iDb<db->nDb );
  106912. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  106913. }
  106914. }
  106915. return pSrc;
  106916. }
  106917. /*
  106918. ** Generate VDBE code for the statements inside the body of a single
  106919. ** trigger.
  106920. */
  106921. static int codeTriggerProgram(
  106922. Parse *pParse, /* The parser context */
  106923. TriggerStep *pStepList, /* List of statements inside the trigger body */
  106924. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  106925. ){
  106926. TriggerStep *pStep;
  106927. Vdbe *v = pParse->pVdbe;
  106928. sqlite3 *db = pParse->db;
  106929. assert( pParse->pTriggerTab && pParse->pToplevel );
  106930. assert( pStepList );
  106931. assert( v!=0 );
  106932. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  106933. /* Figure out the ON CONFLICT policy that will be used for this step
  106934. ** of the trigger program. If the statement that caused this trigger
  106935. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  106936. ** the ON CONFLICT policy that was specified as part of the trigger
  106937. ** step statement. Example:
  106938. **
  106939. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  106940. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  106941. ** END;
  106942. **
  106943. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  106944. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  106945. */
  106946. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  106947. assert( pParse->okConstFactor==0 );
  106948. switch( pStep->op ){
  106949. case TK_UPDATE: {
  106950. sqlite3Update(pParse,
  106951. targetSrcList(pParse, pStep),
  106952. sqlite3ExprListDup(db, pStep->pExprList, 0),
  106953. sqlite3ExprDup(db, pStep->pWhere, 0),
  106954. pParse->eOrconf
  106955. );
  106956. break;
  106957. }
  106958. case TK_INSERT: {
  106959. sqlite3Insert(pParse,
  106960. targetSrcList(pParse, pStep),
  106961. sqlite3SelectDup(db, pStep->pSelect, 0),
  106962. sqlite3IdListDup(db, pStep->pIdList),
  106963. pParse->eOrconf
  106964. );
  106965. break;
  106966. }
  106967. case TK_DELETE: {
  106968. sqlite3DeleteFrom(pParse,
  106969. targetSrcList(pParse, pStep),
  106970. sqlite3ExprDup(db, pStep->pWhere, 0)
  106971. );
  106972. break;
  106973. }
  106974. default: assert( pStep->op==TK_SELECT ); {
  106975. SelectDest sDest;
  106976. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  106977. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  106978. sqlite3Select(pParse, pSelect, &sDest);
  106979. sqlite3SelectDelete(db, pSelect);
  106980. break;
  106981. }
  106982. }
  106983. if( pStep->op!=TK_SELECT ){
  106984. sqlite3VdbeAddOp0(v, OP_ResetCount);
  106985. }
  106986. }
  106987. return 0;
  106988. }
  106989. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  106990. /*
  106991. ** This function is used to add VdbeComment() annotations to a VDBE
  106992. ** program. It is not used in production code, only for debugging.
  106993. */
  106994. static const char *onErrorText(int onError){
  106995. switch( onError ){
  106996. case OE_Abort: return "abort";
  106997. case OE_Rollback: return "rollback";
  106998. case OE_Fail: return "fail";
  106999. case OE_Replace: return "replace";
  107000. case OE_Ignore: return "ignore";
  107001. case OE_Default: return "default";
  107002. }
  107003. return "n/a";
  107004. }
  107005. #endif
  107006. /*
  107007. ** Parse context structure pFrom has just been used to create a sub-vdbe
  107008. ** (trigger program). If an error has occurred, transfer error information
  107009. ** from pFrom to pTo.
  107010. */
  107011. static void transferParseError(Parse *pTo, Parse *pFrom){
  107012. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  107013. assert( pTo->zErrMsg==0 || pTo->nErr );
  107014. if( pTo->nErr==0 ){
  107015. pTo->zErrMsg = pFrom->zErrMsg;
  107016. pTo->nErr = pFrom->nErr;
  107017. pTo->rc = pFrom->rc;
  107018. }else{
  107019. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  107020. }
  107021. }
  107022. /*
  107023. ** Create and populate a new TriggerPrg object with a sub-program
  107024. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  107025. */
  107026. static TriggerPrg *codeRowTrigger(
  107027. Parse *pParse, /* Current parse context */
  107028. Trigger *pTrigger, /* Trigger to code */
  107029. Table *pTab, /* The table pTrigger is attached to */
  107030. int orconf /* ON CONFLICT policy to code trigger program with */
  107031. ){
  107032. Parse *pTop = sqlite3ParseToplevel(pParse);
  107033. sqlite3 *db = pParse->db; /* Database handle */
  107034. TriggerPrg *pPrg; /* Value to return */
  107035. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  107036. Vdbe *v; /* Temporary VM */
  107037. NameContext sNC; /* Name context for sub-vdbe */
  107038. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  107039. Parse *pSubParse; /* Parse context for sub-vdbe */
  107040. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  107041. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  107042. assert( pTop->pVdbe );
  107043. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  107044. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  107045. ** list of the top-level Parse object sooner rather than later. */
  107046. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  107047. if( !pPrg ) return 0;
  107048. pPrg->pNext = pTop->pTriggerPrg;
  107049. pTop->pTriggerPrg = pPrg;
  107050. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  107051. if( !pProgram ) return 0;
  107052. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  107053. pPrg->pTrigger = pTrigger;
  107054. pPrg->orconf = orconf;
  107055. pPrg->aColmask[0] = 0xffffffff;
  107056. pPrg->aColmask[1] = 0xffffffff;
  107057. /* Allocate and populate a new Parse context to use for coding the
  107058. ** trigger sub-program. */
  107059. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  107060. if( !pSubParse ) return 0;
  107061. memset(&sNC, 0, sizeof(sNC));
  107062. sNC.pParse = pSubParse;
  107063. pSubParse->db = db;
  107064. pSubParse->pTriggerTab = pTab;
  107065. pSubParse->pToplevel = pTop;
  107066. pSubParse->zAuthContext = pTrigger->zName;
  107067. pSubParse->eTriggerOp = pTrigger->op;
  107068. pSubParse->nQueryLoop = pParse->nQueryLoop;
  107069. v = sqlite3GetVdbe(pSubParse);
  107070. if( v ){
  107071. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  107072. pTrigger->zName, onErrorText(orconf),
  107073. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  107074. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  107075. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  107076. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  107077. pTab->zName
  107078. ));
  107079. #ifndef SQLITE_OMIT_TRACE
  107080. sqlite3VdbeChangeP4(v, -1,
  107081. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  107082. );
  107083. #endif
  107084. /* If one was specified, code the WHEN clause. If it evaluates to false
  107085. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  107086. ** OP_Halt inserted at the end of the program. */
  107087. if( pTrigger->pWhen ){
  107088. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  107089. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  107090. && db->mallocFailed==0
  107091. ){
  107092. iEndTrigger = sqlite3VdbeMakeLabel(v);
  107093. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  107094. }
  107095. sqlite3ExprDelete(db, pWhen);
  107096. }
  107097. /* Code the trigger program into the sub-vdbe. */
  107098. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  107099. /* Insert an OP_Halt at the end of the sub-program. */
  107100. if( iEndTrigger ){
  107101. sqlite3VdbeResolveLabel(v, iEndTrigger);
  107102. }
  107103. sqlite3VdbeAddOp0(v, OP_Halt);
  107104. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  107105. transferParseError(pParse, pSubParse);
  107106. if( db->mallocFailed==0 ){
  107107. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  107108. }
  107109. pProgram->nMem = pSubParse->nMem;
  107110. pProgram->nCsr = pSubParse->nTab;
  107111. pProgram->nOnce = pSubParse->nOnce;
  107112. pProgram->token = (void *)pTrigger;
  107113. pPrg->aColmask[0] = pSubParse->oldmask;
  107114. pPrg->aColmask[1] = pSubParse->newmask;
  107115. sqlite3VdbeDelete(v);
  107116. }
  107117. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  107118. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  107119. sqlite3ParserReset(pSubParse);
  107120. sqlite3StackFree(db, pSubParse);
  107121. return pPrg;
  107122. }
  107123. /*
  107124. ** Return a pointer to a TriggerPrg object containing the sub-program for
  107125. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  107126. ** TriggerPrg object exists, a new object is allocated and populated before
  107127. ** being returned.
  107128. */
  107129. static TriggerPrg *getRowTrigger(
  107130. Parse *pParse, /* Current parse context */
  107131. Trigger *pTrigger, /* Trigger to code */
  107132. Table *pTab, /* The table trigger pTrigger is attached to */
  107133. int orconf /* ON CONFLICT algorithm. */
  107134. ){
  107135. Parse *pRoot = sqlite3ParseToplevel(pParse);
  107136. TriggerPrg *pPrg;
  107137. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  107138. /* It may be that this trigger has already been coded (or is in the
  107139. ** process of being coded). If this is the case, then an entry with
  107140. ** a matching TriggerPrg.pTrigger field will be present somewhere
  107141. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  107142. for(pPrg=pRoot->pTriggerPrg;
  107143. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  107144. pPrg=pPrg->pNext
  107145. );
  107146. /* If an existing TriggerPrg could not be located, create a new one. */
  107147. if( !pPrg ){
  107148. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  107149. }
  107150. return pPrg;
  107151. }
  107152. /*
  107153. ** Generate code for the trigger program associated with trigger p on
  107154. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  107155. ** function are the same as those described in the header function for
  107156. ** sqlite3CodeRowTrigger()
  107157. */
  107158. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  107159. Parse *pParse, /* Parse context */
  107160. Trigger *p, /* Trigger to code */
  107161. Table *pTab, /* The table to code triggers from */
  107162. int reg, /* Reg array containing OLD.* and NEW.* values */
  107163. int orconf, /* ON CONFLICT policy */
  107164. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  107165. ){
  107166. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  107167. TriggerPrg *pPrg;
  107168. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  107169. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  107170. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  107171. ** is a pointer to the sub-vdbe containing the trigger program. */
  107172. if( pPrg ){
  107173. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  107174. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  107175. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  107176. VdbeComment(
  107177. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  107178. /* Set the P5 operand of the OP_Program instruction to non-zero if
  107179. ** recursive invocation of this trigger program is disallowed. Recursive
  107180. ** invocation is disallowed if (a) the sub-program is really a trigger,
  107181. ** not a foreign key action, and (b) the flag to enable recursive triggers
  107182. ** is clear. */
  107183. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  107184. }
  107185. }
  107186. /*
  107187. ** This is called to code the required FOR EACH ROW triggers for an operation
  107188. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  107189. ** is given by the op parameter. The tr_tm parameter determines whether the
  107190. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  107191. ** parameter pChanges is passed the list of columns being modified.
  107192. **
  107193. ** If there are no triggers that fire at the specified time for the specified
  107194. ** operation on pTab, this function is a no-op.
  107195. **
  107196. ** The reg argument is the address of the first in an array of registers
  107197. ** that contain the values substituted for the new.* and old.* references
  107198. ** in the trigger program. If N is the number of columns in table pTab
  107199. ** (a copy of pTab->nCol), then registers are populated as follows:
  107200. **
  107201. ** Register Contains
  107202. ** ------------------------------------------------------
  107203. ** reg+0 OLD.rowid
  107204. ** reg+1 OLD.* value of left-most column of pTab
  107205. ** ... ...
  107206. ** reg+N OLD.* value of right-most column of pTab
  107207. ** reg+N+1 NEW.rowid
  107208. ** reg+N+2 OLD.* value of left-most column of pTab
  107209. ** ... ...
  107210. ** reg+N+N+1 NEW.* value of right-most column of pTab
  107211. **
  107212. ** For ON DELETE triggers, the registers containing the NEW.* values will
  107213. ** never be accessed by the trigger program, so they are not allocated or
  107214. ** populated by the caller (there is no data to populate them with anyway).
  107215. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  107216. ** are never accessed, and so are not allocated by the caller. So, for an
  107217. ** ON INSERT trigger, the value passed to this function as parameter reg
  107218. ** is not a readable register, although registers (reg+N) through
  107219. ** (reg+N+N+1) are.
  107220. **
  107221. ** Parameter orconf is the default conflict resolution algorithm for the
  107222. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  107223. ** is the instruction that control should jump to if a trigger program
  107224. ** raises an IGNORE exception.
  107225. */
  107226. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  107227. Parse *pParse, /* Parse context */
  107228. Trigger *pTrigger, /* List of triggers on table pTab */
  107229. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  107230. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  107231. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  107232. Table *pTab, /* The table to code triggers from */
  107233. int reg, /* The first in an array of registers (see above) */
  107234. int orconf, /* ON CONFLICT policy */
  107235. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  107236. ){
  107237. Trigger *p; /* Used to iterate through pTrigger list */
  107238. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  107239. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  107240. assert( (op==TK_UPDATE)==(pChanges!=0) );
  107241. for(p=pTrigger; p; p=p->pNext){
  107242. /* Sanity checking: The schema for the trigger and for the table are
  107243. ** always defined. The trigger must be in the same schema as the table
  107244. ** or else it must be a TEMP trigger. */
  107245. assert( p->pSchema!=0 );
  107246. assert( p->pTabSchema!=0 );
  107247. assert( p->pSchema==p->pTabSchema
  107248. || p->pSchema==pParse->db->aDb[1].pSchema );
  107249. /* Determine whether we should code this trigger */
  107250. if( p->op==op
  107251. && p->tr_tm==tr_tm
  107252. && checkColumnOverlap(p->pColumns, pChanges)
  107253. ){
  107254. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  107255. }
  107256. }
  107257. }
  107258. /*
  107259. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  107260. ** This function returns a 32-bit bitmask indicating which columns of the
  107261. ** old.* or new.* tables actually are used by triggers. This information
  107262. ** may be used by the caller, for example, to avoid having to load the entire
  107263. ** old.* record into memory when executing an UPDATE or DELETE command.
  107264. **
  107265. ** Bit 0 of the returned mask is set if the left-most column of the
  107266. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  107267. ** the second leftmost column value is required, and so on. If there
  107268. ** are more than 32 columns in the table, and at least one of the columns
  107269. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  107270. **
  107271. ** It is not possible to determine if the old.rowid or new.rowid column is
  107272. ** accessed by triggers. The caller must always assume that it is.
  107273. **
  107274. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  107275. ** applies to the old.* table. If 1, the new.* table.
  107276. **
  107277. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  107278. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  107279. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  107280. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  107281. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  107282. */
  107283. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  107284. Parse *pParse, /* Parse context */
  107285. Trigger *pTrigger, /* List of triggers on table pTab */
  107286. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  107287. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  107288. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  107289. Table *pTab, /* The table to code triggers from */
  107290. int orconf /* Default ON CONFLICT policy for trigger steps */
  107291. ){
  107292. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  107293. u32 mask = 0;
  107294. Trigger *p;
  107295. assert( isNew==1 || isNew==0 );
  107296. for(p=pTrigger; p; p=p->pNext){
  107297. if( p->op==op && (tr_tm&p->tr_tm)
  107298. && checkColumnOverlap(p->pColumns,pChanges)
  107299. ){
  107300. TriggerPrg *pPrg;
  107301. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  107302. if( pPrg ){
  107303. mask |= pPrg->aColmask[isNew];
  107304. }
  107305. }
  107306. }
  107307. return mask;
  107308. }
  107309. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  107310. /************** End of trigger.c *********************************************/
  107311. /************** Begin file update.c ******************************************/
  107312. /*
  107313. ** 2001 September 15
  107314. **
  107315. ** The author disclaims copyright to this source code. In place of
  107316. ** a legal notice, here is a blessing:
  107317. **
  107318. ** May you do good and not evil.
  107319. ** May you find forgiveness for yourself and forgive others.
  107320. ** May you share freely, never taking more than you give.
  107321. **
  107322. *************************************************************************
  107323. ** This file contains C code routines that are called by the parser
  107324. ** to handle UPDATE statements.
  107325. */
  107326. /* #include "sqliteInt.h" */
  107327. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107328. /* Forward declaration */
  107329. static void updateVirtualTable(
  107330. Parse *pParse, /* The parsing context */
  107331. SrcList *pSrc, /* The virtual table to be modified */
  107332. Table *pTab, /* The virtual table */
  107333. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  107334. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  107335. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  107336. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  107337. int onError /* ON CONFLICT strategy */
  107338. );
  107339. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  107340. /*
  107341. ** The most recently coded instruction was an OP_Column to retrieve the
  107342. ** i-th column of table pTab. This routine sets the P4 parameter of the
  107343. ** OP_Column to the default value, if any.
  107344. **
  107345. ** The default value of a column is specified by a DEFAULT clause in the
  107346. ** column definition. This was either supplied by the user when the table
  107347. ** was created, or added later to the table definition by an ALTER TABLE
  107348. ** command. If the latter, then the row-records in the table btree on disk
  107349. ** may not contain a value for the column and the default value, taken
  107350. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  107351. ** If the former, then all row-records are guaranteed to include a value
  107352. ** for the column and the P4 value is not required.
  107353. **
  107354. ** Column definitions created by an ALTER TABLE command may only have
  107355. ** literal default values specified: a number, null or a string. (If a more
  107356. ** complicated default expression value was provided, it is evaluated
  107357. ** when the ALTER TABLE is executed and one of the literal values written
  107358. ** into the sqlite_master table.)
  107359. **
  107360. ** Therefore, the P4 parameter is only required if the default value for
  107361. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  107362. ** function is capable of transforming these types of expressions into
  107363. ** sqlite3_value objects.
  107364. **
  107365. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  107366. ** on register iReg. This is used when an equivalent integer value is
  107367. ** stored in place of an 8-byte floating point value in order to save
  107368. ** space.
  107369. */
  107370. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  107371. assert( pTab!=0 );
  107372. if( !pTab->pSelect ){
  107373. sqlite3_value *pValue = 0;
  107374. u8 enc = ENC(sqlite3VdbeDb(v));
  107375. Column *pCol = &pTab->aCol[i];
  107376. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  107377. assert( i<pTab->nCol );
  107378. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  107379. pCol->affinity, &pValue);
  107380. if( pValue ){
  107381. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  107382. }
  107383. #ifndef SQLITE_OMIT_FLOATING_POINT
  107384. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  107385. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  107386. }
  107387. #endif
  107388. }
  107389. }
  107390. /*
  107391. ** Process an UPDATE statement.
  107392. **
  107393. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  107394. ** \_______/ \________/ \______/ \________________/
  107395. * onError pTabList pChanges pWhere
  107396. */
  107397. SQLITE_PRIVATE void sqlite3Update(
  107398. Parse *pParse, /* The parser context */
  107399. SrcList *pTabList, /* The table in which we should change things */
  107400. ExprList *pChanges, /* Things to be changed */
  107401. Expr *pWhere, /* The WHERE clause. May be null */
  107402. int onError /* How to handle constraint errors */
  107403. ){
  107404. int i, j; /* Loop counters */
  107405. Table *pTab; /* The table to be updated */
  107406. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  107407. WhereInfo *pWInfo; /* Information about the WHERE clause */
  107408. Vdbe *v; /* The virtual database engine */
  107409. Index *pIdx; /* For looping over indices */
  107410. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  107411. int nIdx; /* Number of indices that need updating */
  107412. int iBaseCur; /* Base cursor number */
  107413. int iDataCur; /* Cursor for the canonical data btree */
  107414. int iIdxCur; /* Cursor for the first index */
  107415. sqlite3 *db; /* The database structure */
  107416. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  107417. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  107418. ** an expression for the i-th column of the table.
  107419. ** aXRef[i]==-1 if the i-th column is not changed. */
  107420. u8 *aToOpen; /* 1 for tables and indices to be opened */
  107421. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  107422. u8 chngRowid; /* Rowid changed in a normal table */
  107423. u8 chngKey; /* Either chngPk or chngRowid */
  107424. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  107425. AuthContext sContext; /* The authorization context */
  107426. NameContext sNC; /* The name-context to resolve expressions in */
  107427. int iDb; /* Database containing the table being updated */
  107428. int okOnePass; /* True for one-pass algorithm without the FIFO */
  107429. int hasFK; /* True if foreign key processing is required */
  107430. int labelBreak; /* Jump here to break out of UPDATE loop */
  107431. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  107432. #ifndef SQLITE_OMIT_TRIGGER
  107433. int isView; /* True when updating a view (INSTEAD OF trigger) */
  107434. Trigger *pTrigger; /* List of triggers on pTab, if required */
  107435. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  107436. #endif
  107437. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  107438. int iEph = 0; /* Ephemeral table holding all primary key values */
  107439. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  107440. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  107441. /* Register Allocations */
  107442. int regRowCount = 0; /* A count of rows changed */
  107443. int regOldRowid; /* The old rowid */
  107444. int regNewRowid; /* The new rowid */
  107445. int regNew; /* Content of the NEW.* table in triggers */
  107446. int regOld = 0; /* Content of OLD.* table in triggers */
  107447. int regRowSet = 0; /* Rowset of rows to be updated */
  107448. int regKey = 0; /* composite PRIMARY KEY value */
  107449. memset(&sContext, 0, sizeof(sContext));
  107450. db = pParse->db;
  107451. if( pParse->nErr || db->mallocFailed ){
  107452. goto update_cleanup;
  107453. }
  107454. assert( pTabList->nSrc==1 );
  107455. /* Locate the table which we want to update.
  107456. */
  107457. pTab = sqlite3SrcListLookup(pParse, pTabList);
  107458. if( pTab==0 ) goto update_cleanup;
  107459. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  107460. /* Figure out if we have any triggers and if the table being
  107461. ** updated is a view.
  107462. */
  107463. #ifndef SQLITE_OMIT_TRIGGER
  107464. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  107465. isView = pTab->pSelect!=0;
  107466. assert( pTrigger || tmask==0 );
  107467. #else
  107468. # define pTrigger 0
  107469. # define isView 0
  107470. # define tmask 0
  107471. #endif
  107472. #ifdef SQLITE_OMIT_VIEW
  107473. # undef isView
  107474. # define isView 0
  107475. #endif
  107476. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  107477. goto update_cleanup;
  107478. }
  107479. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  107480. goto update_cleanup;
  107481. }
  107482. /* Allocate a cursors for the main database table and for all indices.
  107483. ** The index cursors might not be used, but if they are used they
  107484. ** need to occur right after the database cursor. So go ahead and
  107485. ** allocate enough space, just in case.
  107486. */
  107487. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  107488. iIdxCur = iDataCur+1;
  107489. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  107490. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  107491. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  107492. iDataCur = pParse->nTab;
  107493. pTabList->a[0].iCursor = iDataCur;
  107494. }
  107495. pParse->nTab++;
  107496. }
  107497. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  107498. ** Initialize aXRef[] and aToOpen[] to their default values.
  107499. */
  107500. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  107501. if( aXRef==0 ) goto update_cleanup;
  107502. aRegIdx = aXRef+pTab->nCol;
  107503. aToOpen = (u8*)(aRegIdx+nIdx);
  107504. memset(aToOpen, 1, nIdx+1);
  107505. aToOpen[nIdx+1] = 0;
  107506. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  107507. /* Initialize the name-context */
  107508. memset(&sNC, 0, sizeof(sNC));
  107509. sNC.pParse = pParse;
  107510. sNC.pSrcList = pTabList;
  107511. /* Resolve the column names in all the expressions of the
  107512. ** of the UPDATE statement. Also find the column index
  107513. ** for each column to be updated in the pChanges array. For each
  107514. ** column to be updated, make sure we have authorization to change
  107515. ** that column.
  107516. */
  107517. chngRowid = chngPk = 0;
  107518. for(i=0; i<pChanges->nExpr; i++){
  107519. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  107520. goto update_cleanup;
  107521. }
  107522. for(j=0; j<pTab->nCol; j++){
  107523. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  107524. if( j==pTab->iPKey ){
  107525. chngRowid = 1;
  107526. pRowidExpr = pChanges->a[i].pExpr;
  107527. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  107528. chngPk = 1;
  107529. }
  107530. aXRef[j] = i;
  107531. break;
  107532. }
  107533. }
  107534. if( j>=pTab->nCol ){
  107535. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  107536. j = -1;
  107537. chngRowid = 1;
  107538. pRowidExpr = pChanges->a[i].pExpr;
  107539. }else{
  107540. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  107541. pParse->checkSchema = 1;
  107542. goto update_cleanup;
  107543. }
  107544. }
  107545. #ifndef SQLITE_OMIT_AUTHORIZATION
  107546. {
  107547. int rc;
  107548. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  107549. j<0 ? "ROWID" : pTab->aCol[j].zName,
  107550. db->aDb[iDb].zName);
  107551. if( rc==SQLITE_DENY ){
  107552. goto update_cleanup;
  107553. }else if( rc==SQLITE_IGNORE ){
  107554. aXRef[j] = -1;
  107555. }
  107556. }
  107557. #endif
  107558. }
  107559. assert( (chngRowid & chngPk)==0 );
  107560. assert( chngRowid==0 || chngRowid==1 );
  107561. assert( chngPk==0 || chngPk==1 );
  107562. chngKey = chngRowid + chngPk;
  107563. /* The SET expressions are not actually used inside the WHERE loop.
  107564. ** So reset the colUsed mask
  107565. */
  107566. pTabList->a[0].colUsed = 0;
  107567. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  107568. /* There is one entry in the aRegIdx[] array for each index on the table
  107569. ** being updated. Fill in aRegIdx[] with a register number that will hold
  107570. ** the key for accessing each index.
  107571. */
  107572. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  107573. int reg;
  107574. if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
  107575. reg = ++pParse->nMem;
  107576. }else{
  107577. reg = 0;
  107578. for(i=0; i<pIdx->nKeyCol; i++){
  107579. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  107580. reg = ++pParse->nMem;
  107581. break;
  107582. }
  107583. }
  107584. }
  107585. if( reg==0 ) aToOpen[j+1] = 0;
  107586. aRegIdx[j] = reg;
  107587. }
  107588. /* Begin generating code. */
  107589. v = sqlite3GetVdbe(pParse);
  107590. if( v==0 ) goto update_cleanup;
  107591. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  107592. sqlite3BeginWriteOperation(pParse, 1, iDb);
  107593. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107594. /* Virtual tables must be handled separately */
  107595. if( IsVirtual(pTab) ){
  107596. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  107597. pWhere, onError);
  107598. pWhere = 0;
  107599. pTabList = 0;
  107600. goto update_cleanup;
  107601. }
  107602. #endif
  107603. /* Allocate required registers. */
  107604. regRowSet = ++pParse->nMem;
  107605. regOldRowid = regNewRowid = ++pParse->nMem;
  107606. if( chngPk || pTrigger || hasFK ){
  107607. regOld = pParse->nMem + 1;
  107608. pParse->nMem += pTab->nCol;
  107609. }
  107610. if( chngKey || pTrigger || hasFK ){
  107611. regNewRowid = ++pParse->nMem;
  107612. }
  107613. regNew = pParse->nMem + 1;
  107614. pParse->nMem += pTab->nCol;
  107615. /* Start the view context. */
  107616. if( isView ){
  107617. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  107618. }
  107619. /* If we are trying to update a view, realize that view into
  107620. ** an ephemeral table.
  107621. */
  107622. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  107623. if( isView ){
  107624. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  107625. }
  107626. #endif
  107627. /* Resolve the column names in all the expressions in the
  107628. ** WHERE clause.
  107629. */
  107630. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  107631. goto update_cleanup;
  107632. }
  107633. /* Begin the database scan
  107634. */
  107635. if( HasRowid(pTab) ){
  107636. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  107637. pWInfo = sqlite3WhereBegin(
  107638. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
  107639. );
  107640. if( pWInfo==0 ) goto update_cleanup;
  107641. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  107642. /* Remember the rowid of every item to be updated.
  107643. */
  107644. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  107645. if( !okOnePass ){
  107646. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  107647. }
  107648. /* End the database scan loop.
  107649. */
  107650. sqlite3WhereEnd(pWInfo);
  107651. }else{
  107652. int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
  107653. i16 nPk; /* Number of components of the PRIMARY KEY */
  107654. int addrOpen; /* Address of the OpenEphemeral instruction */
  107655. assert( pPk!=0 );
  107656. nPk = pPk->nKeyCol;
  107657. iPk = pParse->nMem+1;
  107658. pParse->nMem += nPk;
  107659. regKey = ++pParse->nMem;
  107660. iEph = pParse->nTab++;
  107661. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  107662. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  107663. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  107664. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  107665. WHERE_ONEPASS_DESIRED, iIdxCur);
  107666. if( pWInfo==0 ) goto update_cleanup;
  107667. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  107668. for(i=0; i<nPk; i++){
  107669. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
  107670. iPk+i);
  107671. }
  107672. if( okOnePass ){
  107673. sqlite3VdbeChangeToNoop(v, addrOpen);
  107674. nKey = nPk;
  107675. regKey = iPk;
  107676. }else{
  107677. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  107678. sqlite3IndexAffinityStr(v, pPk), nPk);
  107679. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
  107680. }
  107681. sqlite3WhereEnd(pWInfo);
  107682. }
  107683. /* Initialize the count of updated rows
  107684. */
  107685. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  107686. regRowCount = ++pParse->nMem;
  107687. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  107688. }
  107689. labelBreak = sqlite3VdbeMakeLabel(v);
  107690. if( !isView ){
  107691. /*
  107692. ** Open every index that needs updating. Note that if any
  107693. ** index could potentially invoke a REPLACE conflict resolution
  107694. ** action, then we need to open all indices because we might need
  107695. ** to be deleting some records.
  107696. */
  107697. if( onError==OE_Replace ){
  107698. memset(aToOpen, 1, nIdx+1);
  107699. }else{
  107700. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107701. if( pIdx->onError==OE_Replace ){
  107702. memset(aToOpen, 1, nIdx+1);
  107703. break;
  107704. }
  107705. }
  107706. }
  107707. if( okOnePass ){
  107708. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  107709. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  107710. }
  107711. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
  107712. 0, 0);
  107713. }
  107714. /* Top of the update loop */
  107715. if( okOnePass ){
  107716. if( aToOpen[iDataCur-iBaseCur] && !isView ){
  107717. assert( pPk );
  107718. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  107719. VdbeCoverageNeverTaken(v);
  107720. }
  107721. labelContinue = labelBreak;
  107722. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  107723. VdbeCoverageIf(v, pPk==0);
  107724. VdbeCoverageIf(v, pPk!=0);
  107725. }else if( pPk ){
  107726. labelContinue = sqlite3VdbeMakeLabel(v);
  107727. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  107728. addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
  107729. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  107730. VdbeCoverage(v);
  107731. }else{
  107732. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  107733. regOldRowid);
  107734. VdbeCoverage(v);
  107735. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  107736. VdbeCoverage(v);
  107737. }
  107738. /* If the record number will change, set register regNewRowid to
  107739. ** contain the new value. If the record number is not being modified,
  107740. ** then regNewRowid is the same register as regOldRowid, which is
  107741. ** already populated. */
  107742. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  107743. if( chngRowid ){
  107744. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  107745. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  107746. }
  107747. /* Compute the old pre-UPDATE content of the row being changed, if that
  107748. ** information is needed */
  107749. if( chngPk || hasFK || pTrigger ){
  107750. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  107751. oldmask |= sqlite3TriggerColmask(pParse,
  107752. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  107753. );
  107754. for(i=0; i<pTab->nCol; i++){
  107755. if( oldmask==0xffffffff
  107756. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  107757. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  107758. ){
  107759. testcase( oldmask!=0xffffffff && i==31 );
  107760. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  107761. }else{
  107762. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  107763. }
  107764. }
  107765. if( chngRowid==0 && pPk==0 ){
  107766. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  107767. }
  107768. }
  107769. /* Populate the array of registers beginning at regNew with the new
  107770. ** row data. This array is used to check constants, create the new
  107771. ** table and index records, and as the values for any new.* references
  107772. ** made by triggers.
  107773. **
  107774. ** If there are one or more BEFORE triggers, then do not populate the
  107775. ** registers associated with columns that are (a) not modified by
  107776. ** this UPDATE statement and (b) not accessed by new.* references. The
  107777. ** values for registers not modified by the UPDATE must be reloaded from
  107778. ** the database after the BEFORE triggers are fired anyway (as the trigger
  107779. ** may have modified them). So not loading those that are not going to
  107780. ** be used eliminates some redundant opcodes.
  107781. */
  107782. newmask = sqlite3TriggerColmask(
  107783. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  107784. );
  107785. /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
  107786. for(i=0; i<pTab->nCol; i++){
  107787. if( i==pTab->iPKey ){
  107788. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  107789. }else{
  107790. j = aXRef[i];
  107791. if( j>=0 ){
  107792. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  107793. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  107794. /* This branch loads the value of a column that will not be changed
  107795. ** into a register. This is done if there are no BEFORE triggers, or
  107796. ** if there are one or more BEFORE triggers that use this value via
  107797. ** a new.* reference in a trigger program.
  107798. */
  107799. testcase( i==31 );
  107800. testcase( i==32 );
  107801. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  107802. }else{
  107803. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  107804. }
  107805. }
  107806. }
  107807. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  107808. ** verified. One could argue that this is wrong.
  107809. */
  107810. if( tmask&TRIGGER_BEFORE ){
  107811. sqlite3TableAffinity(v, pTab, regNew);
  107812. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  107813. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  107814. /* The row-trigger may have deleted the row being updated. In this
  107815. ** case, jump to the next row. No updates or AFTER triggers are
  107816. ** required. This behavior - what happens when the row being updated
  107817. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  107818. ** documentation.
  107819. */
  107820. if( pPk ){
  107821. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  107822. VdbeCoverage(v);
  107823. }else{
  107824. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  107825. VdbeCoverage(v);
  107826. }
  107827. /* If it did not delete it, the row-trigger may still have modified
  107828. ** some of the columns of the row being updated. Load the values for
  107829. ** all columns not modified by the update statement into their
  107830. ** registers in case this has happened.
  107831. */
  107832. for(i=0; i<pTab->nCol; i++){
  107833. if( aXRef[i]<0 && i!=pTab->iPKey ){
  107834. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  107835. }
  107836. }
  107837. }
  107838. if( !isView ){
  107839. int j1 = 0; /* Address of jump instruction */
  107840. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  107841. /* Do constraint checks. */
  107842. assert( regOldRowid>0 );
  107843. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  107844. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
  107845. /* Do FK constraint checks. */
  107846. if( hasFK ){
  107847. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  107848. }
  107849. /* Delete the index entries associated with the current record. */
  107850. if( bReplace || chngKey ){
  107851. if( pPk ){
  107852. j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  107853. }else{
  107854. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  107855. }
  107856. VdbeCoverageNeverTaken(v);
  107857. }
  107858. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
  107859. /* If changing the record number, delete the old record. */
  107860. if( hasFK || chngKey || pPk!=0 ){
  107861. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  107862. }
  107863. if( bReplace || chngKey ){
  107864. sqlite3VdbeJumpHere(v, j1);
  107865. }
  107866. if( hasFK ){
  107867. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  107868. }
  107869. /* Insert the new index entries and the new record. */
  107870. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  107871. regNewRowid, aRegIdx, 1, 0, 0);
  107872. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  107873. ** handle rows (possibly in other tables) that refer via a foreign key
  107874. ** to the row just updated. */
  107875. if( hasFK ){
  107876. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  107877. }
  107878. }
  107879. /* Increment the row counter
  107880. */
  107881. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  107882. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  107883. }
  107884. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  107885. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  107886. /* Repeat the above with the next record to be updated, until
  107887. ** all record selected by the WHERE clause have been updated.
  107888. */
  107889. if( okOnePass ){
  107890. /* Nothing to do at end-of-loop for a single-pass */
  107891. }else if( pPk ){
  107892. sqlite3VdbeResolveLabel(v, labelContinue);
  107893. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  107894. }else{
  107895. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
  107896. }
  107897. sqlite3VdbeResolveLabel(v, labelBreak);
  107898. /* Close all tables */
  107899. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  107900. assert( aRegIdx );
  107901. if( aToOpen[i+1] ){
  107902. sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
  107903. }
  107904. }
  107905. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
  107906. /* Update the sqlite_sequence table by storing the content of the
  107907. ** maximum rowid counter values recorded while inserting into
  107908. ** autoincrement tables.
  107909. */
  107910. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  107911. sqlite3AutoincrementEnd(pParse);
  107912. }
  107913. /*
  107914. ** Return the number of rows that were changed. If this routine is
  107915. ** generating code because of a call to sqlite3NestedParse(), do not
  107916. ** invoke the callback function.
  107917. */
  107918. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  107919. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  107920. sqlite3VdbeSetNumCols(v, 1);
  107921. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  107922. }
  107923. update_cleanup:
  107924. sqlite3AuthContextPop(&sContext);
  107925. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  107926. sqlite3SrcListDelete(db, pTabList);
  107927. sqlite3ExprListDelete(db, pChanges);
  107928. sqlite3ExprDelete(db, pWhere);
  107929. return;
  107930. }
  107931. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  107932. ** they may interfere with compilation of other functions in this file
  107933. ** (or in another file, if this file becomes part of the amalgamation). */
  107934. #ifdef isView
  107935. #undef isView
  107936. #endif
  107937. #ifdef pTrigger
  107938. #undef pTrigger
  107939. #endif
  107940. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107941. /*
  107942. ** Generate code for an UPDATE of a virtual table.
  107943. **
  107944. ** The strategy is that we create an ephemeral table that contains
  107945. ** for each row to be changed:
  107946. **
  107947. ** (A) The original rowid of that row.
  107948. ** (B) The revised rowid for the row. (note1)
  107949. ** (C) The content of every column in the row.
  107950. **
  107951. ** Then we loop over this ephemeral table and for each row in
  107952. ** the ephemeral table call VUpdate.
  107953. **
  107954. ** When finished, drop the ephemeral table.
  107955. **
  107956. ** (note1) Actually, if we know in advance that (A) is always the same
  107957. ** as (B) we only store (A), then duplicate (A) when pulling
  107958. ** it out of the ephemeral table before calling VUpdate.
  107959. */
  107960. static void updateVirtualTable(
  107961. Parse *pParse, /* The parsing context */
  107962. SrcList *pSrc, /* The virtual table to be modified */
  107963. Table *pTab, /* The virtual table */
  107964. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  107965. Expr *pRowid, /* Expression used to recompute the rowid */
  107966. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  107967. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  107968. int onError /* ON CONFLICT strategy */
  107969. ){
  107970. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  107971. ExprList *pEList = 0; /* The result set of the SELECT statement */
  107972. Select *pSelect = 0; /* The SELECT statement */
  107973. Expr *pExpr; /* Temporary expression */
  107974. int ephemTab; /* Table holding the result of the SELECT */
  107975. int i; /* Loop counter */
  107976. int addr; /* Address of top of loop */
  107977. int iReg; /* First register in set passed to OP_VUpdate */
  107978. sqlite3 *db = pParse->db; /* Database connection */
  107979. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  107980. SelectDest dest;
  107981. /* Construct the SELECT statement that will find the new values for
  107982. ** all updated rows.
  107983. */
  107984. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  107985. if( pRowid ){
  107986. pEList = sqlite3ExprListAppend(pParse, pEList,
  107987. sqlite3ExprDup(db, pRowid, 0));
  107988. }
  107989. assert( pTab->iPKey<0 );
  107990. for(i=0; i<pTab->nCol; i++){
  107991. if( aXRef[i]>=0 ){
  107992. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  107993. }else{
  107994. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  107995. }
  107996. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  107997. }
  107998. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  107999. /* Create the ephemeral table into which the update results will
  108000. ** be stored.
  108001. */
  108002. assert( v );
  108003. ephemTab = pParse->nTab++;
  108004. /* fill the ephemeral table
  108005. */
  108006. sqlite3SelectDestInit(&dest, SRT_EphemTab, ephemTab);
  108007. sqlite3Select(pParse, pSelect, &dest);
  108008. /* Generate code to scan the ephemeral table and call VUpdate. */
  108009. iReg = ++pParse->nMem;
  108010. pParse->nMem += pTab->nCol+1;
  108011. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
  108012. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  108013. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  108014. for(i=0; i<pTab->nCol; i++){
  108015. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  108016. }
  108017. sqlite3VtabMakeWritable(pParse, pTab);
  108018. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  108019. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  108020. sqlite3MayAbort(pParse);
  108021. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  108022. sqlite3VdbeJumpHere(v, addr);
  108023. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  108024. /* Cleanup */
  108025. sqlite3SelectDelete(db, pSelect);
  108026. }
  108027. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  108028. /************** End of update.c **********************************************/
  108029. /************** Begin file vacuum.c ******************************************/
  108030. /*
  108031. ** 2003 April 6
  108032. **
  108033. ** The author disclaims copyright to this source code. In place of
  108034. ** a legal notice, here is a blessing:
  108035. **
  108036. ** May you do good and not evil.
  108037. ** May you find forgiveness for yourself and forgive others.
  108038. ** May you share freely, never taking more than you give.
  108039. **
  108040. *************************************************************************
  108041. ** This file contains code used to implement the VACUUM command.
  108042. **
  108043. ** Most of the code in this file may be omitted by defining the
  108044. ** SQLITE_OMIT_VACUUM macro.
  108045. */
  108046. /* #include "sqliteInt.h" */
  108047. /* #include "vdbeInt.h" */
  108048. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  108049. /*
  108050. ** Finalize a prepared statement. If there was an error, store the
  108051. ** text of the error message in *pzErrMsg. Return the result code.
  108052. */
  108053. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  108054. int rc;
  108055. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  108056. if( rc ){
  108057. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  108058. }
  108059. return rc;
  108060. }
  108061. /*
  108062. ** Execute zSql on database db. Return an error code.
  108063. */
  108064. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  108065. sqlite3_stmt *pStmt;
  108066. VVA_ONLY( int rc; )
  108067. if( !zSql ){
  108068. return SQLITE_NOMEM;
  108069. }
  108070. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  108071. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  108072. return sqlite3_errcode(db);
  108073. }
  108074. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  108075. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  108076. return vacuumFinalize(db, pStmt, pzErrMsg);
  108077. }
  108078. /*
  108079. ** Execute zSql on database db. The statement returns exactly
  108080. ** one column. Execute this as SQL on the same database.
  108081. */
  108082. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  108083. sqlite3_stmt *pStmt;
  108084. int rc;
  108085. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  108086. if( rc!=SQLITE_OK ) return rc;
  108087. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  108088. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  108089. if( rc!=SQLITE_OK ){
  108090. vacuumFinalize(db, pStmt, pzErrMsg);
  108091. return rc;
  108092. }
  108093. }
  108094. return vacuumFinalize(db, pStmt, pzErrMsg);
  108095. }
  108096. /*
  108097. ** The VACUUM command is used to clean up the database,
  108098. ** collapse free space, etc. It is modelled after the VACUUM command
  108099. ** in PostgreSQL. The VACUUM command works as follows:
  108100. **
  108101. ** (1) Create a new transient database file
  108102. ** (2) Copy all content from the database being vacuumed into
  108103. ** the new transient database file
  108104. ** (3) Copy content from the transient database back into the
  108105. ** original database.
  108106. **
  108107. ** The transient database requires temporary disk space approximately
  108108. ** equal to the size of the original database. The copy operation of
  108109. ** step (3) requires additional temporary disk space approximately equal
  108110. ** to the size of the original database for the rollback journal.
  108111. ** Hence, temporary disk space that is approximately 2x the size of the
  108112. ** original database is required. Every page of the database is written
  108113. ** approximately 3 times: Once for step (2) and twice for step (3).
  108114. ** Two writes per page are required in step (3) because the original
  108115. ** database content must be written into the rollback journal prior to
  108116. ** overwriting the database with the vacuumed content.
  108117. **
  108118. ** Only 1x temporary space and only 1x writes would be required if
  108119. ** the copy of step (3) were replaced by deleting the original database
  108120. ** and renaming the transient database as the original. But that will
  108121. ** not work if other processes are attached to the original database.
  108122. ** And a power loss in between deleting the original and renaming the
  108123. ** transient would cause the database file to appear to be deleted
  108124. ** following reboot.
  108125. */
  108126. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  108127. Vdbe *v = sqlite3GetVdbe(pParse);
  108128. if( v ){
  108129. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  108130. sqlite3VdbeUsesBtree(v, 0);
  108131. }
  108132. return;
  108133. }
  108134. /*
  108135. ** This routine implements the OP_Vacuum opcode of the VDBE.
  108136. */
  108137. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  108138. int rc = SQLITE_OK; /* Return code from service routines */
  108139. Btree *pMain; /* The database being vacuumed */
  108140. Btree *pTemp; /* The temporary database we vacuum into */
  108141. char *zSql = 0; /* SQL statements */
  108142. int saved_flags; /* Saved value of the db->flags */
  108143. int saved_nChange; /* Saved value of db->nChange */
  108144. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  108145. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  108146. Db *pDb = 0; /* Database to detach at end of vacuum */
  108147. int isMemDb; /* True if vacuuming a :memory: database */
  108148. int nRes; /* Bytes of reserved space at the end of each page */
  108149. int nDb; /* Number of attached databases */
  108150. if( !db->autoCommit ){
  108151. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  108152. return SQLITE_ERROR;
  108153. }
  108154. if( db->nVdbeActive>1 ){
  108155. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  108156. return SQLITE_ERROR;
  108157. }
  108158. /* Save the current value of the database flags so that it can be
  108159. ** restored before returning. Then set the writable-schema flag, and
  108160. ** disable CHECK and foreign key constraints. */
  108161. saved_flags = db->flags;
  108162. saved_nChange = db->nChange;
  108163. saved_nTotalChange = db->nTotalChange;
  108164. saved_xTrace = db->xTrace;
  108165. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  108166. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  108167. db->xTrace = 0;
  108168. pMain = db->aDb[0].pBt;
  108169. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  108170. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  108171. ** can be set to 'off' for this file, as it is not recovered if a crash
  108172. ** occurs anyway. The integrity of the database is maintained by a
  108173. ** (possibly synchronous) transaction opened on the main database before
  108174. ** sqlite3BtreeCopyFile() is called.
  108175. **
  108176. ** An optimisation would be to use a non-journaled pager.
  108177. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  108178. ** that actually made the VACUUM run slower. Very little journalling
  108179. ** actually occurs when doing a vacuum since the vacuum_db is initially
  108180. ** empty. Only the journal header is written. Apparently it takes more
  108181. ** time to parse and run the PRAGMA to turn journalling off than it does
  108182. ** to write the journal header file.
  108183. */
  108184. nDb = db->nDb;
  108185. if( sqlite3TempInMemory(db) ){
  108186. zSql = "ATTACH ':memory:' AS vacuum_db;";
  108187. }else{
  108188. zSql = "ATTACH '' AS vacuum_db;";
  108189. }
  108190. rc = execSql(db, pzErrMsg, zSql);
  108191. if( db->nDb>nDb ){
  108192. pDb = &db->aDb[db->nDb-1];
  108193. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  108194. }
  108195. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108196. pTemp = db->aDb[db->nDb-1].pBt;
  108197. /* The call to execSql() to attach the temp database has left the file
  108198. ** locked (as there was more than one active statement when the transaction
  108199. ** to read the schema was concluded. Unlock it here so that this doesn't
  108200. ** cause problems for the call to BtreeSetPageSize() below. */
  108201. sqlite3BtreeCommit(pTemp);
  108202. nRes = sqlite3BtreeGetOptimalReserve(pMain);
  108203. /* A VACUUM cannot change the pagesize of an encrypted database. */
  108204. #ifdef SQLITE_HAS_CODEC
  108205. if( db->nextPagesize ){
  108206. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  108207. int nKey;
  108208. char *zKey;
  108209. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  108210. if( nKey ) db->nextPagesize = 0;
  108211. }
  108212. #endif
  108213. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  108214. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108215. /* Begin a transaction and take an exclusive lock on the main database
  108216. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  108217. ** to ensure that we do not try to change the page-size on a WAL database.
  108218. */
  108219. rc = execSql(db, pzErrMsg, "BEGIN;");
  108220. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108221. rc = sqlite3BtreeBeginTrans(pMain, 2);
  108222. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108223. /* Do not attempt to change the page size for a WAL database */
  108224. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  108225. ==PAGER_JOURNALMODE_WAL ){
  108226. db->nextPagesize = 0;
  108227. }
  108228. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  108229. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  108230. || NEVER(db->mallocFailed)
  108231. ){
  108232. rc = SQLITE_NOMEM;
  108233. goto end_of_vacuum;
  108234. }
  108235. #ifndef SQLITE_OMIT_AUTOVACUUM
  108236. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  108237. sqlite3BtreeGetAutoVacuum(pMain));
  108238. #endif
  108239. /* Query the schema of the main database. Create a mirror schema
  108240. ** in the temporary database.
  108241. */
  108242. rc = execExecSql(db, pzErrMsg,
  108243. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  108244. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  108245. " AND coalesce(rootpage,1)>0"
  108246. );
  108247. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108248. rc = execExecSql(db, pzErrMsg,
  108249. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  108250. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  108251. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108252. rc = execExecSql(db, pzErrMsg,
  108253. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  108254. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  108255. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108256. /* Loop through the tables in the main database. For each, do
  108257. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  108258. ** the contents to the temporary database.
  108259. */
  108260. assert( (db->flags & SQLITE_Vacuum)==0 );
  108261. db->flags |= SQLITE_Vacuum;
  108262. rc = execExecSql(db, pzErrMsg,
  108263. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  108264. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  108265. "FROM main.sqlite_master "
  108266. "WHERE type = 'table' AND name!='sqlite_sequence' "
  108267. " AND coalesce(rootpage,1)>0"
  108268. );
  108269. assert( (db->flags & SQLITE_Vacuum)!=0 );
  108270. db->flags &= ~SQLITE_Vacuum;
  108271. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108272. /* Copy over the sequence table
  108273. */
  108274. rc = execExecSql(db, pzErrMsg,
  108275. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  108276. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  108277. );
  108278. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108279. rc = execExecSql(db, pzErrMsg,
  108280. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  108281. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  108282. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  108283. );
  108284. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108285. /* Copy the triggers, views, and virtual tables from the main database
  108286. ** over to the temporary database. None of these objects has any
  108287. ** associated storage, so all we have to do is copy their entries
  108288. ** from the SQLITE_MASTER table.
  108289. */
  108290. rc = execSql(db, pzErrMsg,
  108291. "INSERT INTO vacuum_db.sqlite_master "
  108292. " SELECT type, name, tbl_name, rootpage, sql"
  108293. " FROM main.sqlite_master"
  108294. " WHERE type='view' OR type='trigger'"
  108295. " OR (type='table' AND rootpage=0)"
  108296. );
  108297. if( rc ) goto end_of_vacuum;
  108298. /* At this point, there is a write transaction open on both the
  108299. ** vacuum database and the main database. Assuming no error occurs,
  108300. ** both transactions are closed by this block - the main database
  108301. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  108302. ** call to sqlite3BtreeCommit().
  108303. */
  108304. {
  108305. u32 meta;
  108306. int i;
  108307. /* This array determines which meta meta values are preserved in the
  108308. ** vacuum. Even entries are the meta value number and odd entries
  108309. ** are an increment to apply to the meta value after the vacuum.
  108310. ** The increment is used to increase the schema cookie so that other
  108311. ** connections to the same database will know to reread the schema.
  108312. */
  108313. static const unsigned char aCopy[] = {
  108314. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  108315. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  108316. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  108317. BTREE_USER_VERSION, 0, /* Preserve the user version */
  108318. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  108319. };
  108320. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  108321. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  108322. /* Copy Btree meta values */
  108323. for(i=0; i<ArraySize(aCopy); i+=2){
  108324. /* GetMeta() and UpdateMeta() cannot fail in this context because
  108325. ** we already have page 1 loaded into cache and marked dirty. */
  108326. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  108327. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  108328. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  108329. }
  108330. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  108331. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108332. rc = sqlite3BtreeCommit(pTemp);
  108333. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  108334. #ifndef SQLITE_OMIT_AUTOVACUUM
  108335. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  108336. #endif
  108337. }
  108338. assert( rc==SQLITE_OK );
  108339. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  108340. end_of_vacuum:
  108341. /* Restore the original value of db->flags */
  108342. db->flags = saved_flags;
  108343. db->nChange = saved_nChange;
  108344. db->nTotalChange = saved_nTotalChange;
  108345. db->xTrace = saved_xTrace;
  108346. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  108347. /* Currently there is an SQL level transaction open on the vacuum
  108348. ** database. No locks are held on any other files (since the main file
  108349. ** was committed at the btree level). So it safe to end the transaction
  108350. ** by manually setting the autoCommit flag to true and detaching the
  108351. ** vacuum database. The vacuum_db journal file is deleted when the pager
  108352. ** is closed by the DETACH.
  108353. */
  108354. db->autoCommit = 1;
  108355. if( pDb ){
  108356. sqlite3BtreeClose(pDb->pBt);
  108357. pDb->pBt = 0;
  108358. pDb->pSchema = 0;
  108359. }
  108360. /* This both clears the schemas and reduces the size of the db->aDb[]
  108361. ** array. */
  108362. sqlite3ResetAllSchemasOfConnection(db);
  108363. return rc;
  108364. }
  108365. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  108366. /************** End of vacuum.c **********************************************/
  108367. /************** Begin file vtab.c ********************************************/
  108368. /*
  108369. ** 2006 June 10
  108370. **
  108371. ** The author disclaims copyright to this source code. In place of
  108372. ** a legal notice, here is a blessing:
  108373. **
  108374. ** May you do good and not evil.
  108375. ** May you find forgiveness for yourself and forgive others.
  108376. ** May you share freely, never taking more than you give.
  108377. **
  108378. *************************************************************************
  108379. ** This file contains code used to help implement virtual tables.
  108380. */
  108381. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108382. /* #include "sqliteInt.h" */
  108383. /*
  108384. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  108385. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  108386. ** this struct allocated on the stack. It is used by the implementation of
  108387. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  108388. ** are invoked only from within xCreate and xConnect methods.
  108389. */
  108390. struct VtabCtx {
  108391. VTable *pVTable; /* The virtual table being constructed */
  108392. Table *pTab; /* The Table object to which the virtual table belongs */
  108393. VtabCtx *pPrior; /* Parent context (if any) */
  108394. int bDeclared; /* True after sqlite3_declare_vtab() is called */
  108395. };
  108396. /*
  108397. ** The actual function that does the work of creating a new module.
  108398. ** This function implements the sqlite3_create_module() and
  108399. ** sqlite3_create_module_v2() interfaces.
  108400. */
  108401. static int createModule(
  108402. sqlite3 *db, /* Database in which module is registered */
  108403. const char *zName, /* Name assigned to this module */
  108404. const sqlite3_module *pModule, /* The definition of the module */
  108405. void *pAux, /* Context pointer for xCreate/xConnect */
  108406. void (*xDestroy)(void *) /* Module destructor function */
  108407. ){
  108408. int rc = SQLITE_OK;
  108409. int nName;
  108410. sqlite3_mutex_enter(db->mutex);
  108411. nName = sqlite3Strlen30(zName);
  108412. if( sqlite3HashFind(&db->aModule, zName) ){
  108413. rc = SQLITE_MISUSE_BKPT;
  108414. }else{
  108415. Module *pMod;
  108416. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  108417. if( pMod ){
  108418. Module *pDel;
  108419. char *zCopy = (char *)(&pMod[1]);
  108420. memcpy(zCopy, zName, nName+1);
  108421. pMod->zName = zCopy;
  108422. pMod->pModule = pModule;
  108423. pMod->pAux = pAux;
  108424. pMod->xDestroy = xDestroy;
  108425. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  108426. assert( pDel==0 || pDel==pMod );
  108427. if( pDel ){
  108428. db->mallocFailed = 1;
  108429. sqlite3DbFree(db, pDel);
  108430. }
  108431. }
  108432. }
  108433. rc = sqlite3ApiExit(db, rc);
  108434. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  108435. sqlite3_mutex_leave(db->mutex);
  108436. return rc;
  108437. }
  108438. /*
  108439. ** External API function used to create a new virtual-table module.
  108440. */
  108441. SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
  108442. sqlite3 *db, /* Database in which module is registered */
  108443. const char *zName, /* Name assigned to this module */
  108444. const sqlite3_module *pModule, /* The definition of the module */
  108445. void *pAux /* Context pointer for xCreate/xConnect */
  108446. ){
  108447. #ifdef SQLITE_ENABLE_API_ARMOR
  108448. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  108449. #endif
  108450. return createModule(db, zName, pModule, pAux, 0);
  108451. }
  108452. /*
  108453. ** External API function used to create a new virtual-table module.
  108454. */
  108455. SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
  108456. sqlite3 *db, /* Database in which module is registered */
  108457. const char *zName, /* Name assigned to this module */
  108458. const sqlite3_module *pModule, /* The definition of the module */
  108459. void *pAux, /* Context pointer for xCreate/xConnect */
  108460. void (*xDestroy)(void *) /* Module destructor function */
  108461. ){
  108462. #ifdef SQLITE_ENABLE_API_ARMOR
  108463. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  108464. #endif
  108465. return createModule(db, zName, pModule, pAux, xDestroy);
  108466. }
  108467. /*
  108468. ** Lock the virtual table so that it cannot be disconnected.
  108469. ** Locks nest. Every lock should have a corresponding unlock.
  108470. ** If an unlock is omitted, resources leaks will occur.
  108471. **
  108472. ** If a disconnect is attempted while a virtual table is locked,
  108473. ** the disconnect is deferred until all locks have been removed.
  108474. */
  108475. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  108476. pVTab->nRef++;
  108477. }
  108478. /*
  108479. ** pTab is a pointer to a Table structure representing a virtual-table.
  108480. ** Return a pointer to the VTable object used by connection db to access
  108481. ** this virtual-table, if one has been created, or NULL otherwise.
  108482. */
  108483. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  108484. VTable *pVtab;
  108485. assert( IsVirtual(pTab) );
  108486. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  108487. return pVtab;
  108488. }
  108489. /*
  108490. ** Decrement the ref-count on a virtual table object. When the ref-count
  108491. ** reaches zero, call the xDisconnect() method to delete the object.
  108492. */
  108493. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  108494. sqlite3 *db = pVTab->db;
  108495. assert( db );
  108496. assert( pVTab->nRef>0 );
  108497. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  108498. pVTab->nRef--;
  108499. if( pVTab->nRef==0 ){
  108500. sqlite3_vtab *p = pVTab->pVtab;
  108501. if( p ){
  108502. p->pModule->xDisconnect(p);
  108503. }
  108504. sqlite3DbFree(db, pVTab);
  108505. }
  108506. }
  108507. /*
  108508. ** Table p is a virtual table. This function moves all elements in the
  108509. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  108510. ** database connections to be disconnected at the next opportunity.
  108511. ** Except, if argument db is not NULL, then the entry associated with
  108512. ** connection db is left in the p->pVTable list.
  108513. */
  108514. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  108515. VTable *pRet = 0;
  108516. VTable *pVTable = p->pVTable;
  108517. p->pVTable = 0;
  108518. /* Assert that the mutex (if any) associated with the BtShared database
  108519. ** that contains table p is held by the caller. See header comments
  108520. ** above function sqlite3VtabUnlockList() for an explanation of why
  108521. ** this makes it safe to access the sqlite3.pDisconnect list of any
  108522. ** database connection that may have an entry in the p->pVTable list.
  108523. */
  108524. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  108525. while( pVTable ){
  108526. sqlite3 *db2 = pVTable->db;
  108527. VTable *pNext = pVTable->pNext;
  108528. assert( db2 );
  108529. if( db2==db ){
  108530. pRet = pVTable;
  108531. p->pVTable = pRet;
  108532. pRet->pNext = 0;
  108533. }else{
  108534. pVTable->pNext = db2->pDisconnect;
  108535. db2->pDisconnect = pVTable;
  108536. }
  108537. pVTable = pNext;
  108538. }
  108539. assert( !db || pRet );
  108540. return pRet;
  108541. }
  108542. /*
  108543. ** Table *p is a virtual table. This function removes the VTable object
  108544. ** for table *p associated with database connection db from the linked
  108545. ** list in p->pVTab. It also decrements the VTable ref count. This is
  108546. ** used when closing database connection db to free all of its VTable
  108547. ** objects without disturbing the rest of the Schema object (which may
  108548. ** be being used by other shared-cache connections).
  108549. */
  108550. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  108551. VTable **ppVTab;
  108552. assert( IsVirtual(p) );
  108553. assert( sqlite3BtreeHoldsAllMutexes(db) );
  108554. assert( sqlite3_mutex_held(db->mutex) );
  108555. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  108556. if( (*ppVTab)->db==db ){
  108557. VTable *pVTab = *ppVTab;
  108558. *ppVTab = pVTab->pNext;
  108559. sqlite3VtabUnlock(pVTab);
  108560. break;
  108561. }
  108562. }
  108563. }
  108564. /*
  108565. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  108566. **
  108567. ** This function may only be called when the mutexes associated with all
  108568. ** shared b-tree databases opened using connection db are held by the
  108569. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  108570. ** sqlite3.pDisconnect list is accessed only as follows:
  108571. **
  108572. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  108573. ** associated with the database handle itself must be held.
  108574. **
  108575. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  108576. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  108577. ** associated with the database the virtual table is stored in is held
  108578. ** or, if the virtual table is stored in a non-sharable database, then
  108579. ** the database handle mutex is held.
  108580. **
  108581. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  108582. ** by multiple threads. It is thread-safe.
  108583. */
  108584. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  108585. VTable *p = db->pDisconnect;
  108586. db->pDisconnect = 0;
  108587. assert( sqlite3BtreeHoldsAllMutexes(db) );
  108588. assert( sqlite3_mutex_held(db->mutex) );
  108589. if( p ){
  108590. sqlite3ExpirePreparedStatements(db);
  108591. do {
  108592. VTable *pNext = p->pNext;
  108593. sqlite3VtabUnlock(p);
  108594. p = pNext;
  108595. }while( p );
  108596. }
  108597. }
  108598. /*
  108599. ** Clear any and all virtual-table information from the Table record.
  108600. ** This routine is called, for example, just before deleting the Table
  108601. ** record.
  108602. **
  108603. ** Since it is a virtual-table, the Table structure contains a pointer
  108604. ** to the head of a linked list of VTable structures. Each VTable
  108605. ** structure is associated with a single sqlite3* user of the schema.
  108606. ** The reference count of the VTable structure associated with database
  108607. ** connection db is decremented immediately (which may lead to the
  108608. ** structure being xDisconnected and free). Any other VTable structures
  108609. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  108610. ** database connection.
  108611. */
  108612. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  108613. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  108614. if( p->azModuleArg ){
  108615. int i;
  108616. for(i=0; i<p->nModuleArg; i++){
  108617. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  108618. }
  108619. sqlite3DbFree(db, p->azModuleArg);
  108620. }
  108621. }
  108622. /*
  108623. ** Add a new module argument to pTable->azModuleArg[].
  108624. ** The string is not copied - the pointer is stored. The
  108625. ** string will be freed automatically when the table is
  108626. ** deleted.
  108627. */
  108628. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  108629. int i = pTable->nModuleArg++;
  108630. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  108631. char **azModuleArg;
  108632. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  108633. if( azModuleArg==0 ){
  108634. int j;
  108635. for(j=0; j<i; j++){
  108636. sqlite3DbFree(db, pTable->azModuleArg[j]);
  108637. }
  108638. sqlite3DbFree(db, zArg);
  108639. sqlite3DbFree(db, pTable->azModuleArg);
  108640. pTable->nModuleArg = 0;
  108641. }else{
  108642. azModuleArg[i] = zArg;
  108643. azModuleArg[i+1] = 0;
  108644. }
  108645. pTable->azModuleArg = azModuleArg;
  108646. }
  108647. /*
  108648. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  108649. ** statement. The module name has been parsed, but the optional list
  108650. ** of parameters that follow the module name are still pending.
  108651. */
  108652. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  108653. Parse *pParse, /* Parsing context */
  108654. Token *pName1, /* Name of new table, or database name */
  108655. Token *pName2, /* Name of new table or NULL */
  108656. Token *pModuleName, /* Name of the module for the virtual table */
  108657. int ifNotExists /* No error if the table already exists */
  108658. ){
  108659. int iDb; /* The database the table is being created in */
  108660. Table *pTable; /* The new virtual table */
  108661. sqlite3 *db; /* Database connection */
  108662. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  108663. pTable = pParse->pNewTable;
  108664. if( pTable==0 ) return;
  108665. assert( 0==pTable->pIndex );
  108666. db = pParse->db;
  108667. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  108668. assert( iDb>=0 );
  108669. pTable->tabFlags |= TF_Virtual;
  108670. pTable->nModuleArg = 0;
  108671. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  108672. addModuleArgument(db, pTable, 0);
  108673. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  108674. assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
  108675. || (pParse->sNameToken.z==pName1->z && pName2->z==0)
  108676. );
  108677. pParse->sNameToken.n = (int)(
  108678. &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
  108679. );
  108680. #ifndef SQLITE_OMIT_AUTHORIZATION
  108681. /* Creating a virtual table invokes the authorization callback twice.
  108682. ** The first invocation, to obtain permission to INSERT a row into the
  108683. ** sqlite_master table, has already been made by sqlite3StartTable().
  108684. ** The second call, to obtain permission to create the table, is made now.
  108685. */
  108686. if( pTable->azModuleArg ){
  108687. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  108688. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  108689. }
  108690. #endif
  108691. }
  108692. /*
  108693. ** This routine takes the module argument that has been accumulating
  108694. ** in pParse->zArg[] and appends it to the list of arguments on the
  108695. ** virtual table currently under construction in pParse->pTable.
  108696. */
  108697. static void addArgumentToVtab(Parse *pParse){
  108698. if( pParse->sArg.z && pParse->pNewTable ){
  108699. const char *z = (const char*)pParse->sArg.z;
  108700. int n = pParse->sArg.n;
  108701. sqlite3 *db = pParse->db;
  108702. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  108703. }
  108704. }
  108705. /*
  108706. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  108707. ** has been completely parsed.
  108708. */
  108709. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  108710. Table *pTab = pParse->pNewTable; /* The table being constructed */
  108711. sqlite3 *db = pParse->db; /* The database connection */
  108712. if( pTab==0 ) return;
  108713. addArgumentToVtab(pParse);
  108714. pParse->sArg.z = 0;
  108715. if( pTab->nModuleArg<1 ) return;
  108716. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  108717. ** first time (in other words if the virtual table is actually being
  108718. ** created now instead of just being read out of sqlite_master) then
  108719. ** do additional initialization work and store the statement text
  108720. ** in the sqlite_master table.
  108721. */
  108722. if( !db->init.busy ){
  108723. char *zStmt;
  108724. char *zWhere;
  108725. int iDb;
  108726. int iReg;
  108727. Vdbe *v;
  108728. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  108729. if( pEnd ){
  108730. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  108731. }
  108732. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  108733. /* A slot for the record has already been allocated in the
  108734. ** SQLITE_MASTER table. We just need to update that slot with all
  108735. ** the information we've collected.
  108736. **
  108737. ** The VM register number pParse->regRowid holds the rowid of an
  108738. ** entry in the sqlite_master table tht was created for this vtab
  108739. ** by sqlite3StartTable().
  108740. */
  108741. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108742. sqlite3NestedParse(pParse,
  108743. "UPDATE %Q.%s "
  108744. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  108745. "WHERE rowid=#%d",
  108746. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  108747. pTab->zName,
  108748. pTab->zName,
  108749. zStmt,
  108750. pParse->regRowid
  108751. );
  108752. sqlite3DbFree(db, zStmt);
  108753. v = sqlite3GetVdbe(pParse);
  108754. sqlite3ChangeCookie(pParse, iDb);
  108755. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  108756. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  108757. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  108758. iReg = ++pParse->nMem;
  108759. sqlite3VdbeAddOp4(v, OP_String8, 0, iReg, 0, pTab->zName, 0);
  108760. sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
  108761. }
  108762. /* If we are rereading the sqlite_master table create the in-memory
  108763. ** record of the table. The xConnect() method is not called until
  108764. ** the first time the virtual table is used in an SQL statement. This
  108765. ** allows a schema that contains virtual tables to be loaded before
  108766. ** the required virtual table implementations are registered. */
  108767. else {
  108768. Table *pOld;
  108769. Schema *pSchema = pTab->pSchema;
  108770. const char *zName = pTab->zName;
  108771. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  108772. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  108773. if( pOld ){
  108774. db->mallocFailed = 1;
  108775. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  108776. return;
  108777. }
  108778. pParse->pNewTable = 0;
  108779. }
  108780. }
  108781. /*
  108782. ** The parser calls this routine when it sees the first token
  108783. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  108784. */
  108785. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  108786. addArgumentToVtab(pParse);
  108787. pParse->sArg.z = 0;
  108788. pParse->sArg.n = 0;
  108789. }
  108790. /*
  108791. ** The parser calls this routine for each token after the first token
  108792. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  108793. */
  108794. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  108795. Token *pArg = &pParse->sArg;
  108796. if( pArg->z==0 ){
  108797. pArg->z = p->z;
  108798. pArg->n = p->n;
  108799. }else{
  108800. assert(pArg->z <= p->z);
  108801. pArg->n = (int)(&p->z[p->n] - pArg->z);
  108802. }
  108803. }
  108804. /*
  108805. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  108806. ** pointer to the function to invoke is passed as the fourth parameter
  108807. ** to this procedure.
  108808. */
  108809. static int vtabCallConstructor(
  108810. sqlite3 *db,
  108811. Table *pTab,
  108812. Module *pMod,
  108813. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  108814. char **pzErr
  108815. ){
  108816. VtabCtx sCtx;
  108817. VTable *pVTable;
  108818. int rc;
  108819. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  108820. int nArg = pTab->nModuleArg;
  108821. char *zErr = 0;
  108822. char *zModuleName;
  108823. int iDb;
  108824. VtabCtx *pCtx;
  108825. /* Check that the virtual-table is not already being initialized */
  108826. for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
  108827. if( pCtx->pTab==pTab ){
  108828. *pzErr = sqlite3MPrintf(db,
  108829. "vtable constructor called recursively: %s", pTab->zName
  108830. );
  108831. return SQLITE_LOCKED;
  108832. }
  108833. }
  108834. zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  108835. if( !zModuleName ){
  108836. return SQLITE_NOMEM;
  108837. }
  108838. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  108839. if( !pVTable ){
  108840. sqlite3DbFree(db, zModuleName);
  108841. return SQLITE_NOMEM;
  108842. }
  108843. pVTable->db = db;
  108844. pVTable->pMod = pMod;
  108845. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108846. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  108847. /* Invoke the virtual table constructor */
  108848. assert( &db->pVtabCtx );
  108849. assert( xConstruct );
  108850. sCtx.pTab = pTab;
  108851. sCtx.pVTable = pVTable;
  108852. sCtx.pPrior = db->pVtabCtx;
  108853. sCtx.bDeclared = 0;
  108854. db->pVtabCtx = &sCtx;
  108855. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  108856. db->pVtabCtx = sCtx.pPrior;
  108857. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  108858. assert( sCtx.pTab==pTab );
  108859. if( SQLITE_OK!=rc ){
  108860. if( zErr==0 ){
  108861. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  108862. }else {
  108863. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  108864. sqlite3_free(zErr);
  108865. }
  108866. sqlite3DbFree(db, pVTable);
  108867. }else if( ALWAYS(pVTable->pVtab) ){
  108868. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  108869. ** the sqlite3_vtab object if successful. */
  108870. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  108871. pVTable->pVtab->pModule = pMod->pModule;
  108872. pVTable->nRef = 1;
  108873. if( sCtx.bDeclared==0 ){
  108874. const char *zFormat = "vtable constructor did not declare schema: %s";
  108875. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  108876. sqlite3VtabUnlock(pVTable);
  108877. rc = SQLITE_ERROR;
  108878. }else{
  108879. int iCol;
  108880. u8 oooHidden = 0;
  108881. /* If everything went according to plan, link the new VTable structure
  108882. ** into the linked list headed by pTab->pVTable. Then loop through the
  108883. ** columns of the table to see if any of them contain the token "hidden".
  108884. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  108885. ** the type string. */
  108886. pVTable->pNext = pTab->pVTable;
  108887. pTab->pVTable = pVTable;
  108888. for(iCol=0; iCol<pTab->nCol; iCol++){
  108889. char *zType = pTab->aCol[iCol].zType;
  108890. int nType;
  108891. int i = 0;
  108892. if( !zType ){
  108893. pTab->tabFlags |= oooHidden;
  108894. continue;
  108895. }
  108896. nType = sqlite3Strlen30(zType);
  108897. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  108898. for(i=0; i<nType; i++){
  108899. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  108900. && (zType[i+7]=='\0' || zType[i+7]==' ')
  108901. ){
  108902. i++;
  108903. break;
  108904. }
  108905. }
  108906. }
  108907. if( i<nType ){
  108908. int j;
  108909. int nDel = 6 + (zType[i+6] ? 1 : 0);
  108910. for(j=i; (j+nDel)<=nType; j++){
  108911. zType[j] = zType[j+nDel];
  108912. }
  108913. if( zType[i]=='\0' && i>0 ){
  108914. assert(zType[i-1]==' ');
  108915. zType[i-1] = '\0';
  108916. }
  108917. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  108918. oooHidden = TF_OOOHidden;
  108919. }else{
  108920. pTab->tabFlags |= oooHidden;
  108921. }
  108922. }
  108923. }
  108924. }
  108925. sqlite3DbFree(db, zModuleName);
  108926. return rc;
  108927. }
  108928. /*
  108929. ** This function is invoked by the parser to call the xConnect() method
  108930. ** of the virtual table pTab. If an error occurs, an error code is returned
  108931. ** and an error left in pParse.
  108932. **
  108933. ** This call is a no-op if table pTab is not a virtual table.
  108934. */
  108935. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  108936. sqlite3 *db = pParse->db;
  108937. const char *zMod;
  108938. Module *pMod;
  108939. int rc;
  108940. assert( pTab );
  108941. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  108942. return SQLITE_OK;
  108943. }
  108944. /* Locate the required virtual table module */
  108945. zMod = pTab->azModuleArg[0];
  108946. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  108947. if( !pMod ){
  108948. const char *zModule = pTab->azModuleArg[0];
  108949. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  108950. rc = SQLITE_ERROR;
  108951. }else{
  108952. char *zErr = 0;
  108953. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  108954. if( rc!=SQLITE_OK ){
  108955. sqlite3ErrorMsg(pParse, "%s", zErr);
  108956. }
  108957. sqlite3DbFree(db, zErr);
  108958. }
  108959. return rc;
  108960. }
  108961. /*
  108962. ** Grow the db->aVTrans[] array so that there is room for at least one
  108963. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  108964. */
  108965. static int growVTrans(sqlite3 *db){
  108966. const int ARRAY_INCR = 5;
  108967. /* Grow the sqlite3.aVTrans array if required */
  108968. if( (db->nVTrans%ARRAY_INCR)==0 ){
  108969. VTable **aVTrans;
  108970. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  108971. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  108972. if( !aVTrans ){
  108973. return SQLITE_NOMEM;
  108974. }
  108975. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  108976. db->aVTrans = aVTrans;
  108977. }
  108978. return SQLITE_OK;
  108979. }
  108980. /*
  108981. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  108982. ** have already been reserved using growVTrans().
  108983. */
  108984. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  108985. /* Add pVtab to the end of sqlite3.aVTrans */
  108986. db->aVTrans[db->nVTrans++] = pVTab;
  108987. sqlite3VtabLock(pVTab);
  108988. }
  108989. /*
  108990. ** This function is invoked by the vdbe to call the xCreate method
  108991. ** of the virtual table named zTab in database iDb.
  108992. **
  108993. ** If an error occurs, *pzErr is set to point an an English language
  108994. ** description of the error and an SQLITE_XXX error code is returned.
  108995. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  108996. */
  108997. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  108998. int rc = SQLITE_OK;
  108999. Table *pTab;
  109000. Module *pMod;
  109001. const char *zMod;
  109002. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  109003. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  109004. /* Locate the required virtual table module */
  109005. zMod = pTab->azModuleArg[0];
  109006. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  109007. /* If the module has been registered and includes a Create method,
  109008. ** invoke it now. If the module has not been registered, return an
  109009. ** error. Otherwise, do nothing.
  109010. */
  109011. if( !pMod ){
  109012. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  109013. rc = SQLITE_ERROR;
  109014. }else{
  109015. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  109016. }
  109017. /* Justification of ALWAYS(): The xConstructor method is required to
  109018. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  109019. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  109020. rc = growVTrans(db);
  109021. if( rc==SQLITE_OK ){
  109022. addToVTrans(db, sqlite3GetVTable(db, pTab));
  109023. }
  109024. }
  109025. return rc;
  109026. }
  109027. /*
  109028. ** This function is used to set the schema of a virtual table. It is only
  109029. ** valid to call this function from within the xCreate() or xConnect() of a
  109030. ** virtual table module.
  109031. */
  109032. SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  109033. VtabCtx *pCtx;
  109034. Parse *pParse;
  109035. int rc = SQLITE_OK;
  109036. Table *pTab;
  109037. char *zErr = 0;
  109038. #ifdef SQLITE_ENABLE_API_ARMOR
  109039. if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
  109040. return SQLITE_MISUSE_BKPT;
  109041. }
  109042. #endif
  109043. sqlite3_mutex_enter(db->mutex);
  109044. pCtx = db->pVtabCtx;
  109045. if( !pCtx || pCtx->bDeclared ){
  109046. sqlite3Error(db, SQLITE_MISUSE);
  109047. sqlite3_mutex_leave(db->mutex);
  109048. return SQLITE_MISUSE_BKPT;
  109049. }
  109050. pTab = pCtx->pTab;
  109051. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  109052. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  109053. if( pParse==0 ){
  109054. rc = SQLITE_NOMEM;
  109055. }else{
  109056. pParse->declareVtab = 1;
  109057. pParse->db = db;
  109058. pParse->nQueryLoop = 1;
  109059. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  109060. && pParse->pNewTable
  109061. && !db->mallocFailed
  109062. && !pParse->pNewTable->pSelect
  109063. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  109064. ){
  109065. if( !pTab->aCol ){
  109066. pTab->aCol = pParse->pNewTable->aCol;
  109067. pTab->nCol = pParse->pNewTable->nCol;
  109068. pParse->pNewTable->nCol = 0;
  109069. pParse->pNewTable->aCol = 0;
  109070. }
  109071. pCtx->bDeclared = 1;
  109072. }else{
  109073. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  109074. sqlite3DbFree(db, zErr);
  109075. rc = SQLITE_ERROR;
  109076. }
  109077. pParse->declareVtab = 0;
  109078. if( pParse->pVdbe ){
  109079. sqlite3VdbeFinalize(pParse->pVdbe);
  109080. }
  109081. sqlite3DeleteTable(db, pParse->pNewTable);
  109082. sqlite3ParserReset(pParse);
  109083. sqlite3StackFree(db, pParse);
  109084. }
  109085. assert( (rc&0xff)==rc );
  109086. rc = sqlite3ApiExit(db, rc);
  109087. sqlite3_mutex_leave(db->mutex);
  109088. return rc;
  109089. }
  109090. /*
  109091. ** This function is invoked by the vdbe to call the xDestroy method
  109092. ** of the virtual table named zTab in database iDb. This occurs
  109093. ** when a DROP TABLE is mentioned.
  109094. **
  109095. ** This call is a no-op if zTab is not a virtual table.
  109096. */
  109097. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  109098. int rc = SQLITE_OK;
  109099. Table *pTab;
  109100. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  109101. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  109102. VTable *p;
  109103. for(p=pTab->pVTable; p; p=p->pNext){
  109104. assert( p->pVtab );
  109105. if( p->pVtab->nRef>0 ){
  109106. return SQLITE_LOCKED;
  109107. }
  109108. }
  109109. p = vtabDisconnectAll(db, pTab);
  109110. rc = p->pMod->pModule->xDestroy(p->pVtab);
  109111. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  109112. if( rc==SQLITE_OK ){
  109113. assert( pTab->pVTable==p && p->pNext==0 );
  109114. p->pVtab = 0;
  109115. pTab->pVTable = 0;
  109116. sqlite3VtabUnlock(p);
  109117. }
  109118. }
  109119. return rc;
  109120. }
  109121. /*
  109122. ** This function invokes either the xRollback or xCommit method
  109123. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  109124. ** called is identified by the second argument, "offset", which is
  109125. ** the offset of the method to call in the sqlite3_module structure.
  109126. **
  109127. ** The array is cleared after invoking the callbacks.
  109128. */
  109129. static void callFinaliser(sqlite3 *db, int offset){
  109130. int i;
  109131. if( db->aVTrans ){
  109132. VTable **aVTrans = db->aVTrans;
  109133. db->aVTrans = 0;
  109134. for(i=0; i<db->nVTrans; i++){
  109135. VTable *pVTab = aVTrans[i];
  109136. sqlite3_vtab *p = pVTab->pVtab;
  109137. if( p ){
  109138. int (*x)(sqlite3_vtab *);
  109139. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  109140. if( x ) x(p);
  109141. }
  109142. pVTab->iSavepoint = 0;
  109143. sqlite3VtabUnlock(pVTab);
  109144. }
  109145. sqlite3DbFree(db, aVTrans);
  109146. db->nVTrans = 0;
  109147. }
  109148. }
  109149. /*
  109150. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  109151. ** array. Return the error code for the first error that occurs, or
  109152. ** SQLITE_OK if all xSync operations are successful.
  109153. **
  109154. ** If an error message is available, leave it in p->zErrMsg.
  109155. */
  109156. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  109157. int i;
  109158. int rc = SQLITE_OK;
  109159. VTable **aVTrans = db->aVTrans;
  109160. db->aVTrans = 0;
  109161. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  109162. int (*x)(sqlite3_vtab *);
  109163. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  109164. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  109165. rc = x(pVtab);
  109166. sqlite3VtabImportErrmsg(p, pVtab);
  109167. }
  109168. }
  109169. db->aVTrans = aVTrans;
  109170. return rc;
  109171. }
  109172. /*
  109173. ** Invoke the xRollback method of all virtual tables in the
  109174. ** sqlite3.aVTrans array. Then clear the array itself.
  109175. */
  109176. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  109177. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  109178. return SQLITE_OK;
  109179. }
  109180. /*
  109181. ** Invoke the xCommit method of all virtual tables in the
  109182. ** sqlite3.aVTrans array. Then clear the array itself.
  109183. */
  109184. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  109185. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  109186. return SQLITE_OK;
  109187. }
  109188. /*
  109189. ** If the virtual table pVtab supports the transaction interface
  109190. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  109191. ** not currently open, invoke the xBegin method now.
  109192. **
  109193. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  109194. ** in the sqlite3.aVTrans array.
  109195. */
  109196. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  109197. int rc = SQLITE_OK;
  109198. const sqlite3_module *pModule;
  109199. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  109200. ** than zero, then this function is being called from within a
  109201. ** virtual module xSync() callback. It is illegal to write to
  109202. ** virtual module tables in this case, so return SQLITE_LOCKED.
  109203. */
  109204. if( sqlite3VtabInSync(db) ){
  109205. return SQLITE_LOCKED;
  109206. }
  109207. if( !pVTab ){
  109208. return SQLITE_OK;
  109209. }
  109210. pModule = pVTab->pVtab->pModule;
  109211. if( pModule->xBegin ){
  109212. int i;
  109213. /* If pVtab is already in the aVTrans array, return early */
  109214. for(i=0; i<db->nVTrans; i++){
  109215. if( db->aVTrans[i]==pVTab ){
  109216. return SQLITE_OK;
  109217. }
  109218. }
  109219. /* Invoke the xBegin method. If successful, add the vtab to the
  109220. ** sqlite3.aVTrans[] array. */
  109221. rc = growVTrans(db);
  109222. if( rc==SQLITE_OK ){
  109223. rc = pModule->xBegin(pVTab->pVtab);
  109224. if( rc==SQLITE_OK ){
  109225. addToVTrans(db, pVTab);
  109226. }
  109227. }
  109228. }
  109229. return rc;
  109230. }
  109231. /*
  109232. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  109233. ** virtual tables that currently have an open transaction. Pass iSavepoint
  109234. ** as the second argument to the virtual table method invoked.
  109235. **
  109236. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  109237. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  109238. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  109239. ** an open transaction is invoked.
  109240. **
  109241. ** If any virtual table method returns an error code other than SQLITE_OK,
  109242. ** processing is abandoned and the error returned to the caller of this
  109243. ** function immediately. If all calls to virtual table methods are successful,
  109244. ** SQLITE_OK is returned.
  109245. */
  109246. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  109247. int rc = SQLITE_OK;
  109248. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  109249. assert( iSavepoint>=-1 );
  109250. if( db->aVTrans ){
  109251. int i;
  109252. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  109253. VTable *pVTab = db->aVTrans[i];
  109254. const sqlite3_module *pMod = pVTab->pMod->pModule;
  109255. if( pVTab->pVtab && pMod->iVersion>=2 ){
  109256. int (*xMethod)(sqlite3_vtab *, int);
  109257. switch( op ){
  109258. case SAVEPOINT_BEGIN:
  109259. xMethod = pMod->xSavepoint;
  109260. pVTab->iSavepoint = iSavepoint+1;
  109261. break;
  109262. case SAVEPOINT_ROLLBACK:
  109263. xMethod = pMod->xRollbackTo;
  109264. break;
  109265. default:
  109266. xMethod = pMod->xRelease;
  109267. break;
  109268. }
  109269. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  109270. rc = xMethod(pVTab->pVtab, iSavepoint);
  109271. }
  109272. }
  109273. }
  109274. }
  109275. return rc;
  109276. }
  109277. /*
  109278. ** The first parameter (pDef) is a function implementation. The
  109279. ** second parameter (pExpr) is the first argument to this function.
  109280. ** If pExpr is a column in a virtual table, then let the virtual
  109281. ** table implementation have an opportunity to overload the function.
  109282. **
  109283. ** This routine is used to allow virtual table implementations to
  109284. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  109285. **
  109286. ** Return either the pDef argument (indicating no change) or a
  109287. ** new FuncDef structure that is marked as ephemeral using the
  109288. ** SQLITE_FUNC_EPHEM flag.
  109289. */
  109290. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  109291. sqlite3 *db, /* Database connection for reporting malloc problems */
  109292. FuncDef *pDef, /* Function to possibly overload */
  109293. int nArg, /* Number of arguments to the function */
  109294. Expr *pExpr /* First argument to the function */
  109295. ){
  109296. Table *pTab;
  109297. sqlite3_vtab *pVtab;
  109298. sqlite3_module *pMod;
  109299. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  109300. void *pArg = 0;
  109301. FuncDef *pNew;
  109302. int rc = 0;
  109303. char *zLowerName;
  109304. unsigned char *z;
  109305. /* Check to see the left operand is a column in a virtual table */
  109306. if( NEVER(pExpr==0) ) return pDef;
  109307. if( pExpr->op!=TK_COLUMN ) return pDef;
  109308. pTab = pExpr->pTab;
  109309. if( NEVER(pTab==0) ) return pDef;
  109310. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  109311. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  109312. assert( pVtab!=0 );
  109313. assert( pVtab->pModule!=0 );
  109314. pMod = (sqlite3_module *)pVtab->pModule;
  109315. if( pMod->xFindFunction==0 ) return pDef;
  109316. /* Call the xFindFunction method on the virtual table implementation
  109317. ** to see if the implementation wants to overload this function
  109318. */
  109319. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  109320. if( zLowerName ){
  109321. for(z=(unsigned char*)zLowerName; *z; z++){
  109322. *z = sqlite3UpperToLower[*z];
  109323. }
  109324. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  109325. sqlite3DbFree(db, zLowerName);
  109326. }
  109327. if( rc==0 ){
  109328. return pDef;
  109329. }
  109330. /* Create a new ephemeral function definition for the overloaded
  109331. ** function */
  109332. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  109333. + sqlite3Strlen30(pDef->zName) + 1);
  109334. if( pNew==0 ){
  109335. return pDef;
  109336. }
  109337. *pNew = *pDef;
  109338. pNew->zName = (char *)&pNew[1];
  109339. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  109340. pNew->xFunc = xFunc;
  109341. pNew->pUserData = pArg;
  109342. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  109343. return pNew;
  109344. }
  109345. /*
  109346. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  109347. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  109348. ** array if it is missing. If pTab is already in the array, this routine
  109349. ** is a no-op.
  109350. */
  109351. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  109352. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  109353. int i, n;
  109354. Table **apVtabLock;
  109355. assert( IsVirtual(pTab) );
  109356. for(i=0; i<pToplevel->nVtabLock; i++){
  109357. if( pTab==pToplevel->apVtabLock[i] ) return;
  109358. }
  109359. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  109360. apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
  109361. if( apVtabLock ){
  109362. pToplevel->apVtabLock = apVtabLock;
  109363. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  109364. }else{
  109365. pToplevel->db->mallocFailed = 1;
  109366. }
  109367. }
  109368. /*
  109369. ** Return the ON CONFLICT resolution mode in effect for the virtual
  109370. ** table update operation currently in progress.
  109371. **
  109372. ** The results of this routine are undefined unless it is called from
  109373. ** within an xUpdate method.
  109374. */
  109375. SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
  109376. static const unsigned char aMap[] = {
  109377. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  109378. };
  109379. #ifdef SQLITE_ENABLE_API_ARMOR
  109380. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  109381. #endif
  109382. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  109383. assert( OE_Ignore==4 && OE_Replace==5 );
  109384. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  109385. return (int)aMap[db->vtabOnConflict-1];
  109386. }
  109387. /*
  109388. ** Call from within the xCreate() or xConnect() methods to provide
  109389. ** the SQLite core with additional information about the behavior
  109390. ** of the virtual table being implemented.
  109391. */
  109392. SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
  109393. va_list ap;
  109394. int rc = SQLITE_OK;
  109395. #ifdef SQLITE_ENABLE_API_ARMOR
  109396. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  109397. #endif
  109398. sqlite3_mutex_enter(db->mutex);
  109399. va_start(ap, op);
  109400. switch( op ){
  109401. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  109402. VtabCtx *p = db->pVtabCtx;
  109403. if( !p ){
  109404. rc = SQLITE_MISUSE_BKPT;
  109405. }else{
  109406. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  109407. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  109408. }
  109409. break;
  109410. }
  109411. default:
  109412. rc = SQLITE_MISUSE_BKPT;
  109413. break;
  109414. }
  109415. va_end(ap);
  109416. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  109417. sqlite3_mutex_leave(db->mutex);
  109418. return rc;
  109419. }
  109420. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  109421. /************** End of vtab.c ************************************************/
  109422. /************** Begin file wherecode.c ***************************************/
  109423. /*
  109424. ** 2015-06-06
  109425. **
  109426. ** The author disclaims copyright to this source code. In place of
  109427. ** a legal notice, here is a blessing:
  109428. **
  109429. ** May you do good and not evil.
  109430. ** May you find forgiveness for yourself and forgive others.
  109431. ** May you share freely, never taking more than you give.
  109432. **
  109433. *************************************************************************
  109434. ** This module contains C code that generates VDBE code used to process
  109435. ** the WHERE clause of SQL statements.
  109436. **
  109437. ** This file was split off from where.c on 2015-06-06 in order to reduce the
  109438. ** size of where.c and make it easier to edit. This file contains the routines
  109439. ** that actually generate the bulk of the WHERE loop code. The original where.c
  109440. ** file retains the code that does query planning and analysis.
  109441. */
  109442. /* #include "sqliteInt.h" */
  109443. /************** Include whereInt.h in the middle of wherecode.c **************/
  109444. /************** Begin file whereInt.h ****************************************/
  109445. /*
  109446. ** 2013-11-12
  109447. **
  109448. ** The author disclaims copyright to this source code. In place of
  109449. ** a legal notice, here is a blessing:
  109450. **
  109451. ** May you do good and not evil.
  109452. ** May you find forgiveness for yourself and forgive others.
  109453. ** May you share freely, never taking more than you give.
  109454. **
  109455. *************************************************************************
  109456. **
  109457. ** This file contains structure and macro definitions for the query
  109458. ** planner logic in "where.c". These definitions are broken out into
  109459. ** a separate source file for easier editing.
  109460. */
  109461. /*
  109462. ** Trace output macros
  109463. */
  109464. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  109465. /***/ int sqlite3WhereTrace;
  109466. #endif
  109467. #if defined(SQLITE_DEBUG) \
  109468. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  109469. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  109470. # define WHERETRACE_ENABLED 1
  109471. #else
  109472. # define WHERETRACE(K,X)
  109473. #endif
  109474. /* Forward references
  109475. */
  109476. typedef struct WhereClause WhereClause;
  109477. typedef struct WhereMaskSet WhereMaskSet;
  109478. typedef struct WhereOrInfo WhereOrInfo;
  109479. typedef struct WhereAndInfo WhereAndInfo;
  109480. typedef struct WhereLevel WhereLevel;
  109481. typedef struct WhereLoop WhereLoop;
  109482. typedef struct WherePath WherePath;
  109483. typedef struct WhereTerm WhereTerm;
  109484. typedef struct WhereLoopBuilder WhereLoopBuilder;
  109485. typedef struct WhereScan WhereScan;
  109486. typedef struct WhereOrCost WhereOrCost;
  109487. typedef struct WhereOrSet WhereOrSet;
  109488. /*
  109489. ** This object contains information needed to implement a single nested
  109490. ** loop in WHERE clause.
  109491. **
  109492. ** Contrast this object with WhereLoop. This object describes the
  109493. ** implementation of the loop. WhereLoop describes the algorithm.
  109494. ** This object contains a pointer to the WhereLoop algorithm as one of
  109495. ** its elements.
  109496. **
  109497. ** The WhereInfo object contains a single instance of this object for
  109498. ** each term in the FROM clause (which is to say, for each of the
  109499. ** nested loops as implemented). The order of WhereLevel objects determines
  109500. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  109501. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  109502. */
  109503. struct WhereLevel {
  109504. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  109505. int iTabCur; /* The VDBE cursor used to access the table */
  109506. int iIdxCur; /* The VDBE cursor used to access pIdx */
  109507. int addrBrk; /* Jump here to break out of the loop */
  109508. int addrNxt; /* Jump here to start the next IN combination */
  109509. int addrSkip; /* Jump here for next iteration of skip-scan */
  109510. int addrCont; /* Jump here to continue with the next loop cycle */
  109511. int addrFirst; /* First instruction of interior of the loop */
  109512. int addrBody; /* Beginning of the body of this loop */
  109513. int iLikeRepCntr; /* LIKE range processing counter register */
  109514. int addrLikeRep; /* LIKE range processing address */
  109515. u8 iFrom; /* Which entry in the FROM clause */
  109516. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  109517. int p1, p2; /* Operands of the opcode used to ends the loop */
  109518. union { /* Information that depends on pWLoop->wsFlags */
  109519. struct {
  109520. int nIn; /* Number of entries in aInLoop[] */
  109521. struct InLoop {
  109522. int iCur; /* The VDBE cursor used by this IN operator */
  109523. int addrInTop; /* Top of the IN loop */
  109524. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  109525. } *aInLoop; /* Information about each nested IN operator */
  109526. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  109527. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  109528. } u;
  109529. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  109530. Bitmask notReady; /* FROM entries not usable at this level */
  109531. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  109532. int addrVisit; /* Address at which row is visited */
  109533. #endif
  109534. };
  109535. /*
  109536. ** Each instance of this object represents an algorithm for evaluating one
  109537. ** term of a join. Every term of the FROM clause will have at least
  109538. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  109539. ** prevent a query solution - which is an error) and many terms of the
  109540. ** FROM clause will have multiple WhereLoop objects, each describing a
  109541. ** potential way of implementing that FROM-clause term, together with
  109542. ** dependencies and cost estimates for using the chosen algorithm.
  109543. **
  109544. ** Query planning consists of building up a collection of these WhereLoop
  109545. ** objects, then computing a particular sequence of WhereLoop objects, with
  109546. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  109547. ** and that minimize the overall cost.
  109548. */
  109549. struct WhereLoop {
  109550. Bitmask prereq; /* Bitmask of other loops that must run first */
  109551. Bitmask maskSelf; /* Bitmask identifying table iTab */
  109552. #ifdef SQLITE_DEBUG
  109553. char cId; /* Symbolic ID of this loop for debugging use */
  109554. #endif
  109555. u8 iTab; /* Position in FROM clause of table for this loop */
  109556. u8 iSortIdx; /* Sorting index number. 0==None */
  109557. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  109558. LogEst rRun; /* Cost of running each loop */
  109559. LogEst nOut; /* Estimated number of output rows */
  109560. union {
  109561. struct { /* Information for internal btree tables */
  109562. u16 nEq; /* Number of equality constraints */
  109563. Index *pIndex; /* Index used, or NULL */
  109564. } btree;
  109565. struct { /* Information for virtual tables */
  109566. int idxNum; /* Index number */
  109567. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  109568. i8 isOrdered; /* True if satisfies ORDER BY */
  109569. u16 omitMask; /* Terms that may be omitted */
  109570. char *idxStr; /* Index identifier string */
  109571. } vtab;
  109572. } u;
  109573. u32 wsFlags; /* WHERE_* flags describing the plan */
  109574. u16 nLTerm; /* Number of entries in aLTerm[] */
  109575. u16 nSkip; /* Number of NULL aLTerm[] entries */
  109576. /**** whereLoopXfer() copies fields above ***********************/
  109577. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  109578. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  109579. WhereTerm **aLTerm; /* WhereTerms used */
  109580. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  109581. WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
  109582. };
  109583. /* This object holds the prerequisites and the cost of running a
  109584. ** subquery on one operand of an OR operator in the WHERE clause.
  109585. ** See WhereOrSet for additional information
  109586. */
  109587. struct WhereOrCost {
  109588. Bitmask prereq; /* Prerequisites */
  109589. LogEst rRun; /* Cost of running this subquery */
  109590. LogEst nOut; /* Number of outputs for this subquery */
  109591. };
  109592. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  109593. ** correspond to the subquery(s) of OR-clause processing. Only the
  109594. ** best N_OR_COST elements are retained.
  109595. */
  109596. #define N_OR_COST 3
  109597. struct WhereOrSet {
  109598. u16 n; /* Number of valid a[] entries */
  109599. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  109600. };
  109601. /*
  109602. ** Each instance of this object holds a sequence of WhereLoop objects
  109603. ** that implement some or all of a query plan.
  109604. **
  109605. ** Think of each WhereLoop object as a node in a graph with arcs
  109606. ** showing dependencies and costs for travelling between nodes. (That is
  109607. ** not a completely accurate description because WhereLoop costs are a
  109608. ** vector, not a scalar, and because dependencies are many-to-one, not
  109609. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  109610. ** Then a WherePath object is a path through the graph that visits some
  109611. ** or all of the WhereLoop objects once.
  109612. **
  109613. ** The "solver" works by creating the N best WherePath objects of length
  109614. ** 1. Then using those as a basis to compute the N best WherePath objects
  109615. ** of length 2. And so forth until the length of WherePaths equals the
  109616. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  109617. ** at the end is the chosen query plan.
  109618. */
  109619. struct WherePath {
  109620. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  109621. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  109622. LogEst nRow; /* Estimated number of rows generated by this path */
  109623. LogEst rCost; /* Total cost of this path */
  109624. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  109625. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  109626. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  109627. };
  109628. /*
  109629. ** The query generator uses an array of instances of this structure to
  109630. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  109631. ** clause subexpression is separated from the others by AND operators,
  109632. ** usually, or sometimes subexpressions separated by OR.
  109633. **
  109634. ** All WhereTerms are collected into a single WhereClause structure.
  109635. ** The following identity holds:
  109636. **
  109637. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  109638. **
  109639. ** When a term is of the form:
  109640. **
  109641. ** X <op> <expr>
  109642. **
  109643. ** where X is a column name and <op> is one of certain operators,
  109644. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  109645. ** cursor number and column number for X. WhereTerm.eOperator records
  109646. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  109647. ** use of a bitmask encoding for the operator allows us to search
  109648. ** quickly for terms that match any of several different operators.
  109649. **
  109650. ** A WhereTerm might also be two or more subterms connected by OR:
  109651. **
  109652. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  109653. **
  109654. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  109655. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  109656. ** is collected about the OR clause.
  109657. **
  109658. ** If a term in the WHERE clause does not match either of the two previous
  109659. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  109660. ** to the original subexpression content and wtFlags is set up appropriately
  109661. ** but no other fields in the WhereTerm object are meaningful.
  109662. **
  109663. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  109664. ** but they do so indirectly. A single WhereMaskSet structure translates
  109665. ** cursor number into bits and the translated bit is stored in the prereq
  109666. ** fields. The translation is used in order to maximize the number of
  109667. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  109668. ** spread out over the non-negative integers. For example, the cursor
  109669. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  109670. ** translates these sparse cursor numbers into consecutive integers
  109671. ** beginning with 0 in order to make the best possible use of the available
  109672. ** bits in the Bitmask. So, in the example above, the cursor numbers
  109673. ** would be mapped into integers 0 through 7.
  109674. **
  109675. ** The number of terms in a join is limited by the number of bits
  109676. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  109677. ** is only able to process joins with 64 or fewer tables.
  109678. */
  109679. struct WhereTerm {
  109680. Expr *pExpr; /* Pointer to the subexpression that is this term */
  109681. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  109682. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  109683. union {
  109684. int leftColumn; /* Column number of X in "X <op> <expr>" */
  109685. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  109686. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  109687. } u;
  109688. LogEst truthProb; /* Probability of truth for this expression */
  109689. u16 eOperator; /* A WO_xx value describing <op> */
  109690. u16 wtFlags; /* TERM_xxx bit flags. See below */
  109691. u8 nChild; /* Number of children that must disable us */
  109692. WhereClause *pWC; /* The clause this term is part of */
  109693. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  109694. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  109695. };
  109696. /*
  109697. ** Allowed values of WhereTerm.wtFlags
  109698. */
  109699. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  109700. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  109701. #define TERM_CODED 0x04 /* This term is already coded */
  109702. #define TERM_COPIED 0x08 /* Has a child */
  109703. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  109704. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  109705. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  109706. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  109707. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  109708. #else
  109709. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  109710. #endif
  109711. #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
  109712. #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
  109713. #define TERM_LIKE 0x400 /* The original LIKE operator */
  109714. #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
  109715. /*
  109716. ** An instance of the WhereScan object is used as an iterator for locating
  109717. ** terms in the WHERE clause that are useful to the query planner.
  109718. */
  109719. struct WhereScan {
  109720. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  109721. WhereClause *pWC; /* WhereClause currently being scanned */
  109722. char *zCollName; /* Required collating sequence, if not NULL */
  109723. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  109724. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  109725. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  109726. u32 opMask; /* Acceptable operators */
  109727. int k; /* Resume scanning at this->pWC->a[this->k] */
  109728. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  109729. };
  109730. /*
  109731. ** An instance of the following structure holds all information about a
  109732. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  109733. **
  109734. ** Explanation of pOuter: For a WHERE clause of the form
  109735. **
  109736. ** a AND ((b AND c) OR (d AND e)) AND f
  109737. **
  109738. ** There are separate WhereClause objects for the whole clause and for
  109739. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  109740. ** subclauses points to the WhereClause object for the whole clause.
  109741. */
  109742. struct WhereClause {
  109743. WhereInfo *pWInfo; /* WHERE clause processing context */
  109744. WhereClause *pOuter; /* Outer conjunction */
  109745. u8 op; /* Split operator. TK_AND or TK_OR */
  109746. int nTerm; /* Number of terms */
  109747. int nSlot; /* Number of entries in a[] */
  109748. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  109749. #if defined(SQLITE_SMALL_STACK)
  109750. WhereTerm aStatic[1]; /* Initial static space for a[] */
  109751. #else
  109752. WhereTerm aStatic[8]; /* Initial static space for a[] */
  109753. #endif
  109754. };
  109755. /*
  109756. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  109757. ** a dynamically allocated instance of the following structure.
  109758. */
  109759. struct WhereOrInfo {
  109760. WhereClause wc; /* Decomposition into subterms */
  109761. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  109762. };
  109763. /*
  109764. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  109765. ** a dynamically allocated instance of the following structure.
  109766. */
  109767. struct WhereAndInfo {
  109768. WhereClause wc; /* The subexpression broken out */
  109769. };
  109770. /*
  109771. ** An instance of the following structure keeps track of a mapping
  109772. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  109773. **
  109774. ** The VDBE cursor numbers are small integers contained in
  109775. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  109776. ** clause, the cursor numbers might not begin with 0 and they might
  109777. ** contain gaps in the numbering sequence. But we want to make maximum
  109778. ** use of the bits in our bitmasks. This structure provides a mapping
  109779. ** from the sparse cursor numbers into consecutive integers beginning
  109780. ** with 0.
  109781. **
  109782. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  109783. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  109784. **
  109785. ** For example, if the WHERE clause expression used these VDBE
  109786. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  109787. ** would map those cursor numbers into bits 0 through 5.
  109788. **
  109789. ** Note that the mapping is not necessarily ordered. In the example
  109790. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  109791. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  109792. ** does not really matter. What is important is that sparse cursor
  109793. ** numbers all get mapped into bit numbers that begin with 0 and contain
  109794. ** no gaps.
  109795. */
  109796. struct WhereMaskSet {
  109797. int n; /* Number of assigned cursor values */
  109798. int ix[BMS]; /* Cursor assigned to each bit */
  109799. };
  109800. /*
  109801. ** Initialize a WhereMaskSet object
  109802. */
  109803. #define initMaskSet(P) (P)->n=0
  109804. /*
  109805. ** This object is a convenience wrapper holding all information needed
  109806. ** to construct WhereLoop objects for a particular query.
  109807. */
  109808. struct WhereLoopBuilder {
  109809. WhereInfo *pWInfo; /* Information about this WHERE */
  109810. WhereClause *pWC; /* WHERE clause terms */
  109811. ExprList *pOrderBy; /* ORDER BY clause */
  109812. WhereLoop *pNew; /* Template WhereLoop */
  109813. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  109814. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  109815. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  109816. int nRecValid; /* Number of valid fields currently in pRec */
  109817. #endif
  109818. };
  109819. /*
  109820. ** The WHERE clause processing routine has two halves. The
  109821. ** first part does the start of the WHERE loop and the second
  109822. ** half does the tail of the WHERE loop. An instance of
  109823. ** this structure is returned by the first half and passed
  109824. ** into the second half to give some continuity.
  109825. **
  109826. ** An instance of this object holds the complete state of the query
  109827. ** planner.
  109828. */
  109829. struct WhereInfo {
  109830. Parse *pParse; /* Parsing and code generating context */
  109831. SrcList *pTabList; /* List of tables in the join */
  109832. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  109833. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  109834. WhereLoop *pLoops; /* List of all WhereLoop objects */
  109835. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  109836. LogEst nRowOut; /* Estimated number of output rows */
  109837. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  109838. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  109839. u8 sorted; /* True if really sorted (not just grouped) */
  109840. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  109841. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  109842. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  109843. u8 nLevel; /* Number of nested loop */
  109844. int iTop; /* The very beginning of the WHERE loop */
  109845. int iContinue; /* Jump here to continue with next record */
  109846. int iBreak; /* Jump here to break out of the loop */
  109847. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  109848. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  109849. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  109850. WhereClause sWC; /* Decomposition of the WHERE clause */
  109851. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  109852. };
  109853. /*
  109854. ** Private interfaces - callable only by other where.c routines.
  109855. **
  109856. ** where.c:
  109857. */
  109858. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet*,int);
  109859. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  109860. WhereClause *pWC, /* The WHERE clause to be searched */
  109861. int iCur, /* Cursor number of LHS */
  109862. int iColumn, /* Column number of LHS */
  109863. Bitmask notReady, /* RHS must not overlap with this mask */
  109864. u32 op, /* Mask of WO_xx values describing operator */
  109865. Index *pIdx /* Must be compatible with this index, if not NULL */
  109866. );
  109867. /* wherecode.c: */
  109868. #ifndef SQLITE_OMIT_EXPLAIN
  109869. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  109870. Parse *pParse, /* Parse context */
  109871. SrcList *pTabList, /* Table list this loop refers to */
  109872. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  109873. int iLevel, /* Value for "level" column of output */
  109874. int iFrom, /* Value for "from" column of output */
  109875. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  109876. );
  109877. #else
  109878. # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
  109879. #endif /* SQLITE_OMIT_EXPLAIN */
  109880. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  109881. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  109882. Vdbe *v, /* Vdbe to add scanstatus entry to */
  109883. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  109884. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  109885. int addrExplain /* Address of OP_Explain (or 0) */
  109886. );
  109887. #else
  109888. # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
  109889. #endif
  109890. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  109891. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  109892. int iLevel, /* Which level of pWInfo->a[] should be coded */
  109893. Bitmask notReady /* Which tables are currently available */
  109894. );
  109895. /* whereexpr.c: */
  109896. SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause*,WhereInfo*);
  109897. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause*);
  109898. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause*,Expr*,u8);
  109899. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet*, Expr*);
  109900. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet*, ExprList*);
  109901. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList*, WhereClause*);
  109902. /*
  109903. ** Bitmasks for the operators on WhereTerm objects. These are all
  109904. ** operators that are of interest to the query planner. An
  109905. ** OR-ed combination of these values can be used when searching for
  109906. ** particular WhereTerms within a WhereClause.
  109907. */
  109908. #define WO_IN 0x0001
  109909. #define WO_EQ 0x0002
  109910. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  109911. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  109912. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  109913. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  109914. #define WO_MATCH 0x0040
  109915. #define WO_IS 0x0080
  109916. #define WO_ISNULL 0x0100
  109917. #define WO_OR 0x0200 /* Two or more OR-connected terms */
  109918. #define WO_AND 0x0400 /* Two or more AND-connected terms */
  109919. #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
  109920. #define WO_NOOP 0x1000 /* This term does not restrict search space */
  109921. #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
  109922. #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
  109923. /*
  109924. ** These are definitions of bits in the WhereLoop.wsFlags field.
  109925. ** The particular combination of bits in each WhereLoop help to
  109926. ** determine the algorithm that WhereLoop represents.
  109927. */
  109928. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  109929. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  109930. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  109931. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  109932. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  109933. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  109934. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  109935. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  109936. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  109937. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  109938. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  109939. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  109940. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  109941. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  109942. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  109943. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  109944. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  109945. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  109946. #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
  109947. /************** End of whereInt.h ********************************************/
  109948. /************** Continuing where we left off in wherecode.c ******************/
  109949. #ifndef SQLITE_OMIT_EXPLAIN
  109950. /*
  109951. ** This routine is a helper for explainIndexRange() below
  109952. **
  109953. ** pStr holds the text of an expression that we are building up one term
  109954. ** at a time. This routine adds a new term to the end of the expression.
  109955. ** Terms are separated by AND so add the "AND" text for second and subsequent
  109956. ** terms only.
  109957. */
  109958. static void explainAppendTerm(
  109959. StrAccum *pStr, /* The text expression being built */
  109960. int iTerm, /* Index of this term. First is zero */
  109961. const char *zColumn, /* Name of the column */
  109962. const char *zOp /* Name of the operator */
  109963. ){
  109964. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  109965. sqlite3StrAccumAppendAll(pStr, zColumn);
  109966. sqlite3StrAccumAppend(pStr, zOp, 1);
  109967. sqlite3StrAccumAppend(pStr, "?", 1);
  109968. }
  109969. /*
  109970. ** Argument pLevel describes a strategy for scanning table pTab. This
  109971. ** function appends text to pStr that describes the subset of table
  109972. ** rows scanned by the strategy in the form of an SQL expression.
  109973. **
  109974. ** For example, if the query:
  109975. **
  109976. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  109977. **
  109978. ** is run and there is an index on (a, b), then this function returns a
  109979. ** string similar to:
  109980. **
  109981. ** "a=? AND b>?"
  109982. */
  109983. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
  109984. Index *pIndex = pLoop->u.btree.pIndex;
  109985. u16 nEq = pLoop->u.btree.nEq;
  109986. u16 nSkip = pLoop->nSkip;
  109987. int i, j;
  109988. Column *aCol = pTab->aCol;
  109989. i16 *aiColumn = pIndex->aiColumn;
  109990. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  109991. sqlite3StrAccumAppend(pStr, " (", 2);
  109992. for(i=0; i<nEq; i++){
  109993. char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
  109994. if( i>=nSkip ){
  109995. explainAppendTerm(pStr, i, z, "=");
  109996. }else{
  109997. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  109998. sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
  109999. }
  110000. }
  110001. j = i;
  110002. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  110003. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  110004. explainAppendTerm(pStr, i++, z, ">");
  110005. }
  110006. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  110007. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  110008. explainAppendTerm(pStr, i, z, "<");
  110009. }
  110010. sqlite3StrAccumAppend(pStr, ")", 1);
  110011. }
  110012. /*
  110013. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  110014. ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
  110015. ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
  110016. ** is added to the output to describe the table scan strategy in pLevel.
  110017. **
  110018. ** If an OP_Explain opcode is added to the VM, its address is returned.
  110019. ** Otherwise, if no OP_Explain is coded, zero is returned.
  110020. */
  110021. SQLITE_PRIVATE int sqlite3WhereExplainOneScan(
  110022. Parse *pParse, /* Parse context */
  110023. SrcList *pTabList, /* Table list this loop refers to */
  110024. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  110025. int iLevel, /* Value for "level" column of output */
  110026. int iFrom, /* Value for "from" column of output */
  110027. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  110028. ){
  110029. int ret = 0;
  110030. #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
  110031. if( pParse->explain==2 )
  110032. #endif
  110033. {
  110034. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  110035. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  110036. sqlite3 *db = pParse->db; /* Database handle */
  110037. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  110038. int isSearch; /* True for a SEARCH. False for SCAN. */
  110039. WhereLoop *pLoop; /* The controlling WhereLoop object */
  110040. u32 flags; /* Flags that describe this loop */
  110041. char *zMsg; /* Text to add to EQP output */
  110042. StrAccum str; /* EQP output string */
  110043. char zBuf[100]; /* Initial space for EQP output string */
  110044. pLoop = pLevel->pWLoop;
  110045. flags = pLoop->wsFlags;
  110046. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
  110047. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  110048. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  110049. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  110050. sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  110051. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  110052. if( pItem->pSelect ){
  110053. sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
  110054. }else{
  110055. sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
  110056. }
  110057. if( pItem->zAlias ){
  110058. sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
  110059. }
  110060. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  110061. const char *zFmt = 0;
  110062. Index *pIdx;
  110063. assert( pLoop->u.btree.pIndex!=0 );
  110064. pIdx = pLoop->u.btree.pIndex;
  110065. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  110066. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  110067. if( isSearch ){
  110068. zFmt = "PRIMARY KEY";
  110069. }
  110070. }else if( flags & WHERE_PARTIALIDX ){
  110071. zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
  110072. }else if( flags & WHERE_AUTO_INDEX ){
  110073. zFmt = "AUTOMATIC COVERING INDEX";
  110074. }else if( flags & WHERE_IDX_ONLY ){
  110075. zFmt = "COVERING INDEX %s";
  110076. }else{
  110077. zFmt = "INDEX %s";
  110078. }
  110079. if( zFmt ){
  110080. sqlite3StrAccumAppend(&str, " USING ", 7);
  110081. sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
  110082. explainIndexRange(&str, pLoop, pItem->pTab);
  110083. }
  110084. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  110085. const char *zRange;
  110086. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  110087. zRange = "(rowid=?)";
  110088. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  110089. zRange = "(rowid>? AND rowid<?)";
  110090. }else if( flags&WHERE_BTM_LIMIT ){
  110091. zRange = "(rowid>?)";
  110092. }else{
  110093. assert( flags&WHERE_TOP_LIMIT);
  110094. zRange = "(rowid<?)";
  110095. }
  110096. sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
  110097. sqlite3StrAccumAppendAll(&str, zRange);
  110098. }
  110099. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110100. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  110101. sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
  110102. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  110103. }
  110104. #endif
  110105. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  110106. if( pLoop->nOut>=10 ){
  110107. sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  110108. }else{
  110109. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  110110. }
  110111. #endif
  110112. zMsg = sqlite3StrAccumFinish(&str);
  110113. ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
  110114. }
  110115. return ret;
  110116. }
  110117. #endif /* SQLITE_OMIT_EXPLAIN */
  110118. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  110119. /*
  110120. ** Configure the VM passed as the first argument with an
  110121. ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
  110122. ** implement level pLvl. Argument pSrclist is a pointer to the FROM
  110123. ** clause that the scan reads data from.
  110124. **
  110125. ** If argument addrExplain is not 0, it must be the address of an
  110126. ** OP_Explain instruction that describes the same loop.
  110127. */
  110128. SQLITE_PRIVATE void sqlite3WhereAddScanStatus(
  110129. Vdbe *v, /* Vdbe to add scanstatus entry to */
  110130. SrcList *pSrclist, /* FROM clause pLvl reads data from */
  110131. WhereLevel *pLvl, /* Level to add scanstatus() entry for */
  110132. int addrExplain /* Address of OP_Explain (or 0) */
  110133. ){
  110134. const char *zObj = 0;
  110135. WhereLoop *pLoop = pLvl->pWLoop;
  110136. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
  110137. zObj = pLoop->u.btree.pIndex->zName;
  110138. }else{
  110139. zObj = pSrclist->a[pLvl->iFrom].zName;
  110140. }
  110141. sqlite3VdbeScanStatus(
  110142. v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
  110143. );
  110144. }
  110145. #endif
  110146. /*
  110147. ** Disable a term in the WHERE clause. Except, do not disable the term
  110148. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  110149. ** or USING clause of that join.
  110150. **
  110151. ** Consider the term t2.z='ok' in the following queries:
  110152. **
  110153. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  110154. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  110155. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  110156. **
  110157. ** The t2.z='ok' is disabled in the in (2) because it originates
  110158. ** in the ON clause. The term is disabled in (3) because it is not part
  110159. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  110160. **
  110161. ** Disabling a term causes that term to not be tested in the inner loop
  110162. ** of the join. Disabling is an optimization. When terms are satisfied
  110163. ** by indices, we disable them to prevent redundant tests in the inner
  110164. ** loop. We would get the correct results if nothing were ever disabled,
  110165. ** but joins might run a little slower. The trick is to disable as much
  110166. ** as we can without disabling too much. If we disabled in (1), we'd get
  110167. ** the wrong answer. See ticket #813.
  110168. **
  110169. ** If all the children of a term are disabled, then that term is also
  110170. ** automatically disabled. In this way, terms get disabled if derived
  110171. ** virtual terms are tested first. For example:
  110172. **
  110173. ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
  110174. ** \___________/ \______/ \_____/
  110175. ** parent child1 child2
  110176. **
  110177. ** Only the parent term was in the original WHERE clause. The child1
  110178. ** and child2 terms were added by the LIKE optimization. If both of
  110179. ** the virtual child terms are valid, then testing of the parent can be
  110180. ** skipped.
  110181. **
  110182. ** Usually the parent term is marked as TERM_CODED. But if the parent
  110183. ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
  110184. ** The TERM_LIKECOND marking indicates that the term should be coded inside
  110185. ** a conditional such that is only evaluated on the second pass of a
  110186. ** LIKE-optimization loop, when scanning BLOBs instead of strings.
  110187. */
  110188. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  110189. int nLoop = 0;
  110190. while( pTerm
  110191. && (pTerm->wtFlags & TERM_CODED)==0
  110192. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  110193. && (pLevel->notReady & pTerm->prereqAll)==0
  110194. ){
  110195. if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
  110196. pTerm->wtFlags |= TERM_LIKECOND;
  110197. }else{
  110198. pTerm->wtFlags |= TERM_CODED;
  110199. }
  110200. if( pTerm->iParent<0 ) break;
  110201. pTerm = &pTerm->pWC->a[pTerm->iParent];
  110202. pTerm->nChild--;
  110203. if( pTerm->nChild!=0 ) break;
  110204. nLoop++;
  110205. }
  110206. }
  110207. /*
  110208. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  110209. ** to the n registers starting at base.
  110210. **
  110211. ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
  110212. ** beginning and end of zAff are ignored. If all entries in zAff are
  110213. ** SQLITE_AFF_BLOB, then no code gets generated.
  110214. **
  110215. ** This routine makes its own copy of zAff so that the caller is free
  110216. ** to modify zAff after this routine returns.
  110217. */
  110218. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  110219. Vdbe *v = pParse->pVdbe;
  110220. if( zAff==0 ){
  110221. assert( pParse->db->mallocFailed );
  110222. return;
  110223. }
  110224. assert( v!=0 );
  110225. /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
  110226. ** and end of the affinity string.
  110227. */
  110228. while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
  110229. n--;
  110230. base++;
  110231. zAff++;
  110232. }
  110233. while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
  110234. n--;
  110235. }
  110236. /* Code the OP_Affinity opcode if there is anything left to do. */
  110237. if( n>0 ){
  110238. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  110239. sqlite3VdbeChangeP4(v, -1, zAff, n);
  110240. sqlite3ExprCacheAffinityChange(pParse, base, n);
  110241. }
  110242. }
  110243. /*
  110244. ** Generate code for a single equality term of the WHERE clause. An equality
  110245. ** term can be either X=expr or X IN (...). pTerm is the term to be
  110246. ** coded.
  110247. **
  110248. ** The current value for the constraint is left in register iReg.
  110249. **
  110250. ** For a constraint of the form X=expr, the expression is evaluated and its
  110251. ** result is left on the stack. For constraints of the form X IN (...)
  110252. ** this routine sets up a loop that will iterate over all values of X.
  110253. */
  110254. static int codeEqualityTerm(
  110255. Parse *pParse, /* The parsing context */
  110256. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  110257. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  110258. int iEq, /* Index of the equality term within this level */
  110259. int bRev, /* True for reverse-order IN operations */
  110260. int iTarget /* Attempt to leave results in this register */
  110261. ){
  110262. Expr *pX = pTerm->pExpr;
  110263. Vdbe *v = pParse->pVdbe;
  110264. int iReg; /* Register holding results */
  110265. assert( iTarget>0 );
  110266. if( pX->op==TK_EQ || pX->op==TK_IS ){
  110267. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  110268. }else if( pX->op==TK_ISNULL ){
  110269. iReg = iTarget;
  110270. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  110271. #ifndef SQLITE_OMIT_SUBQUERY
  110272. }else{
  110273. int eType;
  110274. int iTab;
  110275. struct InLoop *pIn;
  110276. WhereLoop *pLoop = pLevel->pWLoop;
  110277. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  110278. && pLoop->u.btree.pIndex!=0
  110279. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  110280. ){
  110281. testcase( iEq==0 );
  110282. testcase( bRev );
  110283. bRev = !bRev;
  110284. }
  110285. assert( pX->op==TK_IN );
  110286. iReg = iTarget;
  110287. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
  110288. if( eType==IN_INDEX_INDEX_DESC ){
  110289. testcase( bRev );
  110290. bRev = !bRev;
  110291. }
  110292. iTab = pX->iTable;
  110293. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  110294. VdbeCoverageIf(v, bRev);
  110295. VdbeCoverageIf(v, !bRev);
  110296. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  110297. pLoop->wsFlags |= WHERE_IN_ABLE;
  110298. if( pLevel->u.in.nIn==0 ){
  110299. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  110300. }
  110301. pLevel->u.in.nIn++;
  110302. pLevel->u.in.aInLoop =
  110303. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  110304. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  110305. pIn = pLevel->u.in.aInLoop;
  110306. if( pIn ){
  110307. pIn += pLevel->u.in.nIn - 1;
  110308. pIn->iCur = iTab;
  110309. if( eType==IN_INDEX_ROWID ){
  110310. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  110311. }else{
  110312. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  110313. }
  110314. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  110315. sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  110316. }else{
  110317. pLevel->u.in.nIn = 0;
  110318. }
  110319. #endif
  110320. }
  110321. disableTerm(pLevel, pTerm);
  110322. return iReg;
  110323. }
  110324. /*
  110325. ** Generate code that will evaluate all == and IN constraints for an
  110326. ** index scan.
  110327. **
  110328. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  110329. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  110330. ** The index has as many as three equality constraints, but in this
  110331. ** example, the third "c" value is an inequality. So only two
  110332. ** constraints are coded. This routine will generate code to evaluate
  110333. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  110334. ** in consecutive registers and the index of the first register is returned.
  110335. **
  110336. ** In the example above nEq==2. But this subroutine works for any value
  110337. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  110338. ** The only thing it does is allocate the pLevel->iMem memory cell and
  110339. ** compute the affinity string.
  110340. **
  110341. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  110342. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  110343. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  110344. ** occurs after the nEq quality constraints.
  110345. **
  110346. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  110347. ** the index of the first memory cell in that range. The code that
  110348. ** calls this routine will use that memory range to store keys for
  110349. ** start and termination conditions of the loop.
  110350. ** key value of the loop. If one or more IN operators appear, then
  110351. ** this routine allocates an additional nEq memory cells for internal
  110352. ** use.
  110353. **
  110354. ** Before returning, *pzAff is set to point to a buffer containing a
  110355. ** copy of the column affinity string of the index allocated using
  110356. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  110357. ** with equality constraints that use BLOB or NONE affinity are set to
  110358. ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
  110359. **
  110360. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  110361. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  110362. **
  110363. ** In the example above, the index on t1(a) has TEXT affinity. But since
  110364. ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
  110365. ** no conversion should be attempted before using a t2.b value as part of
  110366. ** a key to search the index. Hence the first byte in the returned affinity
  110367. ** string in this example would be set to SQLITE_AFF_BLOB.
  110368. */
  110369. static int codeAllEqualityTerms(
  110370. Parse *pParse, /* Parsing context */
  110371. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  110372. int bRev, /* Reverse the order of IN operators */
  110373. int nExtraReg, /* Number of extra registers to allocate */
  110374. char **pzAff /* OUT: Set to point to affinity string */
  110375. ){
  110376. u16 nEq; /* The number of == or IN constraints to code */
  110377. u16 nSkip; /* Number of left-most columns to skip */
  110378. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  110379. Index *pIdx; /* The index being used for this loop */
  110380. WhereTerm *pTerm; /* A single constraint term */
  110381. WhereLoop *pLoop; /* The WhereLoop object */
  110382. int j; /* Loop counter */
  110383. int regBase; /* Base register */
  110384. int nReg; /* Number of registers to allocate */
  110385. char *zAff; /* Affinity string to return */
  110386. /* This module is only called on query plans that use an index. */
  110387. pLoop = pLevel->pWLoop;
  110388. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  110389. nEq = pLoop->u.btree.nEq;
  110390. nSkip = pLoop->nSkip;
  110391. pIdx = pLoop->u.btree.pIndex;
  110392. assert( pIdx!=0 );
  110393. /* Figure out how many memory cells we will need then allocate them.
  110394. */
  110395. regBase = pParse->nMem + 1;
  110396. nReg = pLoop->u.btree.nEq + nExtraReg;
  110397. pParse->nMem += nReg;
  110398. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  110399. if( !zAff ){
  110400. pParse->db->mallocFailed = 1;
  110401. }
  110402. if( nSkip ){
  110403. int iIdxCur = pLevel->iIdxCur;
  110404. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  110405. VdbeCoverageIf(v, bRev==0);
  110406. VdbeCoverageIf(v, bRev!=0);
  110407. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  110408. j = sqlite3VdbeAddOp0(v, OP_Goto);
  110409. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  110410. iIdxCur, 0, regBase, nSkip);
  110411. VdbeCoverageIf(v, bRev==0);
  110412. VdbeCoverageIf(v, bRev!=0);
  110413. sqlite3VdbeJumpHere(v, j);
  110414. for(j=0; j<nSkip; j++){
  110415. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  110416. assert( pIdx->aiColumn[j]>=0 );
  110417. VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
  110418. }
  110419. }
  110420. /* Evaluate the equality constraints
  110421. */
  110422. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  110423. for(j=nSkip; j<nEq; j++){
  110424. int r1;
  110425. pTerm = pLoop->aLTerm[j];
  110426. assert( pTerm!=0 );
  110427. /* The following testcase is true for indices with redundant columns.
  110428. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  110429. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  110430. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  110431. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  110432. if( r1!=regBase+j ){
  110433. if( nReg==1 ){
  110434. sqlite3ReleaseTempReg(pParse, regBase);
  110435. regBase = r1;
  110436. }else{
  110437. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  110438. }
  110439. }
  110440. testcase( pTerm->eOperator & WO_ISNULL );
  110441. testcase( pTerm->eOperator & WO_IN );
  110442. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  110443. Expr *pRight = pTerm->pExpr->pRight;
  110444. if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
  110445. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  110446. VdbeCoverage(v);
  110447. }
  110448. if( zAff ){
  110449. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
  110450. zAff[j] = SQLITE_AFF_BLOB;
  110451. }
  110452. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  110453. zAff[j] = SQLITE_AFF_BLOB;
  110454. }
  110455. }
  110456. }
  110457. }
  110458. *pzAff = zAff;
  110459. return regBase;
  110460. }
  110461. /*
  110462. ** If the most recently coded instruction is a constant range contraint
  110463. ** that originated from the LIKE optimization, then change the P3 to be
  110464. ** pLoop->iLikeRepCntr and set P5.
  110465. **
  110466. ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
  110467. ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
  110468. ** scan loop run twice, once for strings and a second time for BLOBs.
  110469. ** The OP_String opcodes on the second pass convert the upper and lower
  110470. ** bound string contants to blobs. This routine makes the necessary changes
  110471. ** to the OP_String opcodes for that to happen.
  110472. */
  110473. static void whereLikeOptimizationStringFixup(
  110474. Vdbe *v, /* prepared statement under construction */
  110475. WhereLevel *pLevel, /* The loop that contains the LIKE operator */
  110476. WhereTerm *pTerm /* The upper or lower bound just coded */
  110477. ){
  110478. if( pTerm->wtFlags & TERM_LIKEOPT ){
  110479. VdbeOp *pOp;
  110480. assert( pLevel->iLikeRepCntr>0 );
  110481. pOp = sqlite3VdbeGetOp(v, -1);
  110482. assert( pOp!=0 );
  110483. assert( pOp->opcode==OP_String8
  110484. || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
  110485. pOp->p3 = pLevel->iLikeRepCntr;
  110486. pOp->p5 = 1;
  110487. }
  110488. }
  110489. /*
  110490. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  110491. ** implementation described by pWInfo.
  110492. */
  110493. SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(
  110494. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  110495. int iLevel, /* Which level of pWInfo->a[] should be coded */
  110496. Bitmask notReady /* Which tables are currently available */
  110497. ){
  110498. int j, k; /* Loop counters */
  110499. int iCur; /* The VDBE cursor for the table */
  110500. int addrNxt; /* Where to jump to continue with the next IN case */
  110501. int omitTable; /* True if we use the index only */
  110502. int bRev; /* True if we need to scan in reverse order */
  110503. WhereLevel *pLevel; /* The where level to be coded */
  110504. WhereLoop *pLoop; /* The WhereLoop object being coded */
  110505. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  110506. WhereTerm *pTerm; /* A WHERE clause term */
  110507. Parse *pParse; /* Parsing context */
  110508. sqlite3 *db; /* Database connection */
  110509. Vdbe *v; /* The prepared stmt under constructions */
  110510. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  110511. int addrBrk; /* Jump here to break out of the loop */
  110512. int addrCont; /* Jump here to continue with next cycle */
  110513. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  110514. int iReleaseReg = 0; /* Temp register to free before returning */
  110515. pParse = pWInfo->pParse;
  110516. v = pParse->pVdbe;
  110517. pWC = &pWInfo->sWC;
  110518. db = pParse->db;
  110519. pLevel = &pWInfo->a[iLevel];
  110520. pLoop = pLevel->pWLoop;
  110521. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  110522. iCur = pTabItem->iCursor;
  110523. pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  110524. bRev = (pWInfo->revMask>>iLevel)&1;
  110525. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  110526. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  110527. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  110528. /* Create labels for the "break" and "continue" instructions
  110529. ** for the current loop. Jump to addrBrk to break out of a loop.
  110530. ** Jump to cont to go immediately to the next iteration of the
  110531. ** loop.
  110532. **
  110533. ** When there is an IN operator, we also have a "addrNxt" label that
  110534. ** means to continue with the next IN value combination. When
  110535. ** there are no IN operators in the constraints, the "addrNxt" label
  110536. ** is the same as "addrBrk".
  110537. */
  110538. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  110539. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  110540. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  110541. ** initialize a memory cell that records if this table matches any
  110542. ** row of the left table of the join.
  110543. */
  110544. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  110545. pLevel->iLeftJoin = ++pParse->nMem;
  110546. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  110547. VdbeComment((v, "init LEFT JOIN no-match flag"));
  110548. }
  110549. /* Special case of a FROM clause subquery implemented as a co-routine */
  110550. if( pTabItem->viaCoroutine ){
  110551. int regYield = pTabItem->regReturn;
  110552. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  110553. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  110554. VdbeCoverage(v);
  110555. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  110556. pLevel->op = OP_Goto;
  110557. }else
  110558. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110559. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  110560. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  110561. ** to access the data.
  110562. */
  110563. int iReg; /* P3 Value for OP_VFilter */
  110564. int addrNotFound;
  110565. int nConstraint = pLoop->nLTerm;
  110566. sqlite3ExprCachePush(pParse);
  110567. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  110568. addrNotFound = pLevel->addrBrk;
  110569. for(j=0; j<nConstraint; j++){
  110570. int iTarget = iReg+j+2;
  110571. pTerm = pLoop->aLTerm[j];
  110572. if( pTerm==0 ) continue;
  110573. if( pTerm->eOperator & WO_IN ){
  110574. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  110575. addrNotFound = pLevel->addrNxt;
  110576. }else{
  110577. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  110578. }
  110579. }
  110580. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  110581. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  110582. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  110583. pLoop->u.vtab.idxStr,
  110584. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  110585. VdbeCoverage(v);
  110586. pLoop->u.vtab.needFree = 0;
  110587. for(j=0; j<nConstraint && j<16; j++){
  110588. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  110589. disableTerm(pLevel, pLoop->aLTerm[j]);
  110590. }
  110591. }
  110592. pLevel->op = OP_VNext;
  110593. pLevel->p1 = iCur;
  110594. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  110595. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  110596. sqlite3ExprCachePop(pParse);
  110597. }else
  110598. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  110599. if( (pLoop->wsFlags & WHERE_IPK)!=0
  110600. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  110601. ){
  110602. /* Case 2: We can directly reference a single row using an
  110603. ** equality comparison against the ROWID field. Or
  110604. ** we reference multiple rows using a "rowid IN (...)"
  110605. ** construct.
  110606. */
  110607. assert( pLoop->u.btree.nEq==1 );
  110608. pTerm = pLoop->aLTerm[0];
  110609. assert( pTerm!=0 );
  110610. assert( pTerm->pExpr!=0 );
  110611. assert( omitTable==0 );
  110612. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  110613. iReleaseReg = ++pParse->nMem;
  110614. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  110615. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  110616. addrNxt = pLevel->addrNxt;
  110617. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  110618. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  110619. VdbeCoverage(v);
  110620. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  110621. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  110622. VdbeComment((v, "pk"));
  110623. pLevel->op = OP_Noop;
  110624. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  110625. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  110626. ){
  110627. /* Case 3: We have an inequality comparison against the ROWID field.
  110628. */
  110629. int testOp = OP_Noop;
  110630. int start;
  110631. int memEndValue = 0;
  110632. WhereTerm *pStart, *pEnd;
  110633. assert( omitTable==0 );
  110634. j = 0;
  110635. pStart = pEnd = 0;
  110636. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  110637. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  110638. assert( pStart!=0 || pEnd!=0 );
  110639. if( bRev ){
  110640. pTerm = pStart;
  110641. pStart = pEnd;
  110642. pEnd = pTerm;
  110643. }
  110644. if( pStart ){
  110645. Expr *pX; /* The expression that defines the start bound */
  110646. int r1, rTemp; /* Registers for holding the start boundary */
  110647. /* The following constant maps TK_xx codes into corresponding
  110648. ** seek opcodes. It depends on a particular ordering of TK_xx
  110649. */
  110650. const u8 aMoveOp[] = {
  110651. /* TK_GT */ OP_SeekGT,
  110652. /* TK_LE */ OP_SeekLE,
  110653. /* TK_LT */ OP_SeekLT,
  110654. /* TK_GE */ OP_SeekGE
  110655. };
  110656. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  110657. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  110658. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  110659. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  110660. testcase( pStart->wtFlags & TERM_VIRTUAL );
  110661. pX = pStart->pExpr;
  110662. assert( pX!=0 );
  110663. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  110664. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  110665. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  110666. VdbeComment((v, "pk"));
  110667. VdbeCoverageIf(v, pX->op==TK_GT);
  110668. VdbeCoverageIf(v, pX->op==TK_LE);
  110669. VdbeCoverageIf(v, pX->op==TK_LT);
  110670. VdbeCoverageIf(v, pX->op==TK_GE);
  110671. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  110672. sqlite3ReleaseTempReg(pParse, rTemp);
  110673. disableTerm(pLevel, pStart);
  110674. }else{
  110675. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  110676. VdbeCoverageIf(v, bRev==0);
  110677. VdbeCoverageIf(v, bRev!=0);
  110678. }
  110679. if( pEnd ){
  110680. Expr *pX;
  110681. pX = pEnd->pExpr;
  110682. assert( pX!=0 );
  110683. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  110684. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  110685. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  110686. memEndValue = ++pParse->nMem;
  110687. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  110688. if( pX->op==TK_LT || pX->op==TK_GT ){
  110689. testOp = bRev ? OP_Le : OP_Ge;
  110690. }else{
  110691. testOp = bRev ? OP_Lt : OP_Gt;
  110692. }
  110693. disableTerm(pLevel, pEnd);
  110694. }
  110695. start = sqlite3VdbeCurrentAddr(v);
  110696. pLevel->op = bRev ? OP_Prev : OP_Next;
  110697. pLevel->p1 = iCur;
  110698. pLevel->p2 = start;
  110699. assert( pLevel->p5==0 );
  110700. if( testOp!=OP_Noop ){
  110701. iRowidReg = ++pParse->nMem;
  110702. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  110703. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  110704. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  110705. VdbeCoverageIf(v, testOp==OP_Le);
  110706. VdbeCoverageIf(v, testOp==OP_Lt);
  110707. VdbeCoverageIf(v, testOp==OP_Ge);
  110708. VdbeCoverageIf(v, testOp==OP_Gt);
  110709. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  110710. }
  110711. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  110712. /* Case 4: A scan using an index.
  110713. **
  110714. ** The WHERE clause may contain zero or more equality
  110715. ** terms ("==" or "IN" operators) that refer to the N
  110716. ** left-most columns of the index. It may also contain
  110717. ** inequality constraints (>, <, >= or <=) on the indexed
  110718. ** column that immediately follows the N equalities. Only
  110719. ** the right-most column can be an inequality - the rest must
  110720. ** use the "==" and "IN" operators. For example, if the
  110721. ** index is on (x,y,z), then the following clauses are all
  110722. ** optimized:
  110723. **
  110724. ** x=5
  110725. ** x=5 AND y=10
  110726. ** x=5 AND y<10
  110727. ** x=5 AND y>5 AND y<10
  110728. ** x=5 AND y=5 AND z<=10
  110729. **
  110730. ** The z<10 term of the following cannot be used, only
  110731. ** the x=5 term:
  110732. **
  110733. ** x=5 AND z<10
  110734. **
  110735. ** N may be zero if there are inequality constraints.
  110736. ** If there are no inequality constraints, then N is at
  110737. ** least one.
  110738. **
  110739. ** This case is also used when there are no WHERE clause
  110740. ** constraints but an index is selected anyway, in order
  110741. ** to force the output order to conform to an ORDER BY.
  110742. */
  110743. static const u8 aStartOp[] = {
  110744. 0,
  110745. 0,
  110746. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  110747. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  110748. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  110749. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  110750. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  110751. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  110752. };
  110753. static const u8 aEndOp[] = {
  110754. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  110755. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  110756. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  110757. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  110758. };
  110759. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  110760. int regBase; /* Base register holding constraint values */
  110761. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  110762. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  110763. int startEq; /* True if range start uses ==, >= or <= */
  110764. int endEq; /* True if range end uses ==, >= or <= */
  110765. int start_constraints; /* Start of range is constrained */
  110766. int nConstraint; /* Number of constraint terms */
  110767. Index *pIdx; /* The index we will be using */
  110768. int iIdxCur; /* The VDBE cursor for the index */
  110769. int nExtraReg = 0; /* Number of extra registers needed */
  110770. int op; /* Instruction opcode */
  110771. char *zStartAff; /* Affinity for start of range constraint */
  110772. char cEndAff = 0; /* Affinity for end of range constraint */
  110773. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  110774. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  110775. pIdx = pLoop->u.btree.pIndex;
  110776. iIdxCur = pLevel->iIdxCur;
  110777. assert( nEq>=pLoop->nSkip );
  110778. /* If this loop satisfies a sort order (pOrderBy) request that
  110779. ** was passed to this function to implement a "SELECT min(x) ..."
  110780. ** query, then the caller will only allow the loop to run for
  110781. ** a single iteration. This means that the first row returned
  110782. ** should not have a NULL value stored in 'x'. If column 'x' is
  110783. ** the first one after the nEq equality constraints in the index,
  110784. ** this requires some special handling.
  110785. */
  110786. assert( pWInfo->pOrderBy==0
  110787. || pWInfo->pOrderBy->nExpr==1
  110788. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  110789. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  110790. && pWInfo->nOBSat>0
  110791. && (pIdx->nKeyCol>nEq)
  110792. ){
  110793. assert( pLoop->nSkip==0 );
  110794. bSeekPastNull = 1;
  110795. nExtraReg = 1;
  110796. }
  110797. /* Find any inequality constraint terms for the start and end
  110798. ** of the range.
  110799. */
  110800. j = nEq;
  110801. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  110802. pRangeStart = pLoop->aLTerm[j++];
  110803. nExtraReg = 1;
  110804. /* Like optimization range constraints always occur in pairs */
  110805. assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
  110806. (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
  110807. }
  110808. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  110809. pRangeEnd = pLoop->aLTerm[j++];
  110810. nExtraReg = 1;
  110811. if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
  110812. assert( pRangeStart!=0 ); /* LIKE opt constraints */
  110813. assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
  110814. pLevel->iLikeRepCntr = ++pParse->nMem;
  110815. testcase( bRev );
  110816. testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
  110817. sqlite3VdbeAddOp2(v, OP_Integer,
  110818. bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
  110819. pLevel->iLikeRepCntr);
  110820. VdbeComment((v, "LIKE loop counter"));
  110821. pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
  110822. }
  110823. if( pRangeStart==0
  110824. && (j = pIdx->aiColumn[nEq])>=0
  110825. && pIdx->pTable->aCol[j].notNull==0
  110826. ){
  110827. bSeekPastNull = 1;
  110828. }
  110829. }
  110830. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  110831. /* Generate code to evaluate all constraint terms using == or IN
  110832. ** and store the values of those terms in an array of registers
  110833. ** starting at regBase.
  110834. */
  110835. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  110836. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  110837. if( zStartAff ) cEndAff = zStartAff[nEq];
  110838. addrNxt = pLevel->addrNxt;
  110839. /* If we are doing a reverse order scan on an ascending index, or
  110840. ** a forward order scan on a descending index, interchange the
  110841. ** start and end terms (pRangeStart and pRangeEnd).
  110842. */
  110843. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  110844. || (bRev && pIdx->nKeyCol==nEq)
  110845. ){
  110846. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  110847. SWAP(u8, bSeekPastNull, bStopAtNull);
  110848. }
  110849. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  110850. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  110851. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  110852. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  110853. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  110854. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  110855. start_constraints = pRangeStart || nEq>0;
  110856. /* Seek the index cursor to the start of the range. */
  110857. nConstraint = nEq;
  110858. if( pRangeStart ){
  110859. Expr *pRight = pRangeStart->pExpr->pRight;
  110860. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  110861. whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
  110862. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  110863. && sqlite3ExprCanBeNull(pRight)
  110864. ){
  110865. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  110866. VdbeCoverage(v);
  110867. }
  110868. if( zStartAff ){
  110869. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
  110870. /* Since the comparison is to be performed with no conversions
  110871. ** applied to the operands, set the affinity to apply to pRight to
  110872. ** SQLITE_AFF_BLOB. */
  110873. zStartAff[nEq] = SQLITE_AFF_BLOB;
  110874. }
  110875. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  110876. zStartAff[nEq] = SQLITE_AFF_BLOB;
  110877. }
  110878. }
  110879. nConstraint++;
  110880. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  110881. }else if( bSeekPastNull ){
  110882. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  110883. nConstraint++;
  110884. startEq = 0;
  110885. start_constraints = 1;
  110886. }
  110887. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  110888. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  110889. assert( op!=0 );
  110890. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  110891. VdbeCoverage(v);
  110892. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  110893. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  110894. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  110895. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  110896. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  110897. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  110898. /* Load the value for the inequality constraint at the end of the
  110899. ** range (if any).
  110900. */
  110901. nConstraint = nEq;
  110902. if( pRangeEnd ){
  110903. Expr *pRight = pRangeEnd->pExpr->pRight;
  110904. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  110905. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  110906. whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
  110907. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  110908. && sqlite3ExprCanBeNull(pRight)
  110909. ){
  110910. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  110911. VdbeCoverage(v);
  110912. }
  110913. if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
  110914. && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  110915. ){
  110916. codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  110917. }
  110918. nConstraint++;
  110919. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  110920. }else if( bStopAtNull ){
  110921. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  110922. endEq = 0;
  110923. nConstraint++;
  110924. }
  110925. sqlite3DbFree(db, zStartAff);
  110926. /* Top of the loop body */
  110927. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  110928. /* Check if the index cursor is past the end of the range. */
  110929. if( nConstraint ){
  110930. op = aEndOp[bRev*2 + endEq];
  110931. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  110932. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  110933. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  110934. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  110935. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  110936. }
  110937. /* Seek the table cursor, if required */
  110938. disableTerm(pLevel, pRangeStart);
  110939. disableTerm(pLevel, pRangeEnd);
  110940. if( omitTable ){
  110941. /* pIdx is a covering index. No need to access the main table. */
  110942. }else if( HasRowid(pIdx->pTable) ){
  110943. iRowidReg = ++pParse->nMem;
  110944. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  110945. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  110946. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  110947. }else if( iCur!=iIdxCur ){
  110948. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  110949. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  110950. for(j=0; j<pPk->nKeyCol; j++){
  110951. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  110952. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  110953. }
  110954. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  110955. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  110956. }
  110957. /* Record the instruction used to terminate the loop. Disable
  110958. ** WHERE clause terms made redundant by the index range scan.
  110959. */
  110960. if( pLoop->wsFlags & WHERE_ONEROW ){
  110961. pLevel->op = OP_Noop;
  110962. }else if( bRev ){
  110963. pLevel->op = OP_Prev;
  110964. }else{
  110965. pLevel->op = OP_Next;
  110966. }
  110967. pLevel->p1 = iIdxCur;
  110968. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  110969. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  110970. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  110971. }else{
  110972. assert( pLevel->p5==0 );
  110973. }
  110974. }else
  110975. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  110976. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  110977. /* Case 5: Two or more separately indexed terms connected by OR
  110978. **
  110979. ** Example:
  110980. **
  110981. ** CREATE TABLE t1(a,b,c,d);
  110982. ** CREATE INDEX i1 ON t1(a);
  110983. ** CREATE INDEX i2 ON t1(b);
  110984. ** CREATE INDEX i3 ON t1(c);
  110985. **
  110986. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  110987. **
  110988. ** In the example, there are three indexed terms connected by OR.
  110989. ** The top of the loop looks like this:
  110990. **
  110991. ** Null 1 # Zero the rowset in reg 1
  110992. **
  110993. ** Then, for each indexed term, the following. The arguments to
  110994. ** RowSetTest are such that the rowid of the current row is inserted
  110995. ** into the RowSet. If it is already present, control skips the
  110996. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  110997. **
  110998. ** sqlite3WhereBegin(<term>)
  110999. ** RowSetTest # Insert rowid into rowset
  111000. ** Gosub 2 A
  111001. ** sqlite3WhereEnd()
  111002. **
  111003. ** Following the above, code to terminate the loop. Label A, the target
  111004. ** of the Gosub above, jumps to the instruction right after the Goto.
  111005. **
  111006. ** Null 1 # Zero the rowset in reg 1
  111007. ** Goto B # The loop is finished.
  111008. **
  111009. ** A: <loop body> # Return data, whatever.
  111010. **
  111011. ** Return 2 # Jump back to the Gosub
  111012. **
  111013. ** B: <after the loop>
  111014. **
  111015. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  111016. ** use an ephemeral index instead of a RowSet to record the primary
  111017. ** keys of the rows we have already seen.
  111018. **
  111019. */
  111020. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  111021. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  111022. Index *pCov = 0; /* Potential covering index (or NULL) */
  111023. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  111024. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  111025. int regRowset = 0; /* Register for RowSet object */
  111026. int regRowid = 0; /* Register holding rowid */
  111027. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  111028. int iRetInit; /* Address of regReturn init */
  111029. int untestedTerms = 0; /* Some terms not completely tested */
  111030. int ii; /* Loop counter */
  111031. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  111032. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  111033. Table *pTab = pTabItem->pTab;
  111034. pTerm = pLoop->aLTerm[0];
  111035. assert( pTerm!=0 );
  111036. assert( pTerm->eOperator & WO_OR );
  111037. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  111038. pOrWc = &pTerm->u.pOrInfo->wc;
  111039. pLevel->op = OP_Return;
  111040. pLevel->p1 = regReturn;
  111041. /* Set up a new SrcList in pOrTab containing the table being scanned
  111042. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  111043. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  111044. */
  111045. if( pWInfo->nLevel>1 ){
  111046. int nNotReady; /* The number of notReady tables */
  111047. struct SrcList_item *origSrc; /* Original list of tables */
  111048. nNotReady = pWInfo->nLevel - iLevel - 1;
  111049. pOrTab = sqlite3StackAllocRaw(db,
  111050. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  111051. if( pOrTab==0 ) return notReady;
  111052. pOrTab->nAlloc = (u8)(nNotReady + 1);
  111053. pOrTab->nSrc = pOrTab->nAlloc;
  111054. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  111055. origSrc = pWInfo->pTabList->a;
  111056. for(k=1; k<=nNotReady; k++){
  111057. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  111058. }
  111059. }else{
  111060. pOrTab = pWInfo->pTabList;
  111061. }
  111062. /* Initialize the rowset register to contain NULL. An SQL NULL is
  111063. ** equivalent to an empty rowset. Or, create an ephemeral index
  111064. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  111065. **
  111066. ** Also initialize regReturn to contain the address of the instruction
  111067. ** immediately following the OP_Return at the bottom of the loop. This
  111068. ** is required in a few obscure LEFT JOIN cases where control jumps
  111069. ** over the top of the loop into the body of it. In this case the
  111070. ** correct response for the end-of-loop code (the OP_Return) is to
  111071. ** fall through to the next instruction, just as an OP_Next does if
  111072. ** called on an uninitialized cursor.
  111073. */
  111074. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  111075. if( HasRowid(pTab) ){
  111076. regRowset = ++pParse->nMem;
  111077. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  111078. }else{
  111079. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  111080. regRowset = pParse->nTab++;
  111081. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  111082. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  111083. }
  111084. regRowid = ++pParse->nMem;
  111085. }
  111086. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  111087. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  111088. ** Then for every term xN, evaluate as the subexpression: xN AND z
  111089. ** That way, terms in y that are factored into the disjunction will
  111090. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  111091. **
  111092. ** Actually, each subexpression is converted to "xN AND w" where w is
  111093. ** the "interesting" terms of z - terms that did not originate in the
  111094. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  111095. ** indices.
  111096. **
  111097. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  111098. ** is not contained in the ON clause of a LEFT JOIN.
  111099. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  111100. */
  111101. if( pWC->nTerm>1 ){
  111102. int iTerm;
  111103. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  111104. Expr *pExpr = pWC->a[iTerm].pExpr;
  111105. if( &pWC->a[iTerm] == pTerm ) continue;
  111106. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  111107. if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
  111108. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  111109. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  111110. pExpr = sqlite3ExprDup(db, pExpr, 0);
  111111. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  111112. }
  111113. if( pAndExpr ){
  111114. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  111115. }
  111116. }
  111117. /* Run a separate WHERE clause for each term of the OR clause. After
  111118. ** eliminating duplicates from other WHERE clauses, the action for each
  111119. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  111120. */
  111121. wctrlFlags = WHERE_OMIT_OPEN_CLOSE
  111122. | WHERE_FORCE_TABLE
  111123. | WHERE_ONETABLE_ONLY
  111124. | WHERE_NO_AUTOINDEX;
  111125. for(ii=0; ii<pOrWc->nTerm; ii++){
  111126. WhereTerm *pOrTerm = &pOrWc->a[ii];
  111127. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  111128. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  111129. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  111130. int j1 = 0; /* Address of jump operation */
  111131. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  111132. pAndExpr->pLeft = pOrExpr;
  111133. pOrExpr = pAndExpr;
  111134. }
  111135. /* Loop through table entries that match term pOrTerm. */
  111136. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  111137. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  111138. wctrlFlags, iCovCur);
  111139. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  111140. if( pSubWInfo ){
  111141. WhereLoop *pSubLoop;
  111142. int addrExplain = sqlite3WhereExplainOneScan(
  111143. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  111144. );
  111145. sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
  111146. /* This is the sub-WHERE clause body. First skip over
  111147. ** duplicate rows from prior sub-WHERE clauses, and record the
  111148. ** rowid (or PRIMARY KEY) for the current row so that the same
  111149. ** row will be skipped in subsequent sub-WHERE clauses.
  111150. */
  111151. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  111152. int r;
  111153. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  111154. if( HasRowid(pTab) ){
  111155. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  111156. j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
  111157. VdbeCoverage(v);
  111158. }else{
  111159. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  111160. int nPk = pPk->nKeyCol;
  111161. int iPk;
  111162. /* Read the PK into an array of temp registers. */
  111163. r = sqlite3GetTempRange(pParse, nPk);
  111164. for(iPk=0; iPk<nPk; iPk++){
  111165. int iCol = pPk->aiColumn[iPk];
  111166. int rx;
  111167. rx = sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur,r+iPk,0);
  111168. if( rx!=r+iPk ){
  111169. sqlite3VdbeAddOp2(v, OP_SCopy, rx, r+iPk);
  111170. }
  111171. }
  111172. /* Check if the temp table already contains this key. If so,
  111173. ** the row has already been included in the result set and
  111174. ** can be ignored (by jumping past the Gosub below). Otherwise,
  111175. ** insert the key into the temp table and proceed with processing
  111176. ** the row.
  111177. **
  111178. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  111179. ** is zero, assume that the key cannot already be present in
  111180. ** the temp table. And if iSet is -1, assume that there is no
  111181. ** need to insert the key into the temp table, as it will never
  111182. ** be tested for. */
  111183. if( iSet ){
  111184. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  111185. VdbeCoverage(v);
  111186. }
  111187. if( iSet>=0 ){
  111188. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  111189. sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
  111190. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  111191. }
  111192. /* Release the array of temp registers */
  111193. sqlite3ReleaseTempRange(pParse, r, nPk);
  111194. }
  111195. }
  111196. /* Invoke the main loop body as a subroutine */
  111197. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  111198. /* Jump here (skipping the main loop body subroutine) if the
  111199. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  111200. if( j1 ) sqlite3VdbeJumpHere(v, j1);
  111201. /* The pSubWInfo->untestedTerms flag means that this OR term
  111202. ** contained one or more AND term from a notReady table. The
  111203. ** terms from the notReady table could not be tested and will
  111204. ** need to be tested later.
  111205. */
  111206. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  111207. /* If all of the OR-connected terms are optimized using the same
  111208. ** index, and the index is opened using the same cursor number
  111209. ** by each call to sqlite3WhereBegin() made by this loop, it may
  111210. ** be possible to use that index as a covering index.
  111211. **
  111212. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  111213. ** uses an index, and this is either the first OR-connected term
  111214. ** processed or the index is the same as that used by all previous
  111215. ** terms, set pCov to the candidate covering index. Otherwise, set
  111216. ** pCov to NULL to indicate that no candidate covering index will
  111217. ** be available.
  111218. */
  111219. pSubLoop = pSubWInfo->a[0].pWLoop;
  111220. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  111221. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  111222. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  111223. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  111224. ){
  111225. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  111226. pCov = pSubLoop->u.btree.pIndex;
  111227. wctrlFlags |= WHERE_REOPEN_IDX;
  111228. }else{
  111229. pCov = 0;
  111230. }
  111231. /* Finish the loop through table entries that match term pOrTerm. */
  111232. sqlite3WhereEnd(pSubWInfo);
  111233. }
  111234. }
  111235. }
  111236. pLevel->u.pCovidx = pCov;
  111237. if( pCov ) pLevel->iIdxCur = iCovCur;
  111238. if( pAndExpr ){
  111239. pAndExpr->pLeft = 0;
  111240. sqlite3ExprDelete(db, pAndExpr);
  111241. }
  111242. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  111243. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  111244. sqlite3VdbeResolveLabel(v, iLoopBody);
  111245. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  111246. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  111247. }else
  111248. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  111249. {
  111250. /* Case 6: There is no usable index. We must do a complete
  111251. ** scan of the entire table.
  111252. */
  111253. static const u8 aStep[] = { OP_Next, OP_Prev };
  111254. static const u8 aStart[] = { OP_Rewind, OP_Last };
  111255. assert( bRev==0 || bRev==1 );
  111256. if( pTabItem->isRecursive ){
  111257. /* Tables marked isRecursive have only a single row that is stored in
  111258. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  111259. pLevel->op = OP_Noop;
  111260. }else{
  111261. pLevel->op = aStep[bRev];
  111262. pLevel->p1 = iCur;
  111263. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  111264. VdbeCoverageIf(v, bRev==0);
  111265. VdbeCoverageIf(v, bRev!=0);
  111266. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  111267. }
  111268. }
  111269. #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
  111270. pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
  111271. #endif
  111272. /* Insert code to test every subexpression that can be completely
  111273. ** computed using the current set of tables.
  111274. */
  111275. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  111276. Expr *pE;
  111277. int skipLikeAddr = 0;
  111278. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  111279. testcase( pTerm->wtFlags & TERM_CODED );
  111280. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  111281. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  111282. testcase( pWInfo->untestedTerms==0
  111283. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  111284. pWInfo->untestedTerms = 1;
  111285. continue;
  111286. }
  111287. pE = pTerm->pExpr;
  111288. assert( pE!=0 );
  111289. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  111290. continue;
  111291. }
  111292. if( pTerm->wtFlags & TERM_LIKECOND ){
  111293. assert( pLevel->iLikeRepCntr>0 );
  111294. skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
  111295. VdbeCoverage(v);
  111296. }
  111297. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  111298. if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
  111299. pTerm->wtFlags |= TERM_CODED;
  111300. }
  111301. /* Insert code to test for implied constraints based on transitivity
  111302. ** of the "==" operator.
  111303. **
  111304. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  111305. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  111306. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  111307. ** the implied "t1.a=123" constraint.
  111308. */
  111309. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  111310. Expr *pE, *pEAlt;
  111311. WhereTerm *pAlt;
  111312. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  111313. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
  111314. if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
  111315. if( pTerm->leftCursor!=iCur ) continue;
  111316. if( pLevel->iLeftJoin ) continue;
  111317. pE = pTerm->pExpr;
  111318. assert( !ExprHasProperty(pE, EP_FromJoin) );
  111319. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  111320. pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
  111321. WO_EQ|WO_IN|WO_IS, 0);
  111322. if( pAlt==0 ) continue;
  111323. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  111324. testcase( pAlt->eOperator & WO_EQ );
  111325. testcase( pAlt->eOperator & WO_IS );
  111326. testcase( pAlt->eOperator & WO_IN );
  111327. VdbeModuleComment((v, "begin transitive constraint"));
  111328. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  111329. if( pEAlt ){
  111330. *pEAlt = *pAlt->pExpr;
  111331. pEAlt->pLeft = pE->pLeft;
  111332. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  111333. sqlite3StackFree(db, pEAlt);
  111334. }
  111335. }
  111336. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  111337. ** at least one row of the right table has matched the left table.
  111338. */
  111339. if( pLevel->iLeftJoin ){
  111340. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  111341. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  111342. VdbeComment((v, "record LEFT JOIN hit"));
  111343. sqlite3ExprCacheClear(pParse);
  111344. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  111345. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  111346. testcase( pTerm->wtFlags & TERM_CODED );
  111347. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  111348. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  111349. assert( pWInfo->untestedTerms );
  111350. continue;
  111351. }
  111352. assert( pTerm->pExpr );
  111353. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  111354. pTerm->wtFlags |= TERM_CODED;
  111355. }
  111356. }
  111357. return pLevel->notReady;
  111358. }
  111359. /************** End of wherecode.c *******************************************/
  111360. /************** Begin file whereexpr.c ***************************************/
  111361. /*
  111362. ** 2015-06-08
  111363. **
  111364. ** The author disclaims copyright to this source code. In place of
  111365. ** a legal notice, here is a blessing:
  111366. **
  111367. ** May you do good and not evil.
  111368. ** May you find forgiveness for yourself and forgive others.
  111369. ** May you share freely, never taking more than you give.
  111370. **
  111371. *************************************************************************
  111372. ** This module contains C code that generates VDBE code used to process
  111373. ** the WHERE clause of SQL statements.
  111374. **
  111375. ** This file was originally part of where.c but was split out to improve
  111376. ** readability and editabiliity. This file contains utility routines for
  111377. ** analyzing Expr objects in the WHERE clause.
  111378. */
  111379. /* #include "sqliteInt.h" */
  111380. /* #include "whereInt.h" */
  111381. /* Forward declarations */
  111382. static void exprAnalyze(SrcList*, WhereClause*, int);
  111383. /*
  111384. ** Deallocate all memory associated with a WhereOrInfo object.
  111385. */
  111386. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  111387. sqlite3WhereClauseClear(&p->wc);
  111388. sqlite3DbFree(db, p);
  111389. }
  111390. /*
  111391. ** Deallocate all memory associated with a WhereAndInfo object.
  111392. */
  111393. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  111394. sqlite3WhereClauseClear(&p->wc);
  111395. sqlite3DbFree(db, p);
  111396. }
  111397. /*
  111398. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  111399. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  111400. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  111401. ** 0 is returned if the new WhereTerm could not be added due to a memory
  111402. ** allocation error. The memory allocation failure will be recorded in
  111403. ** the db->mallocFailed flag so that higher-level functions can detect it.
  111404. **
  111405. ** This routine will increase the size of the pWC->a[] array as necessary.
  111406. **
  111407. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  111408. ** for freeing the expression p is assumed by the WhereClause object pWC.
  111409. ** This is true even if this routine fails to allocate a new WhereTerm.
  111410. **
  111411. ** WARNING: This routine might reallocate the space used to store
  111412. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  111413. ** calling this routine. Such pointers may be reinitialized by referencing
  111414. ** the pWC->a[] array.
  111415. */
  111416. static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
  111417. WhereTerm *pTerm;
  111418. int idx;
  111419. testcase( wtFlags & TERM_VIRTUAL );
  111420. if( pWC->nTerm>=pWC->nSlot ){
  111421. WhereTerm *pOld = pWC->a;
  111422. sqlite3 *db = pWC->pWInfo->pParse->db;
  111423. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  111424. if( pWC->a==0 ){
  111425. if( wtFlags & TERM_DYNAMIC ){
  111426. sqlite3ExprDelete(db, p);
  111427. }
  111428. pWC->a = pOld;
  111429. return 0;
  111430. }
  111431. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  111432. if( pOld!=pWC->aStatic ){
  111433. sqlite3DbFree(db, pOld);
  111434. }
  111435. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  111436. memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
  111437. }
  111438. pTerm = &pWC->a[idx = pWC->nTerm++];
  111439. if( p && ExprHasProperty(p, EP_Unlikely) ){
  111440. pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
  111441. }else{
  111442. pTerm->truthProb = 1;
  111443. }
  111444. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  111445. pTerm->wtFlags = wtFlags;
  111446. pTerm->pWC = pWC;
  111447. pTerm->iParent = -1;
  111448. return idx;
  111449. }
  111450. /*
  111451. ** Return TRUE if the given operator is one of the operators that is
  111452. ** allowed for an indexable WHERE clause term. The allowed operators are
  111453. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  111454. */
  111455. static int allowedOp(int op){
  111456. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  111457. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  111458. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  111459. assert( TK_GE==TK_EQ+4 );
  111460. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
  111461. }
  111462. /*
  111463. ** Commute a comparison operator. Expressions of the form "X op Y"
  111464. ** are converted into "Y op X".
  111465. **
  111466. ** If left/right precedence rules come into play when determining the
  111467. ** collating sequence, then COLLATE operators are adjusted to ensure
  111468. ** that the collating sequence does not change. For example:
  111469. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  111470. ** the left hand side of a comparison overrides any collation sequence
  111471. ** attached to the right. For the same reason the EP_Collate flag
  111472. ** is not commuted.
  111473. */
  111474. static void exprCommute(Parse *pParse, Expr *pExpr){
  111475. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  111476. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  111477. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  111478. if( expRight==expLeft ){
  111479. /* Either X and Y both have COLLATE operator or neither do */
  111480. if( expRight ){
  111481. /* Both X and Y have COLLATE operators. Make sure X is always
  111482. ** used by clearing the EP_Collate flag from Y. */
  111483. pExpr->pRight->flags &= ~EP_Collate;
  111484. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  111485. /* Neither X nor Y have COLLATE operators, but X has a non-default
  111486. ** collating sequence. So add the EP_Collate marker on X to cause
  111487. ** it to be searched first. */
  111488. pExpr->pLeft->flags |= EP_Collate;
  111489. }
  111490. }
  111491. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  111492. if( pExpr->op>=TK_GT ){
  111493. assert( TK_LT==TK_GT+2 );
  111494. assert( TK_GE==TK_LE+2 );
  111495. assert( TK_GT>TK_EQ );
  111496. assert( TK_GT<TK_LE );
  111497. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  111498. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  111499. }
  111500. }
  111501. /*
  111502. ** Translate from TK_xx operator to WO_xx bitmask.
  111503. */
  111504. static u16 operatorMask(int op){
  111505. u16 c;
  111506. assert( allowedOp(op) );
  111507. if( op==TK_IN ){
  111508. c = WO_IN;
  111509. }else if( op==TK_ISNULL ){
  111510. c = WO_ISNULL;
  111511. }else if( op==TK_IS ){
  111512. c = WO_IS;
  111513. }else{
  111514. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  111515. c = (u16)(WO_EQ<<(op-TK_EQ));
  111516. }
  111517. assert( op!=TK_ISNULL || c==WO_ISNULL );
  111518. assert( op!=TK_IN || c==WO_IN );
  111519. assert( op!=TK_EQ || c==WO_EQ );
  111520. assert( op!=TK_LT || c==WO_LT );
  111521. assert( op!=TK_LE || c==WO_LE );
  111522. assert( op!=TK_GT || c==WO_GT );
  111523. assert( op!=TK_GE || c==WO_GE );
  111524. assert( op!=TK_IS || c==WO_IS );
  111525. return c;
  111526. }
  111527. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  111528. /*
  111529. ** Check to see if the given expression is a LIKE or GLOB operator that
  111530. ** can be optimized using inequality constraints. Return TRUE if it is
  111531. ** so and false if not.
  111532. **
  111533. ** In order for the operator to be optimizible, the RHS must be a string
  111534. ** literal that does not begin with a wildcard. The LHS must be a column
  111535. ** that may only be NULL, a string, or a BLOB, never a number. (This means
  111536. ** that virtual tables cannot participate in the LIKE optimization.) The
  111537. ** collating sequence for the column on the LHS must be appropriate for
  111538. ** the operator.
  111539. */
  111540. static int isLikeOrGlob(
  111541. Parse *pParse, /* Parsing and code generating context */
  111542. Expr *pExpr, /* Test this expression */
  111543. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  111544. int *pisComplete, /* True if the only wildcard is % in the last character */
  111545. int *pnoCase /* True if uppercase is equivalent to lowercase */
  111546. ){
  111547. const char *z = 0; /* String on RHS of LIKE operator */
  111548. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  111549. ExprList *pList; /* List of operands to the LIKE operator */
  111550. int c; /* One character in z[] */
  111551. int cnt; /* Number of non-wildcard prefix characters */
  111552. char wc[3]; /* Wildcard characters */
  111553. sqlite3 *db = pParse->db; /* Database connection */
  111554. sqlite3_value *pVal = 0;
  111555. int op; /* Opcode of pRight */
  111556. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  111557. return 0;
  111558. }
  111559. #ifdef SQLITE_EBCDIC
  111560. if( *pnoCase ) return 0;
  111561. #endif
  111562. pList = pExpr->x.pList;
  111563. pLeft = pList->a[1].pExpr;
  111564. if( pLeft->op!=TK_COLUMN
  111565. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  111566. || IsVirtual(pLeft->pTab) /* Value might be numeric */
  111567. ){
  111568. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  111569. ** be the name of an indexed column with TEXT affinity. */
  111570. return 0;
  111571. }
  111572. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  111573. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  111574. op = pRight->op;
  111575. if( op==TK_VARIABLE ){
  111576. Vdbe *pReprepare = pParse->pReprepare;
  111577. int iCol = pRight->iColumn;
  111578. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
  111579. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  111580. z = (char *)sqlite3_value_text(pVal);
  111581. }
  111582. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  111583. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  111584. }else if( op==TK_STRING ){
  111585. z = pRight->u.zToken;
  111586. }
  111587. if( z ){
  111588. cnt = 0;
  111589. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  111590. cnt++;
  111591. }
  111592. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  111593. Expr *pPrefix;
  111594. *pisComplete = c==wc[0] && z[cnt+1]==0;
  111595. pPrefix = sqlite3Expr(db, TK_STRING, z);
  111596. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  111597. *ppPrefix = pPrefix;
  111598. if( op==TK_VARIABLE ){
  111599. Vdbe *v = pParse->pVdbe;
  111600. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  111601. if( *pisComplete && pRight->u.zToken[1] ){
  111602. /* If the rhs of the LIKE expression is a variable, and the current
  111603. ** value of the variable means there is no need to invoke the LIKE
  111604. ** function, then no OP_Variable will be added to the program.
  111605. ** This causes problems for the sqlite3_bind_parameter_name()
  111606. ** API. To work around them, add a dummy OP_Variable here.
  111607. */
  111608. int r1 = sqlite3GetTempReg(pParse);
  111609. sqlite3ExprCodeTarget(pParse, pRight, r1);
  111610. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  111611. sqlite3ReleaseTempReg(pParse, r1);
  111612. }
  111613. }
  111614. }else{
  111615. z = 0;
  111616. }
  111617. }
  111618. sqlite3ValueFree(pVal);
  111619. return (z!=0);
  111620. }
  111621. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  111622. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111623. /*
  111624. ** Check to see if the given expression is of the form
  111625. **
  111626. ** column MATCH expr
  111627. **
  111628. ** If it is then return TRUE. If not, return FALSE.
  111629. */
  111630. static int isMatchOfColumn(
  111631. Expr *pExpr /* Test this expression */
  111632. ){
  111633. ExprList *pList;
  111634. if( pExpr->op!=TK_FUNCTION ){
  111635. return 0;
  111636. }
  111637. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  111638. return 0;
  111639. }
  111640. pList = pExpr->x.pList;
  111641. if( pList->nExpr!=2 ){
  111642. return 0;
  111643. }
  111644. if( pList->a[1].pExpr->op != TK_COLUMN ){
  111645. return 0;
  111646. }
  111647. return 1;
  111648. }
  111649. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  111650. /*
  111651. ** If the pBase expression originated in the ON or USING clause of
  111652. ** a join, then transfer the appropriate markings over to derived.
  111653. */
  111654. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  111655. if( pDerived ){
  111656. pDerived->flags |= pBase->flags & EP_FromJoin;
  111657. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  111658. }
  111659. }
  111660. /*
  111661. ** Mark term iChild as being a child of term iParent
  111662. */
  111663. static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
  111664. pWC->a[iChild].iParent = iParent;
  111665. pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
  111666. pWC->a[iParent].nChild++;
  111667. }
  111668. /*
  111669. ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
  111670. ** a conjunction, then return just pTerm when N==0. If N is exceeds
  111671. ** the number of available subterms, return NULL.
  111672. */
  111673. static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
  111674. if( pTerm->eOperator!=WO_AND ){
  111675. return N==0 ? pTerm : 0;
  111676. }
  111677. if( N<pTerm->u.pAndInfo->wc.nTerm ){
  111678. return &pTerm->u.pAndInfo->wc.a[N];
  111679. }
  111680. return 0;
  111681. }
  111682. /*
  111683. ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
  111684. ** two subterms are in disjunction - they are OR-ed together.
  111685. **
  111686. ** If these two terms are both of the form: "A op B" with the same
  111687. ** A and B values but different operators and if the operators are
  111688. ** compatible (if one is = and the other is <, for example) then
  111689. ** add a new virtual AND term to pWC that is the combination of the
  111690. ** two.
  111691. **
  111692. ** Some examples:
  111693. **
  111694. ** x<y OR x=y --> x<=y
  111695. ** x=y OR x=y --> x=y
  111696. ** x<=y OR x<y --> x<=y
  111697. **
  111698. ** The following is NOT generated:
  111699. **
  111700. ** x<y OR x>y --> x!=y
  111701. */
  111702. static void whereCombineDisjuncts(
  111703. SrcList *pSrc, /* the FROM clause */
  111704. WhereClause *pWC, /* The complete WHERE clause */
  111705. WhereTerm *pOne, /* First disjunct */
  111706. WhereTerm *pTwo /* Second disjunct */
  111707. ){
  111708. u16 eOp = pOne->eOperator | pTwo->eOperator;
  111709. sqlite3 *db; /* Database connection (for malloc) */
  111710. Expr *pNew; /* New virtual expression */
  111711. int op; /* Operator for the combined expression */
  111712. int idxNew; /* Index in pWC of the next virtual term */
  111713. if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  111714. if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
  111715. if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
  111716. && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
  111717. assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
  111718. assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
  111719. if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
  111720. if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
  111721. /* If we reach this point, it means the two subterms can be combined */
  111722. if( (eOp & (eOp-1))!=0 ){
  111723. if( eOp & (WO_LT|WO_LE) ){
  111724. eOp = WO_LE;
  111725. }else{
  111726. assert( eOp & (WO_GT|WO_GE) );
  111727. eOp = WO_GE;
  111728. }
  111729. }
  111730. db = pWC->pWInfo->pParse->db;
  111731. pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
  111732. if( pNew==0 ) return;
  111733. for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
  111734. pNew->op = op;
  111735. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  111736. exprAnalyze(pSrc, pWC, idxNew);
  111737. }
  111738. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  111739. /*
  111740. ** Analyze a term that consists of two or more OR-connected
  111741. ** subterms. So in:
  111742. **
  111743. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  111744. ** ^^^^^^^^^^^^^^^^^^^^
  111745. **
  111746. ** This routine analyzes terms such as the middle term in the above example.
  111747. ** A WhereOrTerm object is computed and attached to the term under
  111748. ** analysis, regardless of the outcome of the analysis. Hence:
  111749. **
  111750. ** WhereTerm.wtFlags |= TERM_ORINFO
  111751. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  111752. **
  111753. ** The term being analyzed must have two or more of OR-connected subterms.
  111754. ** A single subterm might be a set of AND-connected sub-subterms.
  111755. ** Examples of terms under analysis:
  111756. **
  111757. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  111758. ** (B) x=expr1 OR expr2=x OR x=expr3
  111759. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  111760. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  111761. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  111762. ** (F) x>A OR (x=A AND y>=B)
  111763. **
  111764. ** CASE 1:
  111765. **
  111766. ** If all subterms are of the form T.C=expr for some single column of C and
  111767. ** a single table T (as shown in example B above) then create a new virtual
  111768. ** term that is an equivalent IN expression. In other words, if the term
  111769. ** being analyzed is:
  111770. **
  111771. ** x = expr1 OR expr2 = x OR x = expr3
  111772. **
  111773. ** then create a new virtual term like this:
  111774. **
  111775. ** x IN (expr1,expr2,expr3)
  111776. **
  111777. ** CASE 2:
  111778. **
  111779. ** If there are exactly two disjuncts and one side has x>A and the other side
  111780. ** has x=A (for the same x and A) then add a new virtual conjunct term to the
  111781. ** WHERE clause of the form "x>=A". Example:
  111782. **
  111783. ** x>A OR (x=A AND y>B) adds: x>=A
  111784. **
  111785. ** The added conjunct can sometimes be helpful in query planning.
  111786. **
  111787. ** CASE 3:
  111788. **
  111789. ** If all subterms are indexable by a single table T, then set
  111790. **
  111791. ** WhereTerm.eOperator = WO_OR
  111792. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  111793. **
  111794. ** A subterm is "indexable" if it is of the form
  111795. ** "T.C <op> <expr>" where C is any column of table T and
  111796. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  111797. ** A subterm is also indexable if it is an AND of two or more
  111798. ** subsubterms at least one of which is indexable. Indexable AND
  111799. ** subterms have their eOperator set to WO_AND and they have
  111800. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  111801. **
  111802. ** From another point of view, "indexable" means that the subterm could
  111803. ** potentially be used with an index if an appropriate index exists.
  111804. ** This analysis does not consider whether or not the index exists; that
  111805. ** is decided elsewhere. This analysis only looks at whether subterms
  111806. ** appropriate for indexing exist.
  111807. **
  111808. ** All examples A through E above satisfy case 3. But if a term
  111809. ** also satisfies case 1 (such as B) we know that the optimizer will
  111810. ** always prefer case 1, so in that case we pretend that case 3 is not
  111811. ** satisfied.
  111812. **
  111813. ** It might be the case that multiple tables are indexable. For example,
  111814. ** (E) above is indexable on tables P, Q, and R.
  111815. **
  111816. ** Terms that satisfy case 3 are candidates for lookup by using
  111817. ** separate indices to find rowids for each subterm and composing
  111818. ** the union of all rowids using a RowSet object. This is similar
  111819. ** to "bitmap indices" in other database engines.
  111820. **
  111821. ** OTHERWISE:
  111822. **
  111823. ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
  111824. ** zero. This term is not useful for search.
  111825. */
  111826. static void exprAnalyzeOrTerm(
  111827. SrcList *pSrc, /* the FROM clause */
  111828. WhereClause *pWC, /* the complete WHERE clause */
  111829. int idxTerm /* Index of the OR-term to be analyzed */
  111830. ){
  111831. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  111832. Parse *pParse = pWInfo->pParse; /* Parser context */
  111833. sqlite3 *db = pParse->db; /* Database connection */
  111834. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  111835. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  111836. int i; /* Loop counters */
  111837. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  111838. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  111839. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  111840. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  111841. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  111842. /*
  111843. ** Break the OR clause into its separate subterms. The subterms are
  111844. ** stored in a WhereClause structure containing within the WhereOrInfo
  111845. ** object that is attached to the original OR clause term.
  111846. */
  111847. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  111848. assert( pExpr->op==TK_OR );
  111849. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  111850. if( pOrInfo==0 ) return;
  111851. pTerm->wtFlags |= TERM_ORINFO;
  111852. pOrWc = &pOrInfo->wc;
  111853. sqlite3WhereClauseInit(pOrWc, pWInfo);
  111854. sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
  111855. sqlite3WhereExprAnalyze(pSrc, pOrWc);
  111856. if( db->mallocFailed ) return;
  111857. assert( pOrWc->nTerm>=2 );
  111858. /*
  111859. ** Compute the set of tables that might satisfy cases 1 or 3.
  111860. */
  111861. indexable = ~(Bitmask)0;
  111862. chngToIN = ~(Bitmask)0;
  111863. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  111864. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  111865. WhereAndInfo *pAndInfo;
  111866. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  111867. chngToIN = 0;
  111868. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  111869. if( pAndInfo ){
  111870. WhereClause *pAndWC;
  111871. WhereTerm *pAndTerm;
  111872. int j;
  111873. Bitmask b = 0;
  111874. pOrTerm->u.pAndInfo = pAndInfo;
  111875. pOrTerm->wtFlags |= TERM_ANDINFO;
  111876. pOrTerm->eOperator = WO_AND;
  111877. pAndWC = &pAndInfo->wc;
  111878. sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
  111879. sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  111880. sqlite3WhereExprAnalyze(pSrc, pAndWC);
  111881. pAndWC->pOuter = pWC;
  111882. testcase( db->mallocFailed );
  111883. if( !db->mallocFailed ){
  111884. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  111885. assert( pAndTerm->pExpr );
  111886. if( allowedOp(pAndTerm->pExpr->op) ){
  111887. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  111888. }
  111889. }
  111890. }
  111891. indexable &= b;
  111892. }
  111893. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  111894. /* Skip this term for now. We revisit it when we process the
  111895. ** corresponding TERM_VIRTUAL term */
  111896. }else{
  111897. Bitmask b;
  111898. b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  111899. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  111900. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  111901. b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
  111902. }
  111903. indexable &= b;
  111904. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  111905. chngToIN = 0;
  111906. }else{
  111907. chngToIN &= b;
  111908. }
  111909. }
  111910. }
  111911. /*
  111912. ** Record the set of tables that satisfy case 3. The set might be
  111913. ** empty.
  111914. */
  111915. pOrInfo->indexable = indexable;
  111916. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  111917. /* For a two-way OR, attempt to implementation case 2.
  111918. */
  111919. if( indexable && pOrWc->nTerm==2 ){
  111920. int iOne = 0;
  111921. WhereTerm *pOne;
  111922. while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
  111923. int iTwo = 0;
  111924. WhereTerm *pTwo;
  111925. while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
  111926. whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
  111927. }
  111928. }
  111929. }
  111930. /*
  111931. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  111932. ** we have to do some additional checking to see if case 1 really
  111933. ** is satisfied.
  111934. **
  111935. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  111936. ** that there is no possibility of transforming the OR clause into an
  111937. ** IN operator because one or more terms in the OR clause contain
  111938. ** something other than == on a column in the single table. The 1-bit
  111939. ** case means that every term of the OR clause is of the form
  111940. ** "table.column=expr" for some single table. The one bit that is set
  111941. ** will correspond to the common table. We still need to check to make
  111942. ** sure the same column is used on all terms. The 2-bit case is when
  111943. ** the all terms are of the form "table1.column=table2.column". It
  111944. ** might be possible to form an IN operator with either table1.column
  111945. ** or table2.column as the LHS if either is common to every term of
  111946. ** the OR clause.
  111947. **
  111948. ** Note that terms of the form "table.column1=table.column2" (the
  111949. ** same table on both sizes of the ==) cannot be optimized.
  111950. */
  111951. if( chngToIN ){
  111952. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  111953. int iColumn = -1; /* Column index on lhs of IN operator */
  111954. int iCursor = -1; /* Table cursor common to all terms */
  111955. int j = 0; /* Loop counter */
  111956. /* Search for a table and column that appears on one side or the
  111957. ** other of the == operator in every subterm. That table and column
  111958. ** will be recorded in iCursor and iColumn. There might not be any
  111959. ** such table and column. Set okToChngToIN if an appropriate table
  111960. ** and column is found but leave okToChngToIN false if not found.
  111961. */
  111962. for(j=0; j<2 && !okToChngToIN; j++){
  111963. pOrTerm = pOrWc->a;
  111964. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  111965. assert( pOrTerm->eOperator & WO_EQ );
  111966. pOrTerm->wtFlags &= ~TERM_OR_OK;
  111967. if( pOrTerm->leftCursor==iCursor ){
  111968. /* This is the 2-bit case and we are on the second iteration and
  111969. ** current term is from the first iteration. So skip this term. */
  111970. assert( j==1 );
  111971. continue;
  111972. }
  111973. if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
  111974. pOrTerm->leftCursor))==0 ){
  111975. /* This term must be of the form t1.a==t2.b where t2 is in the
  111976. ** chngToIN set but t1 is not. This term will be either preceded
  111977. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  111978. ** and use its inversion. */
  111979. testcase( pOrTerm->wtFlags & TERM_COPIED );
  111980. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  111981. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  111982. continue;
  111983. }
  111984. iColumn = pOrTerm->u.leftColumn;
  111985. iCursor = pOrTerm->leftCursor;
  111986. break;
  111987. }
  111988. if( i<0 ){
  111989. /* No candidate table+column was found. This can only occur
  111990. ** on the second iteration */
  111991. assert( j==1 );
  111992. assert( IsPowerOfTwo(chngToIN) );
  111993. assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
  111994. break;
  111995. }
  111996. testcase( j==1 );
  111997. /* We have found a candidate table and column. Check to see if that
  111998. ** table and column is common to every term in the OR clause */
  111999. okToChngToIN = 1;
  112000. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  112001. assert( pOrTerm->eOperator & WO_EQ );
  112002. if( pOrTerm->leftCursor!=iCursor ){
  112003. pOrTerm->wtFlags &= ~TERM_OR_OK;
  112004. }else if( pOrTerm->u.leftColumn!=iColumn ){
  112005. okToChngToIN = 0;
  112006. }else{
  112007. int affLeft, affRight;
  112008. /* If the right-hand side is also a column, then the affinities
  112009. ** of both right and left sides must be such that no type
  112010. ** conversions are required on the right. (Ticket #2249)
  112011. */
  112012. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  112013. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  112014. if( affRight!=0 && affRight!=affLeft ){
  112015. okToChngToIN = 0;
  112016. }else{
  112017. pOrTerm->wtFlags |= TERM_OR_OK;
  112018. }
  112019. }
  112020. }
  112021. }
  112022. /* At this point, okToChngToIN is true if original pTerm satisfies
  112023. ** case 1. In that case, construct a new virtual term that is
  112024. ** pTerm converted into an IN operator.
  112025. */
  112026. if( okToChngToIN ){
  112027. Expr *pDup; /* A transient duplicate expression */
  112028. ExprList *pList = 0; /* The RHS of the IN operator */
  112029. Expr *pLeft = 0; /* The LHS of the IN operator */
  112030. Expr *pNew; /* The complete IN operator */
  112031. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  112032. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  112033. assert( pOrTerm->eOperator & WO_EQ );
  112034. assert( pOrTerm->leftCursor==iCursor );
  112035. assert( pOrTerm->u.leftColumn==iColumn );
  112036. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  112037. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  112038. pLeft = pOrTerm->pExpr->pLeft;
  112039. }
  112040. assert( pLeft!=0 );
  112041. pDup = sqlite3ExprDup(db, pLeft, 0);
  112042. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  112043. if( pNew ){
  112044. int idxNew;
  112045. transferJoinMarkings(pNew, pExpr);
  112046. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  112047. pNew->x.pList = pList;
  112048. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  112049. testcase( idxNew==0 );
  112050. exprAnalyze(pSrc, pWC, idxNew);
  112051. pTerm = &pWC->a[idxTerm];
  112052. markTermAsChild(pWC, idxNew, idxTerm);
  112053. }else{
  112054. sqlite3ExprListDelete(db, pList);
  112055. }
  112056. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
  112057. }
  112058. }
  112059. }
  112060. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  112061. /*
  112062. ** We already know that pExpr is a binary operator where both operands are
  112063. ** column references. This routine checks to see if pExpr is an equivalence
  112064. ** relation:
  112065. ** 1. The SQLITE_Transitive optimization must be enabled
  112066. ** 2. Must be either an == or an IS operator
  112067. ** 3. Not originating in the ON clause of an OUTER JOIN
  112068. ** 4. The affinities of A and B must be compatible
  112069. ** 5a. Both operands use the same collating sequence OR
  112070. ** 5b. The overall collating sequence is BINARY
  112071. ** If this routine returns TRUE, that means that the RHS can be substituted
  112072. ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
  112073. ** This is an optimization. No harm comes from returning 0. But if 1 is
  112074. ** returned when it should not be, then incorrect answers might result.
  112075. */
  112076. static int termIsEquivalence(Parse *pParse, Expr *pExpr){
  112077. char aff1, aff2;
  112078. CollSeq *pColl;
  112079. const char *zColl1, *zColl2;
  112080. if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
  112081. if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
  112082. if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
  112083. aff1 = sqlite3ExprAffinity(pExpr->pLeft);
  112084. aff2 = sqlite3ExprAffinity(pExpr->pRight);
  112085. if( aff1!=aff2
  112086. && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
  112087. ){
  112088. return 0;
  112089. }
  112090. pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
  112091. if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
  112092. pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  112093. /* Since pLeft and pRight are both a column references, their collating
  112094. ** sequence should always be defined. */
  112095. zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
  112096. pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
  112097. zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
  112098. return sqlite3StrICmp(zColl1, zColl2)==0;
  112099. }
  112100. /*
  112101. ** Recursively walk the expressions of a SELECT statement and generate
  112102. ** a bitmask indicating which tables are used in that expression
  112103. ** tree.
  112104. */
  112105. static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
  112106. Bitmask mask = 0;
  112107. while( pS ){
  112108. SrcList *pSrc = pS->pSrc;
  112109. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
  112110. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
  112111. mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
  112112. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
  112113. mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
  112114. if( ALWAYS(pSrc!=0) ){
  112115. int i;
  112116. for(i=0; i<pSrc->nSrc; i++){
  112117. mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
  112118. mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
  112119. }
  112120. }
  112121. pS = pS->pPrior;
  112122. }
  112123. return mask;
  112124. }
  112125. /*
  112126. ** The input to this routine is an WhereTerm structure with only the
  112127. ** "pExpr" field filled in. The job of this routine is to analyze the
  112128. ** subexpression and populate all the other fields of the WhereTerm
  112129. ** structure.
  112130. **
  112131. ** If the expression is of the form "<expr> <op> X" it gets commuted
  112132. ** to the standard form of "X <op> <expr>".
  112133. **
  112134. ** If the expression is of the form "X <op> Y" where both X and Y are
  112135. ** columns, then the original expression is unchanged and a new virtual
  112136. ** term of the form "Y <op> X" is added to the WHERE clause and
  112137. ** analyzed separately. The original term is marked with TERM_COPIED
  112138. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  112139. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  112140. ** is a commuted copy of a prior term.) The original term has nChild=1
  112141. ** and the copy has idxParent set to the index of the original term.
  112142. */
  112143. static void exprAnalyze(
  112144. SrcList *pSrc, /* the FROM clause */
  112145. WhereClause *pWC, /* the WHERE clause */
  112146. int idxTerm /* Index of the term to be analyzed */
  112147. ){
  112148. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  112149. WhereTerm *pTerm; /* The term to be analyzed */
  112150. WhereMaskSet *pMaskSet; /* Set of table index masks */
  112151. Expr *pExpr; /* The expression to be analyzed */
  112152. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  112153. Bitmask prereqAll; /* Prerequesites of pExpr */
  112154. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  112155. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  112156. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  112157. int noCase = 0; /* uppercase equivalent to lowercase */
  112158. int op; /* Top-level operator. pExpr->op */
  112159. Parse *pParse = pWInfo->pParse; /* Parsing context */
  112160. sqlite3 *db = pParse->db; /* Database connection */
  112161. if( db->mallocFailed ){
  112162. return;
  112163. }
  112164. pTerm = &pWC->a[idxTerm];
  112165. pMaskSet = &pWInfo->sMaskSet;
  112166. pExpr = pTerm->pExpr;
  112167. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  112168. prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
  112169. op = pExpr->op;
  112170. if( op==TK_IN ){
  112171. assert( pExpr->pRight==0 );
  112172. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  112173. pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
  112174. }else{
  112175. pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
  112176. }
  112177. }else if( op==TK_ISNULL ){
  112178. pTerm->prereqRight = 0;
  112179. }else{
  112180. pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
  112181. }
  112182. prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
  112183. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  112184. Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
  112185. prereqAll |= x;
  112186. extraRight = x-1; /* ON clause terms may not be used with an index
  112187. ** on left table of a LEFT JOIN. Ticket #3015 */
  112188. }
  112189. pTerm->prereqAll = prereqAll;
  112190. pTerm->leftCursor = -1;
  112191. pTerm->iParent = -1;
  112192. pTerm->eOperator = 0;
  112193. if( allowedOp(op) ){
  112194. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  112195. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  112196. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  112197. if( pLeft->op==TK_COLUMN ){
  112198. pTerm->leftCursor = pLeft->iTable;
  112199. pTerm->u.leftColumn = pLeft->iColumn;
  112200. pTerm->eOperator = operatorMask(op) & opMask;
  112201. }
  112202. if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
  112203. if( pRight && pRight->op==TK_COLUMN ){
  112204. WhereTerm *pNew;
  112205. Expr *pDup;
  112206. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  112207. if( pTerm->leftCursor>=0 ){
  112208. int idxNew;
  112209. pDup = sqlite3ExprDup(db, pExpr, 0);
  112210. if( db->mallocFailed ){
  112211. sqlite3ExprDelete(db, pDup);
  112212. return;
  112213. }
  112214. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  112215. if( idxNew==0 ) return;
  112216. pNew = &pWC->a[idxNew];
  112217. markTermAsChild(pWC, idxNew, idxTerm);
  112218. if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
  112219. pTerm = &pWC->a[idxTerm];
  112220. pTerm->wtFlags |= TERM_COPIED;
  112221. if( termIsEquivalence(pParse, pDup) ){
  112222. pTerm->eOperator |= WO_EQUIV;
  112223. eExtraOp = WO_EQUIV;
  112224. }
  112225. }else{
  112226. pDup = pExpr;
  112227. pNew = pTerm;
  112228. }
  112229. exprCommute(pParse, pDup);
  112230. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  112231. pNew->leftCursor = pLeft->iTable;
  112232. pNew->u.leftColumn = pLeft->iColumn;
  112233. testcase( (prereqLeft | extraRight) != prereqLeft );
  112234. pNew->prereqRight = prereqLeft | extraRight;
  112235. pNew->prereqAll = prereqAll;
  112236. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  112237. }
  112238. }
  112239. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  112240. /* If a term is the BETWEEN operator, create two new virtual terms
  112241. ** that define the range that the BETWEEN implements. For example:
  112242. **
  112243. ** a BETWEEN b AND c
  112244. **
  112245. ** is converted into:
  112246. **
  112247. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  112248. **
  112249. ** The two new terms are added onto the end of the WhereClause object.
  112250. ** The new terms are "dynamic" and are children of the original BETWEEN
  112251. ** term. That means that if the BETWEEN term is coded, the children are
  112252. ** skipped. Or, if the children are satisfied by an index, the original
  112253. ** BETWEEN term is skipped.
  112254. */
  112255. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  112256. ExprList *pList = pExpr->x.pList;
  112257. int i;
  112258. static const u8 ops[] = {TK_GE, TK_LE};
  112259. assert( pList!=0 );
  112260. assert( pList->nExpr==2 );
  112261. for(i=0; i<2; i++){
  112262. Expr *pNewExpr;
  112263. int idxNew;
  112264. pNewExpr = sqlite3PExpr(pParse, ops[i],
  112265. sqlite3ExprDup(db, pExpr->pLeft, 0),
  112266. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  112267. transferJoinMarkings(pNewExpr, pExpr);
  112268. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  112269. testcase( idxNew==0 );
  112270. exprAnalyze(pSrc, pWC, idxNew);
  112271. pTerm = &pWC->a[idxTerm];
  112272. markTermAsChild(pWC, idxNew, idxTerm);
  112273. }
  112274. }
  112275. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  112276. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  112277. /* Analyze a term that is composed of two or more subterms connected by
  112278. ** an OR operator.
  112279. */
  112280. else if( pExpr->op==TK_OR ){
  112281. assert( pWC->op==TK_AND );
  112282. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  112283. pTerm = &pWC->a[idxTerm];
  112284. }
  112285. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  112286. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  112287. /* Add constraints to reduce the search space on a LIKE or GLOB
  112288. ** operator.
  112289. **
  112290. ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
  112291. **
  112292. ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
  112293. **
  112294. ** The last character of the prefix "abc" is incremented to form the
  112295. ** termination condition "abd". If case is not significant (the default
  112296. ** for LIKE) then the lower-bound is made all uppercase and the upper-
  112297. ** bound is made all lowercase so that the bounds also work when comparing
  112298. ** BLOBs.
  112299. */
  112300. if( pWC->op==TK_AND
  112301. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  112302. ){
  112303. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  112304. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  112305. Expr *pNewExpr1;
  112306. Expr *pNewExpr2;
  112307. int idxNew1;
  112308. int idxNew2;
  112309. const char *zCollSeqName; /* Name of collating sequence */
  112310. const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
  112311. pLeft = pExpr->x.pList->a[1].pExpr;
  112312. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  112313. /* Convert the lower bound to upper-case and the upper bound to
  112314. ** lower-case (upper-case is less than lower-case in ASCII) so that
  112315. ** the range constraints also work for BLOBs
  112316. */
  112317. if( noCase && !pParse->db->mallocFailed ){
  112318. int i;
  112319. char c;
  112320. pTerm->wtFlags |= TERM_LIKE;
  112321. for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
  112322. pStr1->u.zToken[i] = sqlite3Toupper(c);
  112323. pStr2->u.zToken[i] = sqlite3Tolower(c);
  112324. }
  112325. }
  112326. if( !db->mallocFailed ){
  112327. u8 c, *pC; /* Last character before the first wildcard */
  112328. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  112329. c = *pC;
  112330. if( noCase ){
  112331. /* The point is to increment the last character before the first
  112332. ** wildcard. But if we increment '@', that will push it into the
  112333. ** alphabetic range where case conversions will mess up the
  112334. ** inequality. To avoid this, make sure to also run the full
  112335. ** LIKE on all candidate expressions by clearing the isComplete flag
  112336. */
  112337. if( c=='A'-1 ) isComplete = 0;
  112338. c = sqlite3UpperToLower[c];
  112339. }
  112340. *pC = c + 1;
  112341. }
  112342. zCollSeqName = noCase ? "NOCASE" : "BINARY";
  112343. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  112344. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  112345. sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
  112346. pStr1, 0);
  112347. transferJoinMarkings(pNewExpr1, pExpr);
  112348. idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
  112349. testcase( idxNew1==0 );
  112350. exprAnalyze(pSrc, pWC, idxNew1);
  112351. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  112352. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  112353. sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
  112354. pStr2, 0);
  112355. transferJoinMarkings(pNewExpr2, pExpr);
  112356. idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
  112357. testcase( idxNew2==0 );
  112358. exprAnalyze(pSrc, pWC, idxNew2);
  112359. pTerm = &pWC->a[idxTerm];
  112360. if( isComplete ){
  112361. markTermAsChild(pWC, idxNew1, idxTerm);
  112362. markTermAsChild(pWC, idxNew2, idxTerm);
  112363. }
  112364. }
  112365. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  112366. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112367. /* Add a WO_MATCH auxiliary term to the constraint set if the
  112368. ** current expression is of the form: column MATCH expr.
  112369. ** This information is used by the xBestIndex methods of
  112370. ** virtual tables. The native query optimizer does not attempt
  112371. ** to do anything with MATCH functions.
  112372. */
  112373. if( isMatchOfColumn(pExpr) ){
  112374. int idxNew;
  112375. Expr *pRight, *pLeft;
  112376. WhereTerm *pNewTerm;
  112377. Bitmask prereqColumn, prereqExpr;
  112378. pRight = pExpr->x.pList->a[0].pExpr;
  112379. pLeft = pExpr->x.pList->a[1].pExpr;
  112380. prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
  112381. prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
  112382. if( (prereqExpr & prereqColumn)==0 ){
  112383. Expr *pNewExpr;
  112384. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  112385. 0, sqlite3ExprDup(db, pRight, 0), 0);
  112386. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  112387. testcase( idxNew==0 );
  112388. pNewTerm = &pWC->a[idxNew];
  112389. pNewTerm->prereqRight = prereqExpr;
  112390. pNewTerm->leftCursor = pLeft->iTable;
  112391. pNewTerm->u.leftColumn = pLeft->iColumn;
  112392. pNewTerm->eOperator = WO_MATCH;
  112393. markTermAsChild(pWC, idxNew, idxTerm);
  112394. pTerm = &pWC->a[idxTerm];
  112395. pTerm->wtFlags |= TERM_COPIED;
  112396. pNewTerm->prereqAll = pTerm->prereqAll;
  112397. }
  112398. }
  112399. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  112400. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  112401. /* When sqlite_stat3 histogram data is available an operator of the
  112402. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  112403. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  112404. ** virtual term of that form.
  112405. **
  112406. ** Note that the virtual term must be tagged with TERM_VNULL.
  112407. */
  112408. if( pExpr->op==TK_NOTNULL
  112409. && pExpr->pLeft->op==TK_COLUMN
  112410. && pExpr->pLeft->iColumn>=0
  112411. && OptimizationEnabled(db, SQLITE_Stat34)
  112412. ){
  112413. Expr *pNewExpr;
  112414. Expr *pLeft = pExpr->pLeft;
  112415. int idxNew;
  112416. WhereTerm *pNewTerm;
  112417. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  112418. sqlite3ExprDup(db, pLeft, 0),
  112419. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  112420. idxNew = whereClauseInsert(pWC, pNewExpr,
  112421. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  112422. if( idxNew ){
  112423. pNewTerm = &pWC->a[idxNew];
  112424. pNewTerm->prereqRight = 0;
  112425. pNewTerm->leftCursor = pLeft->iTable;
  112426. pNewTerm->u.leftColumn = pLeft->iColumn;
  112427. pNewTerm->eOperator = WO_GT;
  112428. markTermAsChild(pWC, idxNew, idxTerm);
  112429. pTerm = &pWC->a[idxTerm];
  112430. pTerm->wtFlags |= TERM_COPIED;
  112431. pNewTerm->prereqAll = pTerm->prereqAll;
  112432. }
  112433. }
  112434. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  112435. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  112436. ** an index for tables to the left of the join.
  112437. */
  112438. pTerm->prereqRight |= extraRight;
  112439. }
  112440. /***************************************************************************
  112441. ** Routines with file scope above. Interface to the rest of the where.c
  112442. ** subsystem follows.
  112443. ***************************************************************************/
  112444. /*
  112445. ** This routine identifies subexpressions in the WHERE clause where
  112446. ** each subexpression is separated by the AND operator or some other
  112447. ** operator specified in the op parameter. The WhereClause structure
  112448. ** is filled with pointers to subexpressions. For example:
  112449. **
  112450. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  112451. ** \________/ \_______________/ \________________/
  112452. ** slot[0] slot[1] slot[2]
  112453. **
  112454. ** The original WHERE clause in pExpr is unaltered. All this routine
  112455. ** does is make slot[] entries point to substructure within pExpr.
  112456. **
  112457. ** In the previous sentence and in the diagram, "slot[]" refers to
  112458. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  112459. ** all terms of the WHERE clause.
  112460. */
  112461. SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  112462. Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
  112463. pWC->op = op;
  112464. if( pE2==0 ) return;
  112465. if( pE2->op!=op ){
  112466. whereClauseInsert(pWC, pExpr, 0);
  112467. }else{
  112468. sqlite3WhereSplit(pWC, pE2->pLeft, op);
  112469. sqlite3WhereSplit(pWC, pE2->pRight, op);
  112470. }
  112471. }
  112472. /*
  112473. ** Initialize a preallocated WhereClause structure.
  112474. */
  112475. SQLITE_PRIVATE void sqlite3WhereClauseInit(
  112476. WhereClause *pWC, /* The WhereClause to be initialized */
  112477. WhereInfo *pWInfo /* The WHERE processing context */
  112478. ){
  112479. pWC->pWInfo = pWInfo;
  112480. pWC->pOuter = 0;
  112481. pWC->nTerm = 0;
  112482. pWC->nSlot = ArraySize(pWC->aStatic);
  112483. pWC->a = pWC->aStatic;
  112484. }
  112485. /*
  112486. ** Deallocate a WhereClause structure. The WhereClause structure
  112487. ** itself is not freed. This routine is the inverse of sqlite3WhereClauseInit().
  112488. */
  112489. SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *pWC){
  112490. int i;
  112491. WhereTerm *a;
  112492. sqlite3 *db = pWC->pWInfo->pParse->db;
  112493. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  112494. if( a->wtFlags & TERM_DYNAMIC ){
  112495. sqlite3ExprDelete(db, a->pExpr);
  112496. }
  112497. if( a->wtFlags & TERM_ORINFO ){
  112498. whereOrInfoDelete(db, a->u.pOrInfo);
  112499. }else if( a->wtFlags & TERM_ANDINFO ){
  112500. whereAndInfoDelete(db, a->u.pAndInfo);
  112501. }
  112502. }
  112503. if( pWC->a!=pWC->aStatic ){
  112504. sqlite3DbFree(db, pWC->a);
  112505. }
  112506. }
  112507. /*
  112508. ** These routines walk (recursively) an expression tree and generate
  112509. ** a bitmask indicating which tables are used in that expression
  112510. ** tree.
  112511. */
  112512. SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
  112513. Bitmask mask = 0;
  112514. if( p==0 ) return 0;
  112515. if( p->op==TK_COLUMN ){
  112516. mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
  112517. return mask;
  112518. }
  112519. mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
  112520. mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
  112521. if( ExprHasProperty(p, EP_xIsSelect) ){
  112522. mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
  112523. }else{
  112524. mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
  112525. }
  112526. return mask;
  112527. }
  112528. SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  112529. int i;
  112530. Bitmask mask = 0;
  112531. if( pList ){
  112532. for(i=0; i<pList->nExpr; i++){
  112533. mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
  112534. }
  112535. }
  112536. return mask;
  112537. }
  112538. /*
  112539. ** Call exprAnalyze on all terms in a WHERE clause.
  112540. **
  112541. ** Note that exprAnalyze() might add new virtual terms onto the
  112542. ** end of the WHERE clause. We do not want to analyze these new
  112543. ** virtual terms, so start analyzing at the end and work forward
  112544. ** so that the added virtual terms are never processed.
  112545. */
  112546. SQLITE_PRIVATE void sqlite3WhereExprAnalyze(
  112547. SrcList *pTabList, /* the FROM clause */
  112548. WhereClause *pWC /* the WHERE clause to be analyzed */
  112549. ){
  112550. int i;
  112551. for(i=pWC->nTerm-1; i>=0; i--){
  112552. exprAnalyze(pTabList, pWC, i);
  112553. }
  112554. }
  112555. /************** End of whereexpr.c *******************************************/
  112556. /************** Begin file where.c *******************************************/
  112557. /*
  112558. ** 2001 September 15
  112559. **
  112560. ** The author disclaims copyright to this source code. In place of
  112561. ** a legal notice, here is a blessing:
  112562. **
  112563. ** May you do good and not evil.
  112564. ** May you find forgiveness for yourself and forgive others.
  112565. ** May you share freely, never taking more than you give.
  112566. **
  112567. *************************************************************************
  112568. ** This module contains C code that generates VDBE code used to process
  112569. ** the WHERE clause of SQL statements. This module is responsible for
  112570. ** generating the code that loops through a table looking for applicable
  112571. ** rows. Indices are selected and used to speed the search when doing
  112572. ** so is applicable. Because this module is responsible for selecting
  112573. ** indices, you might also think of this module as the "query optimizer".
  112574. */
  112575. /* #include "sqliteInt.h" */
  112576. /* #include "whereInt.h" */
  112577. /* Forward declaration of methods */
  112578. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  112579. /* Test variable that can be set to enable WHERE tracing */
  112580. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  112581. /***/ int sqlite3WhereTrace = 0;
  112582. #endif
  112583. /*
  112584. ** Return the estimated number of output rows from a WHERE clause
  112585. */
  112586. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  112587. return sqlite3LogEstToInt(pWInfo->nRowOut);
  112588. }
  112589. /*
  112590. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  112591. ** WHERE clause returns outputs for DISTINCT processing.
  112592. */
  112593. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  112594. return pWInfo->eDistinct;
  112595. }
  112596. /*
  112597. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  112598. ** Return FALSE if the output needs to be sorted.
  112599. */
  112600. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  112601. return pWInfo->nOBSat;
  112602. }
  112603. /*
  112604. ** Return the VDBE address or label to jump to in order to continue
  112605. ** immediately with the next row of a WHERE clause.
  112606. */
  112607. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  112608. assert( pWInfo->iContinue!=0 );
  112609. return pWInfo->iContinue;
  112610. }
  112611. /*
  112612. ** Return the VDBE address or label to jump to in order to break
  112613. ** out of a WHERE loop.
  112614. */
  112615. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  112616. return pWInfo->iBreak;
  112617. }
  112618. /*
  112619. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  112620. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  112621. ** UPDATE or DELETE might change subsequent WHERE clause results.
  112622. **
  112623. ** If the ONEPASS optimization is used (if this routine returns true)
  112624. ** then also write the indices of open cursors used by ONEPASS
  112625. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  112626. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  112627. ** Either value may be -1, indicating that cursor is not used.
  112628. ** Any cursors returned will have been opened for writing.
  112629. **
  112630. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  112631. ** unable to use the ONEPASS optimization.
  112632. */
  112633. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  112634. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  112635. return pWInfo->okOnePass;
  112636. }
  112637. /*
  112638. ** Move the content of pSrc into pDest
  112639. */
  112640. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  112641. pDest->n = pSrc->n;
  112642. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  112643. }
  112644. /*
  112645. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  112646. **
  112647. ** The new entry might overwrite an existing entry, or it might be
  112648. ** appended, or it might be discarded. Do whatever is the right thing
  112649. ** so that pSet keeps the N_OR_COST best entries seen so far.
  112650. */
  112651. static int whereOrInsert(
  112652. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  112653. Bitmask prereq, /* Prerequisites of the new entry */
  112654. LogEst rRun, /* Run-cost of the new entry */
  112655. LogEst nOut /* Number of outputs for the new entry */
  112656. ){
  112657. u16 i;
  112658. WhereOrCost *p;
  112659. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  112660. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  112661. goto whereOrInsert_done;
  112662. }
  112663. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  112664. return 0;
  112665. }
  112666. }
  112667. if( pSet->n<N_OR_COST ){
  112668. p = &pSet->a[pSet->n++];
  112669. p->nOut = nOut;
  112670. }else{
  112671. p = pSet->a;
  112672. for(i=1; i<pSet->n; i++){
  112673. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  112674. }
  112675. if( p->rRun<=rRun ) return 0;
  112676. }
  112677. whereOrInsert_done:
  112678. p->prereq = prereq;
  112679. p->rRun = rRun;
  112680. if( p->nOut>nOut ) p->nOut = nOut;
  112681. return 1;
  112682. }
  112683. /*
  112684. ** Return the bitmask for the given cursor number. Return 0 if
  112685. ** iCursor is not in the set.
  112686. */
  112687. SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
  112688. int i;
  112689. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  112690. for(i=0; i<pMaskSet->n; i++){
  112691. if( pMaskSet->ix[i]==iCursor ){
  112692. return MASKBIT(i);
  112693. }
  112694. }
  112695. return 0;
  112696. }
  112697. /*
  112698. ** Create a new mask for cursor iCursor.
  112699. **
  112700. ** There is one cursor per table in the FROM clause. The number of
  112701. ** tables in the FROM clause is limited by a test early in the
  112702. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  112703. ** array will never overflow.
  112704. */
  112705. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  112706. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  112707. pMaskSet->ix[pMaskSet->n++] = iCursor;
  112708. }
  112709. /*
  112710. ** Advance to the next WhereTerm that matches according to the criteria
  112711. ** established when the pScan object was initialized by whereScanInit().
  112712. ** Return NULL if there are no more matching WhereTerms.
  112713. */
  112714. static WhereTerm *whereScanNext(WhereScan *pScan){
  112715. int iCur; /* The cursor on the LHS of the term */
  112716. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  112717. Expr *pX; /* An expression being tested */
  112718. WhereClause *pWC; /* Shorthand for pScan->pWC */
  112719. WhereTerm *pTerm; /* The term being tested */
  112720. int k = pScan->k; /* Where to start scanning */
  112721. while( pScan->iEquiv<=pScan->nEquiv ){
  112722. iCur = pScan->aEquiv[pScan->iEquiv-2];
  112723. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  112724. while( (pWC = pScan->pWC)!=0 ){
  112725. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  112726. if( pTerm->leftCursor==iCur
  112727. && pTerm->u.leftColumn==iColumn
  112728. && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  112729. ){
  112730. if( (pTerm->eOperator & WO_EQUIV)!=0
  112731. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  112732. ){
  112733. int j;
  112734. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  112735. assert( pX->op==TK_COLUMN );
  112736. for(j=0; j<pScan->nEquiv; j+=2){
  112737. if( pScan->aEquiv[j]==pX->iTable
  112738. && pScan->aEquiv[j+1]==pX->iColumn ){
  112739. break;
  112740. }
  112741. }
  112742. if( j==pScan->nEquiv ){
  112743. pScan->aEquiv[j] = pX->iTable;
  112744. pScan->aEquiv[j+1] = pX->iColumn;
  112745. pScan->nEquiv += 2;
  112746. }
  112747. }
  112748. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  112749. /* Verify the affinity and collating sequence match */
  112750. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  112751. CollSeq *pColl;
  112752. Parse *pParse = pWC->pWInfo->pParse;
  112753. pX = pTerm->pExpr;
  112754. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  112755. continue;
  112756. }
  112757. assert(pX->pLeft);
  112758. pColl = sqlite3BinaryCompareCollSeq(pParse,
  112759. pX->pLeft, pX->pRight);
  112760. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  112761. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  112762. continue;
  112763. }
  112764. }
  112765. if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
  112766. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  112767. && pX->iTable==pScan->aEquiv[0]
  112768. && pX->iColumn==pScan->aEquiv[1]
  112769. ){
  112770. testcase( pTerm->eOperator & WO_IS );
  112771. continue;
  112772. }
  112773. pScan->k = k+1;
  112774. return pTerm;
  112775. }
  112776. }
  112777. }
  112778. pScan->pWC = pScan->pWC->pOuter;
  112779. k = 0;
  112780. }
  112781. pScan->pWC = pScan->pOrigWC;
  112782. k = 0;
  112783. pScan->iEquiv += 2;
  112784. }
  112785. return 0;
  112786. }
  112787. /*
  112788. ** Initialize a WHERE clause scanner object. Return a pointer to the
  112789. ** first match. Return NULL if there are no matches.
  112790. **
  112791. ** The scanner will be searching the WHERE clause pWC. It will look
  112792. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  112793. ** iCur. The <op> must be one of the operators described by opMask.
  112794. **
  112795. ** If the search is for X and the WHERE clause contains terms of the
  112796. ** form X=Y then this routine might also return terms of the form
  112797. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  112798. ** but is enough to handle most commonly occurring SQL statements.
  112799. **
  112800. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  112801. ** index pIdx.
  112802. */
  112803. static WhereTerm *whereScanInit(
  112804. WhereScan *pScan, /* The WhereScan object being initialized */
  112805. WhereClause *pWC, /* The WHERE clause to be scanned */
  112806. int iCur, /* Cursor to scan for */
  112807. int iColumn, /* Column to scan for */
  112808. u32 opMask, /* Operator(s) to scan for */
  112809. Index *pIdx /* Must be compatible with this index */
  112810. ){
  112811. int j;
  112812. /* memset(pScan, 0, sizeof(*pScan)); */
  112813. pScan->pOrigWC = pWC;
  112814. pScan->pWC = pWC;
  112815. if( pIdx && iColumn>=0 ){
  112816. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  112817. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  112818. if( NEVER(j>pIdx->nColumn) ) return 0;
  112819. }
  112820. pScan->zCollName = pIdx->azColl[j];
  112821. }else{
  112822. pScan->idxaff = 0;
  112823. pScan->zCollName = 0;
  112824. }
  112825. pScan->opMask = opMask;
  112826. pScan->k = 0;
  112827. pScan->aEquiv[0] = iCur;
  112828. pScan->aEquiv[1] = iColumn;
  112829. pScan->nEquiv = 2;
  112830. pScan->iEquiv = 2;
  112831. return whereScanNext(pScan);
  112832. }
  112833. /*
  112834. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  112835. ** where X is a reference to the iColumn of table iCur and <op> is one of
  112836. ** the WO_xx operator codes specified by the op parameter.
  112837. ** Return a pointer to the term. Return 0 if not found.
  112838. **
  112839. ** The term returned might by Y=<expr> if there is another constraint in
  112840. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  112841. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  112842. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  112843. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  112844. ** and the second is for the column number. There are 22 slots in aEquiv[]
  112845. ** so that means we can look for X plus up to 10 other equivalent values.
  112846. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  112847. ** and ... and A9=A10 and A10=<expr>.
  112848. **
  112849. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  112850. ** then try for the one with no dependencies on <expr> - in other words where
  112851. ** <expr> is a constant expression of some kind. Only return entries of
  112852. ** the form "X <op> Y" where Y is a column in another table if no terms of
  112853. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  112854. ** exist, try to return a term that does not use WO_EQUIV.
  112855. */
  112856. SQLITE_PRIVATE WhereTerm *sqlite3WhereFindTerm(
  112857. WhereClause *pWC, /* The WHERE clause to be searched */
  112858. int iCur, /* Cursor number of LHS */
  112859. int iColumn, /* Column number of LHS */
  112860. Bitmask notReady, /* RHS must not overlap with this mask */
  112861. u32 op, /* Mask of WO_xx values describing operator */
  112862. Index *pIdx /* Must be compatible with this index, if not NULL */
  112863. ){
  112864. WhereTerm *pResult = 0;
  112865. WhereTerm *p;
  112866. WhereScan scan;
  112867. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  112868. op &= WO_EQ|WO_IS;
  112869. while( p ){
  112870. if( (p->prereqRight & notReady)==0 ){
  112871. if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
  112872. testcase( p->eOperator & WO_IS );
  112873. return p;
  112874. }
  112875. if( pResult==0 ) pResult = p;
  112876. }
  112877. p = whereScanNext(&scan);
  112878. }
  112879. return pResult;
  112880. }
  112881. /*
  112882. ** This function searches pList for an entry that matches the iCol-th column
  112883. ** of index pIdx.
  112884. **
  112885. ** If such an expression is found, its index in pList->a[] is returned. If
  112886. ** no expression is found, -1 is returned.
  112887. */
  112888. static int findIndexCol(
  112889. Parse *pParse, /* Parse context */
  112890. ExprList *pList, /* Expression list to search */
  112891. int iBase, /* Cursor for table associated with pIdx */
  112892. Index *pIdx, /* Index to match column of */
  112893. int iCol /* Column of index to match */
  112894. ){
  112895. int i;
  112896. const char *zColl = pIdx->azColl[iCol];
  112897. for(i=0; i<pList->nExpr; i++){
  112898. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  112899. if( p->op==TK_COLUMN
  112900. && p->iColumn==pIdx->aiColumn[iCol]
  112901. && p->iTable==iBase
  112902. ){
  112903. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  112904. if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  112905. return i;
  112906. }
  112907. }
  112908. }
  112909. return -1;
  112910. }
  112911. /*
  112912. ** Return true if the DISTINCT expression-list passed as the third argument
  112913. ** is redundant.
  112914. **
  112915. ** A DISTINCT list is redundant if any subset of the columns in the
  112916. ** DISTINCT list are collectively unique and individually non-null.
  112917. */
  112918. static int isDistinctRedundant(
  112919. Parse *pParse, /* Parsing context */
  112920. SrcList *pTabList, /* The FROM clause */
  112921. WhereClause *pWC, /* The WHERE clause */
  112922. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  112923. ){
  112924. Table *pTab;
  112925. Index *pIdx;
  112926. int i;
  112927. int iBase;
  112928. /* If there is more than one table or sub-select in the FROM clause of
  112929. ** this query, then it will not be possible to show that the DISTINCT
  112930. ** clause is redundant. */
  112931. if( pTabList->nSrc!=1 ) return 0;
  112932. iBase = pTabList->a[0].iCursor;
  112933. pTab = pTabList->a[0].pTab;
  112934. /* If any of the expressions is an IPK column on table iBase, then return
  112935. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  112936. ** current SELECT is a correlated sub-query.
  112937. */
  112938. for(i=0; i<pDistinct->nExpr; i++){
  112939. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  112940. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  112941. }
  112942. /* Loop through all indices on the table, checking each to see if it makes
  112943. ** the DISTINCT qualifier redundant. It does so if:
  112944. **
  112945. ** 1. The index is itself UNIQUE, and
  112946. **
  112947. ** 2. All of the columns in the index are either part of the pDistinct
  112948. ** list, or else the WHERE clause contains a term of the form "col=X",
  112949. ** where X is a constant value. The collation sequences of the
  112950. ** comparison and select-list expressions must match those of the index.
  112951. **
  112952. ** 3. All of those index columns for which the WHERE clause does not
  112953. ** contain a "col=X" term are subject to a NOT NULL constraint.
  112954. */
  112955. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  112956. if( !IsUniqueIndex(pIdx) ) continue;
  112957. for(i=0; i<pIdx->nKeyCol; i++){
  112958. i16 iCol = pIdx->aiColumn[i];
  112959. if( 0==sqlite3WhereFindTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  112960. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  112961. if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
  112962. break;
  112963. }
  112964. }
  112965. }
  112966. if( i==pIdx->nKeyCol ){
  112967. /* This index implies that the DISTINCT qualifier is redundant. */
  112968. return 1;
  112969. }
  112970. }
  112971. return 0;
  112972. }
  112973. /*
  112974. ** Estimate the logarithm of the input value to base 2.
  112975. */
  112976. static LogEst estLog(LogEst N){
  112977. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  112978. }
  112979. /*
  112980. ** Convert OP_Column opcodes to OP_Copy in previously generated code.
  112981. **
  112982. ** This routine runs over generated VDBE code and translates OP_Column
  112983. ** opcodes into OP_Copy, and OP_Rowid into OP_Null, when the table is being
  112984. ** accessed via co-routine instead of via table lookup.
  112985. */
  112986. static void translateColumnToCopy(
  112987. Vdbe *v, /* The VDBE containing code to translate */
  112988. int iStart, /* Translate from this opcode to the end */
  112989. int iTabCur, /* OP_Column/OP_Rowid references to this table */
  112990. int iRegister /* The first column is in this register */
  112991. ){
  112992. VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
  112993. int iEnd = sqlite3VdbeCurrentAddr(v);
  112994. for(; iStart<iEnd; iStart++, pOp++){
  112995. if( pOp->p1!=iTabCur ) continue;
  112996. if( pOp->opcode==OP_Column ){
  112997. pOp->opcode = OP_Copy;
  112998. pOp->p1 = pOp->p2 + iRegister;
  112999. pOp->p2 = pOp->p3;
  113000. pOp->p3 = 0;
  113001. }else if( pOp->opcode==OP_Rowid ){
  113002. pOp->opcode = OP_Null;
  113003. pOp->p1 = 0;
  113004. pOp->p3 = 0;
  113005. }
  113006. }
  113007. }
  113008. /*
  113009. ** Two routines for printing the content of an sqlite3_index_info
  113010. ** structure. Used for testing and debugging only. If neither
  113011. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  113012. ** are no-ops.
  113013. */
  113014. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  113015. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  113016. int i;
  113017. if( !sqlite3WhereTrace ) return;
  113018. for(i=0; i<p->nConstraint; i++){
  113019. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  113020. i,
  113021. p->aConstraint[i].iColumn,
  113022. p->aConstraint[i].iTermOffset,
  113023. p->aConstraint[i].op,
  113024. p->aConstraint[i].usable);
  113025. }
  113026. for(i=0; i<p->nOrderBy; i++){
  113027. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  113028. i,
  113029. p->aOrderBy[i].iColumn,
  113030. p->aOrderBy[i].desc);
  113031. }
  113032. }
  113033. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  113034. int i;
  113035. if( !sqlite3WhereTrace ) return;
  113036. for(i=0; i<p->nConstraint; i++){
  113037. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  113038. i,
  113039. p->aConstraintUsage[i].argvIndex,
  113040. p->aConstraintUsage[i].omit);
  113041. }
  113042. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  113043. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  113044. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  113045. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  113046. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  113047. }
  113048. #else
  113049. #define TRACE_IDX_INPUTS(A)
  113050. #define TRACE_IDX_OUTPUTS(A)
  113051. #endif
  113052. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  113053. /*
  113054. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  113055. ** could be used with an index to access pSrc, assuming an appropriate
  113056. ** index existed.
  113057. */
  113058. static int termCanDriveIndex(
  113059. WhereTerm *pTerm, /* WHERE clause term to check */
  113060. struct SrcList_item *pSrc, /* Table we are trying to access */
  113061. Bitmask notReady /* Tables in outer loops of the join */
  113062. ){
  113063. char aff;
  113064. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  113065. if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
  113066. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  113067. if( pTerm->u.leftColumn<0 ) return 0;
  113068. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  113069. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  113070. testcase( pTerm->pExpr->op==TK_IS );
  113071. return 1;
  113072. }
  113073. #endif
  113074. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  113075. /*
  113076. ** Generate code to construct the Index object for an automatic index
  113077. ** and to set up the WhereLevel object pLevel so that the code generator
  113078. ** makes use of the automatic index.
  113079. */
  113080. static void constructAutomaticIndex(
  113081. Parse *pParse, /* The parsing context */
  113082. WhereClause *pWC, /* The WHERE clause */
  113083. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  113084. Bitmask notReady, /* Mask of cursors that are not available */
  113085. WhereLevel *pLevel /* Write new index here */
  113086. ){
  113087. int nKeyCol; /* Number of columns in the constructed index */
  113088. WhereTerm *pTerm; /* A single term of the WHERE clause */
  113089. WhereTerm *pWCEnd; /* End of pWC->a[] */
  113090. Index *pIdx; /* Object describing the transient index */
  113091. Vdbe *v; /* Prepared statement under construction */
  113092. int addrInit; /* Address of the initialization bypass jump */
  113093. Table *pTable; /* The table being indexed */
  113094. int addrTop; /* Top of the index fill loop */
  113095. int regRecord; /* Register holding an index record */
  113096. int n; /* Column counter */
  113097. int i; /* Loop counter */
  113098. int mxBitCol; /* Maximum column in pSrc->colUsed */
  113099. CollSeq *pColl; /* Collating sequence to on a column */
  113100. WhereLoop *pLoop; /* The Loop object */
  113101. char *zNotUsed; /* Extra space on the end of pIdx */
  113102. Bitmask idxCols; /* Bitmap of columns used for indexing */
  113103. Bitmask extraCols; /* Bitmap of additional columns */
  113104. u8 sentWarning = 0; /* True if a warnning has been issued */
  113105. Expr *pPartial = 0; /* Partial Index Expression */
  113106. int iContinue = 0; /* Jump here to skip excluded rows */
  113107. struct SrcList_item *pTabItem; /* FROM clause term being indexed */
  113108. /* Generate code to skip over the creation and initialization of the
  113109. ** transient index on 2nd and subsequent iterations of the loop. */
  113110. v = pParse->pVdbe;
  113111. assert( v!=0 );
  113112. addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  113113. /* Count the number of columns that will be added to the index
  113114. ** and used to match WHERE clause constraints */
  113115. nKeyCol = 0;
  113116. pTable = pSrc->pTab;
  113117. pWCEnd = &pWC->a[pWC->nTerm];
  113118. pLoop = pLevel->pWLoop;
  113119. idxCols = 0;
  113120. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  113121. Expr *pExpr = pTerm->pExpr;
  113122. assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
  113123. || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
  113124. || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
  113125. if( pLoop->prereq==0
  113126. && (pTerm->wtFlags & TERM_VIRTUAL)==0
  113127. && !ExprHasProperty(pExpr, EP_FromJoin)
  113128. && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
  113129. pPartial = sqlite3ExprAnd(pParse->db, pPartial,
  113130. sqlite3ExprDup(pParse->db, pExpr, 0));
  113131. }
  113132. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  113133. int iCol = pTerm->u.leftColumn;
  113134. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  113135. testcase( iCol==BMS );
  113136. testcase( iCol==BMS-1 );
  113137. if( !sentWarning ){
  113138. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  113139. "automatic index on %s(%s)", pTable->zName,
  113140. pTable->aCol[iCol].zName);
  113141. sentWarning = 1;
  113142. }
  113143. if( (idxCols & cMask)==0 ){
  113144. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
  113145. goto end_auto_index_create;
  113146. }
  113147. pLoop->aLTerm[nKeyCol++] = pTerm;
  113148. idxCols |= cMask;
  113149. }
  113150. }
  113151. }
  113152. assert( nKeyCol>0 );
  113153. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  113154. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  113155. | WHERE_AUTO_INDEX;
  113156. /* Count the number of additional columns needed to create a
  113157. ** covering index. A "covering index" is an index that contains all
  113158. ** columns that are needed by the query. With a covering index, the
  113159. ** original table never needs to be accessed. Automatic indices must
  113160. ** be a covering index because the index will not be updated if the
  113161. ** original table changes and the index and table cannot both be used
  113162. ** if they go out of sync.
  113163. */
  113164. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  113165. mxBitCol = MIN(BMS-1,pTable->nCol);
  113166. testcase( pTable->nCol==BMS-1 );
  113167. testcase( pTable->nCol==BMS-2 );
  113168. for(i=0; i<mxBitCol; i++){
  113169. if( extraCols & MASKBIT(i) ) nKeyCol++;
  113170. }
  113171. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  113172. nKeyCol += pTable->nCol - BMS + 1;
  113173. }
  113174. /* Construct the Index object to describe this index */
  113175. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  113176. if( pIdx==0 ) goto end_auto_index_create;
  113177. pLoop->u.btree.pIndex = pIdx;
  113178. pIdx->zName = "auto-index";
  113179. pIdx->pTable = pTable;
  113180. n = 0;
  113181. idxCols = 0;
  113182. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  113183. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  113184. int iCol = pTerm->u.leftColumn;
  113185. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  113186. testcase( iCol==BMS-1 );
  113187. testcase( iCol==BMS );
  113188. if( (idxCols & cMask)==0 ){
  113189. Expr *pX = pTerm->pExpr;
  113190. idxCols |= cMask;
  113191. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  113192. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  113193. pIdx->azColl[n] = pColl ? pColl->zName : "BINARY";
  113194. n++;
  113195. }
  113196. }
  113197. }
  113198. assert( (u32)n==pLoop->u.btree.nEq );
  113199. /* Add additional columns needed to make the automatic index into
  113200. ** a covering index */
  113201. for(i=0; i<mxBitCol; i++){
  113202. if( extraCols & MASKBIT(i) ){
  113203. pIdx->aiColumn[n] = i;
  113204. pIdx->azColl[n] = "BINARY";
  113205. n++;
  113206. }
  113207. }
  113208. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  113209. for(i=BMS-1; i<pTable->nCol; i++){
  113210. pIdx->aiColumn[n] = i;
  113211. pIdx->azColl[n] = "BINARY";
  113212. n++;
  113213. }
  113214. }
  113215. assert( n==nKeyCol );
  113216. pIdx->aiColumn[n] = -1;
  113217. pIdx->azColl[n] = "BINARY";
  113218. /* Create the automatic index */
  113219. assert( pLevel->iIdxCur>=0 );
  113220. pLevel->iIdxCur = pParse->nTab++;
  113221. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  113222. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  113223. VdbeComment((v, "for %s", pTable->zName));
  113224. /* Fill the automatic index with content */
  113225. sqlite3ExprCachePush(pParse);
  113226. pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
  113227. if( pTabItem->viaCoroutine ){
  113228. int regYield = pTabItem->regReturn;
  113229. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  113230. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  113231. VdbeCoverage(v);
  113232. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  113233. }else{
  113234. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  113235. }
  113236. if( pPartial ){
  113237. iContinue = sqlite3VdbeMakeLabel(v);
  113238. sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
  113239. pLoop->wsFlags |= WHERE_PARTIALIDX;
  113240. }
  113241. regRecord = sqlite3GetTempReg(pParse);
  113242. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
  113243. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  113244. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  113245. if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
  113246. if( pTabItem->viaCoroutine ){
  113247. translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult);
  113248. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  113249. pTabItem->viaCoroutine = 0;
  113250. }else{
  113251. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  113252. }
  113253. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  113254. sqlite3VdbeJumpHere(v, addrTop);
  113255. sqlite3ReleaseTempReg(pParse, regRecord);
  113256. sqlite3ExprCachePop(pParse);
  113257. /* Jump here when skipping the initialization */
  113258. sqlite3VdbeJumpHere(v, addrInit);
  113259. end_auto_index_create:
  113260. sqlite3ExprDelete(pParse->db, pPartial);
  113261. }
  113262. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  113263. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113264. /*
  113265. ** Allocate and populate an sqlite3_index_info structure. It is the
  113266. ** responsibility of the caller to eventually release the structure
  113267. ** by passing the pointer returned by this function to sqlite3_free().
  113268. */
  113269. static sqlite3_index_info *allocateIndexInfo(
  113270. Parse *pParse,
  113271. WhereClause *pWC,
  113272. Bitmask mUnusable, /* Ignore terms with these prereqs */
  113273. struct SrcList_item *pSrc,
  113274. ExprList *pOrderBy
  113275. ){
  113276. int i, j;
  113277. int nTerm;
  113278. struct sqlite3_index_constraint *pIdxCons;
  113279. struct sqlite3_index_orderby *pIdxOrderBy;
  113280. struct sqlite3_index_constraint_usage *pUsage;
  113281. WhereTerm *pTerm;
  113282. int nOrderBy;
  113283. sqlite3_index_info *pIdxInfo;
  113284. /* Count the number of possible WHERE clause constraints referring
  113285. ** to this virtual table */
  113286. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  113287. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  113288. if( pTerm->prereqRight & mUnusable ) continue;
  113289. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  113290. testcase( pTerm->eOperator & WO_IN );
  113291. testcase( pTerm->eOperator & WO_ISNULL );
  113292. testcase( pTerm->eOperator & WO_IS );
  113293. testcase( pTerm->eOperator & WO_ALL );
  113294. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  113295. if( pTerm->wtFlags & TERM_VNULL ) continue;
  113296. nTerm++;
  113297. }
  113298. /* If the ORDER BY clause contains only columns in the current
  113299. ** virtual table then allocate space for the aOrderBy part of
  113300. ** the sqlite3_index_info structure.
  113301. */
  113302. nOrderBy = 0;
  113303. if( pOrderBy ){
  113304. int n = pOrderBy->nExpr;
  113305. for(i=0; i<n; i++){
  113306. Expr *pExpr = pOrderBy->a[i].pExpr;
  113307. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  113308. }
  113309. if( i==n){
  113310. nOrderBy = n;
  113311. }
  113312. }
  113313. /* Allocate the sqlite3_index_info structure
  113314. */
  113315. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  113316. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  113317. + sizeof(*pIdxOrderBy)*nOrderBy );
  113318. if( pIdxInfo==0 ){
  113319. sqlite3ErrorMsg(pParse, "out of memory");
  113320. return 0;
  113321. }
  113322. /* Initialize the structure. The sqlite3_index_info structure contains
  113323. ** many fields that are declared "const" to prevent xBestIndex from
  113324. ** changing them. We have to do some funky casting in order to
  113325. ** initialize those fields.
  113326. */
  113327. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  113328. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  113329. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  113330. *(int*)&pIdxInfo->nConstraint = nTerm;
  113331. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  113332. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  113333. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  113334. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  113335. pUsage;
  113336. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  113337. u8 op;
  113338. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  113339. if( pTerm->prereqRight & mUnusable ) continue;
  113340. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  113341. testcase( pTerm->eOperator & WO_IN );
  113342. testcase( pTerm->eOperator & WO_IS );
  113343. testcase( pTerm->eOperator & WO_ISNULL );
  113344. testcase( pTerm->eOperator & WO_ALL );
  113345. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
  113346. if( pTerm->wtFlags & TERM_VNULL ) continue;
  113347. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  113348. pIdxCons[j].iTermOffset = i;
  113349. op = (u8)pTerm->eOperator & WO_ALL;
  113350. if( op==WO_IN ) op = WO_EQ;
  113351. pIdxCons[j].op = op;
  113352. /* The direct assignment in the previous line is possible only because
  113353. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  113354. ** following asserts verify this fact. */
  113355. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  113356. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  113357. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  113358. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  113359. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  113360. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  113361. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  113362. j++;
  113363. }
  113364. for(i=0; i<nOrderBy; i++){
  113365. Expr *pExpr = pOrderBy->a[i].pExpr;
  113366. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  113367. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  113368. }
  113369. return pIdxInfo;
  113370. }
  113371. /*
  113372. ** The table object reference passed as the second argument to this function
  113373. ** must represent a virtual table. This function invokes the xBestIndex()
  113374. ** method of the virtual table with the sqlite3_index_info object that
  113375. ** comes in as the 3rd argument to this function.
  113376. **
  113377. ** If an error occurs, pParse is populated with an error message and a
  113378. ** non-zero value is returned. Otherwise, 0 is returned and the output
  113379. ** part of the sqlite3_index_info structure is left populated.
  113380. **
  113381. ** Whether or not an error is returned, it is the responsibility of the
  113382. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  113383. ** that this is required.
  113384. */
  113385. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  113386. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  113387. int i;
  113388. int rc;
  113389. TRACE_IDX_INPUTS(p);
  113390. rc = pVtab->pModule->xBestIndex(pVtab, p);
  113391. TRACE_IDX_OUTPUTS(p);
  113392. if( rc!=SQLITE_OK ){
  113393. if( rc==SQLITE_NOMEM ){
  113394. pParse->db->mallocFailed = 1;
  113395. }else if( !pVtab->zErrMsg ){
  113396. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  113397. }else{
  113398. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  113399. }
  113400. }
  113401. sqlite3_free(pVtab->zErrMsg);
  113402. pVtab->zErrMsg = 0;
  113403. for(i=0; i<p->nConstraint; i++){
  113404. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  113405. sqlite3ErrorMsg(pParse,
  113406. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  113407. }
  113408. }
  113409. return pParse->nErr;
  113410. }
  113411. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  113412. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113413. /*
  113414. ** Estimate the location of a particular key among all keys in an
  113415. ** index. Store the results in aStat as follows:
  113416. **
  113417. ** aStat[0] Est. number of rows less than pRec
  113418. ** aStat[1] Est. number of rows equal to pRec
  113419. **
  113420. ** Return the index of the sample that is the smallest sample that
  113421. ** is greater than or equal to pRec. Note that this index is not an index
  113422. ** into the aSample[] array - it is an index into a virtual set of samples
  113423. ** based on the contents of aSample[] and the number of fields in record
  113424. ** pRec.
  113425. */
  113426. static int whereKeyStats(
  113427. Parse *pParse, /* Database connection */
  113428. Index *pIdx, /* Index to consider domain of */
  113429. UnpackedRecord *pRec, /* Vector of values to consider */
  113430. int roundUp, /* Round up if true. Round down if false */
  113431. tRowcnt *aStat /* OUT: stats written here */
  113432. ){
  113433. IndexSample *aSample = pIdx->aSample;
  113434. int iCol; /* Index of required stats in anEq[] etc. */
  113435. int i; /* Index of first sample >= pRec */
  113436. int iSample; /* Smallest sample larger than or equal to pRec */
  113437. int iMin = 0; /* Smallest sample not yet tested */
  113438. int iTest; /* Next sample to test */
  113439. int res; /* Result of comparison operation */
  113440. int nField; /* Number of fields in pRec */
  113441. tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
  113442. #ifndef SQLITE_DEBUG
  113443. UNUSED_PARAMETER( pParse );
  113444. #endif
  113445. assert( pRec!=0 );
  113446. assert( pIdx->nSample>0 );
  113447. assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
  113448. /* Do a binary search to find the first sample greater than or equal
  113449. ** to pRec. If pRec contains a single field, the set of samples to search
  113450. ** is simply the aSample[] array. If the samples in aSample[] contain more
  113451. ** than one fields, all fields following the first are ignored.
  113452. **
  113453. ** If pRec contains N fields, where N is more than one, then as well as the
  113454. ** samples in aSample[] (truncated to N fields), the search also has to
  113455. ** consider prefixes of those samples. For example, if the set of samples
  113456. ** in aSample is:
  113457. **
  113458. ** aSample[0] = (a, 5)
  113459. ** aSample[1] = (a, 10)
  113460. ** aSample[2] = (b, 5)
  113461. ** aSample[3] = (c, 100)
  113462. ** aSample[4] = (c, 105)
  113463. **
  113464. ** Then the search space should ideally be the samples above and the
  113465. ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
  113466. ** the code actually searches this set:
  113467. **
  113468. ** 0: (a)
  113469. ** 1: (a, 5)
  113470. ** 2: (a, 10)
  113471. ** 3: (a, 10)
  113472. ** 4: (b)
  113473. ** 5: (b, 5)
  113474. ** 6: (c)
  113475. ** 7: (c, 100)
  113476. ** 8: (c, 105)
  113477. ** 9: (c, 105)
  113478. **
  113479. ** For each sample in the aSample[] array, N samples are present in the
  113480. ** effective sample array. In the above, samples 0 and 1 are based on
  113481. ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
  113482. **
  113483. ** Often, sample i of each block of N effective samples has (i+1) fields.
  113484. ** Except, each sample may be extended to ensure that it is greater than or
  113485. ** equal to the previous sample in the array. For example, in the above,
  113486. ** sample 2 is the first sample of a block of N samples, so at first it
  113487. ** appears that it should be 1 field in size. However, that would make it
  113488. ** smaller than sample 1, so the binary search would not work. As a result,
  113489. ** it is extended to two fields. The duplicates that this creates do not
  113490. ** cause any problems.
  113491. */
  113492. nField = pRec->nField;
  113493. iCol = 0;
  113494. iSample = pIdx->nSample * nField;
  113495. do{
  113496. int iSamp; /* Index in aSample[] of test sample */
  113497. int n; /* Number of fields in test sample */
  113498. iTest = (iMin+iSample)/2;
  113499. iSamp = iTest / nField;
  113500. if( iSamp>0 ){
  113501. /* The proposed effective sample is a prefix of sample aSample[iSamp].
  113502. ** Specifically, the shortest prefix of at least (1 + iTest%nField)
  113503. ** fields that is greater than the previous effective sample. */
  113504. for(n=(iTest % nField) + 1; n<nField; n++){
  113505. if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
  113506. }
  113507. }else{
  113508. n = iTest + 1;
  113509. }
  113510. pRec->nField = n;
  113511. res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
  113512. if( res<0 ){
  113513. iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
  113514. iMin = iTest+1;
  113515. }else if( res==0 && n<nField ){
  113516. iLower = aSample[iSamp].anLt[n-1];
  113517. iMin = iTest+1;
  113518. res = -1;
  113519. }else{
  113520. iSample = iTest;
  113521. iCol = n-1;
  113522. }
  113523. }while( res && iMin<iSample );
  113524. i = iSample / nField;
  113525. #ifdef SQLITE_DEBUG
  113526. /* The following assert statements check that the binary search code
  113527. ** above found the right answer. This block serves no purpose other
  113528. ** than to invoke the asserts. */
  113529. if( pParse->db->mallocFailed==0 ){
  113530. if( res==0 ){
  113531. /* If (res==0) is true, then pRec must be equal to sample i. */
  113532. assert( i<pIdx->nSample );
  113533. assert( iCol==nField-1 );
  113534. pRec->nField = nField;
  113535. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  113536. || pParse->db->mallocFailed
  113537. );
  113538. }else{
  113539. /* Unless i==pIdx->nSample, indicating that pRec is larger than
  113540. ** all samples in the aSample[] array, pRec must be smaller than the
  113541. ** (iCol+1) field prefix of sample i. */
  113542. assert( i<=pIdx->nSample && i>=0 );
  113543. pRec->nField = iCol+1;
  113544. assert( i==pIdx->nSample
  113545. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  113546. || pParse->db->mallocFailed );
  113547. /* if i==0 and iCol==0, then record pRec is smaller than all samples
  113548. ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
  113549. ** be greater than or equal to the (iCol) field prefix of sample i.
  113550. ** If (i>0), then pRec must also be greater than sample (i-1). */
  113551. if( iCol>0 ){
  113552. pRec->nField = iCol;
  113553. assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
  113554. || pParse->db->mallocFailed );
  113555. }
  113556. if( i>0 ){
  113557. pRec->nField = nField;
  113558. assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  113559. || pParse->db->mallocFailed );
  113560. }
  113561. }
  113562. }
  113563. #endif /* ifdef SQLITE_DEBUG */
  113564. if( res==0 ){
  113565. /* Record pRec is equal to sample i */
  113566. assert( iCol==nField-1 );
  113567. aStat[0] = aSample[i].anLt[iCol];
  113568. aStat[1] = aSample[i].anEq[iCol];
  113569. }else{
  113570. /* At this point, the (iCol+1) field prefix of aSample[i] is the first
  113571. ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
  113572. ** is larger than all samples in the array. */
  113573. tRowcnt iUpper, iGap;
  113574. if( i>=pIdx->nSample ){
  113575. iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  113576. }else{
  113577. iUpper = aSample[i].anLt[iCol];
  113578. }
  113579. if( iLower>=iUpper ){
  113580. iGap = 0;
  113581. }else{
  113582. iGap = iUpper - iLower;
  113583. }
  113584. if( roundUp ){
  113585. iGap = (iGap*2)/3;
  113586. }else{
  113587. iGap = iGap/3;
  113588. }
  113589. aStat[0] = iLower + iGap;
  113590. aStat[1] = pIdx->aAvgEq[iCol];
  113591. }
  113592. /* Restore the pRec->nField value before returning. */
  113593. pRec->nField = nField;
  113594. return i;
  113595. }
  113596. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  113597. /*
  113598. ** If it is not NULL, pTerm is a term that provides an upper or lower
  113599. ** bound on a range scan. Without considering pTerm, it is estimated
  113600. ** that the scan will visit nNew rows. This function returns the number
  113601. ** estimated to be visited after taking pTerm into account.
  113602. **
  113603. ** If the user explicitly specified a likelihood() value for this term,
  113604. ** then the return value is the likelihood multiplied by the number of
  113605. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  113606. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  113607. */
  113608. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  113609. LogEst nRet = nNew;
  113610. if( pTerm ){
  113611. if( pTerm->truthProb<=0 ){
  113612. nRet += pTerm->truthProb;
  113613. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  113614. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  113615. }
  113616. }
  113617. return nRet;
  113618. }
  113619. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113620. /*
  113621. ** This function is called to estimate the number of rows visited by a
  113622. ** range-scan on a skip-scan index. For example:
  113623. **
  113624. ** CREATE INDEX i1 ON t1(a, b, c);
  113625. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  113626. **
  113627. ** Value pLoop->nOut is currently set to the estimated number of rows
  113628. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  113629. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  113630. ** on the stat4 data for the index. this scan will be peformed multiple
  113631. ** times (once for each (a,b) combination that matches a=?) is dealt with
  113632. ** by the caller.
  113633. **
  113634. ** It does this by scanning through all stat4 samples, comparing values
  113635. ** extracted from pLower and pUpper with the corresponding column in each
  113636. ** sample. If L and U are the number of samples found to be less than or
  113637. ** equal to the values extracted from pLower and pUpper respectively, and
  113638. ** N is the total number of samples, the pLoop->nOut value is adjusted
  113639. ** as follows:
  113640. **
  113641. ** nOut = nOut * ( min(U - L, 1) / N )
  113642. **
  113643. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  113644. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  113645. ** U is set to N.
  113646. **
  113647. ** Normally, this function sets *pbDone to 1 before returning. However,
  113648. ** if no value can be extracted from either pLower or pUpper (and so the
  113649. ** estimate of the number of rows delivered remains unchanged), *pbDone
  113650. ** is left as is.
  113651. **
  113652. ** If an error occurs, an SQLite error code is returned. Otherwise,
  113653. ** SQLITE_OK.
  113654. */
  113655. static int whereRangeSkipScanEst(
  113656. Parse *pParse, /* Parsing & code generating context */
  113657. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  113658. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  113659. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  113660. int *pbDone /* Set to true if at least one expr. value extracted */
  113661. ){
  113662. Index *p = pLoop->u.btree.pIndex;
  113663. int nEq = pLoop->u.btree.nEq;
  113664. sqlite3 *db = pParse->db;
  113665. int nLower = -1;
  113666. int nUpper = p->nSample+1;
  113667. int rc = SQLITE_OK;
  113668. int iCol = p->aiColumn[nEq];
  113669. u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  113670. CollSeq *pColl;
  113671. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  113672. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  113673. sqlite3_value *pVal = 0; /* Value extracted from record */
  113674. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  113675. if( pLower ){
  113676. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  113677. nLower = 0;
  113678. }
  113679. if( pUpper && rc==SQLITE_OK ){
  113680. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  113681. nUpper = p2 ? 0 : p->nSample;
  113682. }
  113683. if( p1 || p2 ){
  113684. int i;
  113685. int nDiff;
  113686. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  113687. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  113688. if( rc==SQLITE_OK && p1 ){
  113689. int res = sqlite3MemCompare(p1, pVal, pColl);
  113690. if( res>=0 ) nLower++;
  113691. }
  113692. if( rc==SQLITE_OK && p2 ){
  113693. int res = sqlite3MemCompare(p2, pVal, pColl);
  113694. if( res>=0 ) nUpper++;
  113695. }
  113696. }
  113697. nDiff = (nUpper - nLower);
  113698. if( nDiff<=0 ) nDiff = 1;
  113699. /* If there is both an upper and lower bound specified, and the
  113700. ** comparisons indicate that they are close together, use the fallback
  113701. ** method (assume that the scan visits 1/64 of the rows) for estimating
  113702. ** the number of rows visited. Otherwise, estimate the number of rows
  113703. ** using the method described in the header comment for this function. */
  113704. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  113705. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  113706. pLoop->nOut -= nAdjust;
  113707. *pbDone = 1;
  113708. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  113709. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  113710. }
  113711. }else{
  113712. assert( *pbDone==0 );
  113713. }
  113714. sqlite3ValueFree(p1);
  113715. sqlite3ValueFree(p2);
  113716. sqlite3ValueFree(pVal);
  113717. return rc;
  113718. }
  113719. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  113720. /*
  113721. ** This function is used to estimate the number of rows that will be visited
  113722. ** by scanning an index for a range of values. The range may have an upper
  113723. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  113724. ** and lower bounds are represented by pLower and pUpper respectively. For
  113725. ** example, assuming that index p is on t1(a):
  113726. **
  113727. ** ... FROM t1 WHERE a > ? AND a < ? ...
  113728. ** |_____| |_____|
  113729. ** | |
  113730. ** pLower pUpper
  113731. **
  113732. ** If either of the upper or lower bound is not present, then NULL is passed in
  113733. ** place of the corresponding WhereTerm.
  113734. **
  113735. ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
  113736. ** column subject to the range constraint. Or, equivalently, the number of
  113737. ** equality constraints optimized by the proposed index scan. For example,
  113738. ** assuming index p is on t1(a, b), and the SQL query is:
  113739. **
  113740. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  113741. **
  113742. ** then nEq is set to 1 (as the range restricted column, b, is the second
  113743. ** left-most column of the index). Or, if the query is:
  113744. **
  113745. ** ... FROM t1 WHERE a > ? AND a < ? ...
  113746. **
  113747. ** then nEq is set to 0.
  113748. **
  113749. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  113750. ** number of rows that the index scan is expected to visit without
  113751. ** considering the range constraints. If nEq is 0, then *pnOut is the number of
  113752. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  113753. ** to account for the range constraints pLower and pUpper.
  113754. **
  113755. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  113756. ** used, a single range inequality reduces the search space by a factor of 4.
  113757. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  113758. ** rows visited by a factor of 64.
  113759. */
  113760. static int whereRangeScanEst(
  113761. Parse *pParse, /* Parsing & code generating context */
  113762. WhereLoopBuilder *pBuilder,
  113763. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  113764. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  113765. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  113766. ){
  113767. int rc = SQLITE_OK;
  113768. int nOut = pLoop->nOut;
  113769. LogEst nNew;
  113770. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113771. Index *p = pLoop->u.btree.pIndex;
  113772. int nEq = pLoop->u.btree.nEq;
  113773. if( p->nSample>0 && nEq<p->nSampleCol ){
  113774. if( nEq==pBuilder->nRecValid ){
  113775. UnpackedRecord *pRec = pBuilder->pRec;
  113776. tRowcnt a[2];
  113777. u8 aff;
  113778. /* Variable iLower will be set to the estimate of the number of rows in
  113779. ** the index that are less than the lower bound of the range query. The
  113780. ** lower bound being the concatenation of $P and $L, where $P is the
  113781. ** key-prefix formed by the nEq values matched against the nEq left-most
  113782. ** columns of the index, and $L is the value in pLower.
  113783. **
  113784. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  113785. ** is not a simple variable or literal value), the lower bound of the
  113786. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  113787. ** if $L is available, whereKeyStats() is called for both ($P) and
  113788. ** ($P:$L) and the larger of the two returned values is used.
  113789. **
  113790. ** Similarly, iUpper is to be set to the estimate of the number of rows
  113791. ** less than the upper bound of the range query. Where the upper bound
  113792. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  113793. ** of iUpper are requested of whereKeyStats() and the smaller used.
  113794. **
  113795. ** The number of rows between the two bounds is then just iUpper-iLower.
  113796. */
  113797. tRowcnt iLower; /* Rows less than the lower bound */
  113798. tRowcnt iUpper; /* Rows less than the upper bound */
  113799. int iLwrIdx = -2; /* aSample[] for the lower bound */
  113800. int iUprIdx = -1; /* aSample[] for the upper bound */
  113801. if( pRec ){
  113802. testcase( pRec->nField!=pBuilder->nRecValid );
  113803. pRec->nField = pBuilder->nRecValid;
  113804. }
  113805. if( nEq==p->nKeyCol ){
  113806. aff = SQLITE_AFF_INTEGER;
  113807. }else{
  113808. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  113809. }
  113810. /* Determine iLower and iUpper using ($P) only. */
  113811. if( nEq==0 ){
  113812. iLower = 0;
  113813. iUpper = p->nRowEst0;
  113814. }else{
  113815. /* Note: this call could be optimized away - since the same values must
  113816. ** have been requested when testing key $P in whereEqualScanEst(). */
  113817. whereKeyStats(pParse, p, pRec, 0, a);
  113818. iLower = a[0];
  113819. iUpper = a[0] + a[1];
  113820. }
  113821. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  113822. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  113823. assert( p->aSortOrder!=0 );
  113824. if( p->aSortOrder[nEq] ){
  113825. /* The roles of pLower and pUpper are swapped for a DESC index */
  113826. SWAP(WhereTerm*, pLower, pUpper);
  113827. }
  113828. /* If possible, improve on the iLower estimate using ($P:$L). */
  113829. if( pLower ){
  113830. int bOk; /* True if value is extracted from pExpr */
  113831. Expr *pExpr = pLower->pExpr->pRight;
  113832. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  113833. if( rc==SQLITE_OK && bOk ){
  113834. tRowcnt iNew;
  113835. iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
  113836. iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  113837. if( iNew>iLower ) iLower = iNew;
  113838. nOut--;
  113839. pLower = 0;
  113840. }
  113841. }
  113842. /* If possible, improve on the iUpper estimate using ($P:$U). */
  113843. if( pUpper ){
  113844. int bOk; /* True if value is extracted from pExpr */
  113845. Expr *pExpr = pUpper->pExpr->pRight;
  113846. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  113847. if( rc==SQLITE_OK && bOk ){
  113848. tRowcnt iNew;
  113849. iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
  113850. iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  113851. if( iNew<iUpper ) iUpper = iNew;
  113852. nOut--;
  113853. pUpper = 0;
  113854. }
  113855. }
  113856. pBuilder->pRec = pRec;
  113857. if( rc==SQLITE_OK ){
  113858. if( iUpper>iLower ){
  113859. nNew = sqlite3LogEst(iUpper - iLower);
  113860. /* TUNING: If both iUpper and iLower are derived from the same
  113861. ** sample, then assume they are 4x more selective. This brings
  113862. ** the estimated selectivity more in line with what it would be
  113863. ** if estimated without the use of STAT3/4 tables. */
  113864. if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
  113865. }else{
  113866. nNew = 10; assert( 10==sqlite3LogEst(2) );
  113867. }
  113868. if( nNew<nOut ){
  113869. nOut = nNew;
  113870. }
  113871. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  113872. (u32)iLower, (u32)iUpper, nOut));
  113873. }
  113874. }else{
  113875. int bDone = 0;
  113876. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  113877. if( bDone ) return rc;
  113878. }
  113879. }
  113880. #else
  113881. UNUSED_PARAMETER(pParse);
  113882. UNUSED_PARAMETER(pBuilder);
  113883. assert( pLower || pUpper );
  113884. #endif
  113885. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  113886. nNew = whereRangeAdjust(pLower, nOut);
  113887. nNew = whereRangeAdjust(pUpper, nNew);
  113888. /* TUNING: If there is both an upper and lower limit and neither limit
  113889. ** has an application-defined likelihood(), assume the range is
  113890. ** reduced by an additional 75%. This means that, by default, an open-ended
  113891. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  113892. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  113893. ** match 1/64 of the index. */
  113894. if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
  113895. nNew -= 20;
  113896. }
  113897. nOut -= (pLower!=0) + (pUpper!=0);
  113898. if( nNew<10 ) nNew = 10;
  113899. if( nNew<nOut ) nOut = nNew;
  113900. #if defined(WHERETRACE_ENABLED)
  113901. if( pLoop->nOut>nOut ){
  113902. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  113903. pLoop->nOut, nOut));
  113904. }
  113905. #endif
  113906. pLoop->nOut = (LogEst)nOut;
  113907. return rc;
  113908. }
  113909. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113910. /*
  113911. ** Estimate the number of rows that will be returned based on
  113912. ** an equality constraint x=VALUE and where that VALUE occurs in
  113913. ** the histogram data. This only works when x is the left-most
  113914. ** column of an index and sqlite_stat3 histogram data is available
  113915. ** for that index. When pExpr==NULL that means the constraint is
  113916. ** "x IS NULL" instead of "x=VALUE".
  113917. **
  113918. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  113919. ** If unable to make an estimate, leave *pnRow unchanged and return
  113920. ** non-zero.
  113921. **
  113922. ** This routine can fail if it is unable to load a collating sequence
  113923. ** required for string comparison, or if unable to allocate memory
  113924. ** for a UTF conversion required for comparison. The error is stored
  113925. ** in the pParse structure.
  113926. */
  113927. static int whereEqualScanEst(
  113928. Parse *pParse, /* Parsing & code generating context */
  113929. WhereLoopBuilder *pBuilder,
  113930. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  113931. tRowcnt *pnRow /* Write the revised row estimate here */
  113932. ){
  113933. Index *p = pBuilder->pNew->u.btree.pIndex;
  113934. int nEq = pBuilder->pNew->u.btree.nEq;
  113935. UnpackedRecord *pRec = pBuilder->pRec;
  113936. u8 aff; /* Column affinity */
  113937. int rc; /* Subfunction return code */
  113938. tRowcnt a[2]; /* Statistics */
  113939. int bOk;
  113940. assert( nEq>=1 );
  113941. assert( nEq<=p->nColumn );
  113942. assert( p->aSample!=0 );
  113943. assert( p->nSample>0 );
  113944. assert( pBuilder->nRecValid<nEq );
  113945. /* If values are not available for all fields of the index to the left
  113946. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  113947. if( pBuilder->nRecValid<(nEq-1) ){
  113948. return SQLITE_NOTFOUND;
  113949. }
  113950. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  113951. ** below would return the same value. */
  113952. if( nEq>=p->nColumn ){
  113953. *pnRow = 1;
  113954. return SQLITE_OK;
  113955. }
  113956. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  113957. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  113958. pBuilder->pRec = pRec;
  113959. if( rc!=SQLITE_OK ) return rc;
  113960. if( bOk==0 ) return SQLITE_NOTFOUND;
  113961. pBuilder->nRecValid = nEq;
  113962. whereKeyStats(pParse, p, pRec, 0, a);
  113963. WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
  113964. *pnRow = a[1];
  113965. return rc;
  113966. }
  113967. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  113968. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  113969. /*
  113970. ** Estimate the number of rows that will be returned based on
  113971. ** an IN constraint where the right-hand side of the IN operator
  113972. ** is a list of values. Example:
  113973. **
  113974. ** WHERE x IN (1,2,3,4)
  113975. **
  113976. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  113977. ** If unable to make an estimate, leave *pnRow unchanged and return
  113978. ** non-zero.
  113979. **
  113980. ** This routine can fail if it is unable to load a collating sequence
  113981. ** required for string comparison, or if unable to allocate memory
  113982. ** for a UTF conversion required for comparison. The error is stored
  113983. ** in the pParse structure.
  113984. */
  113985. static int whereInScanEst(
  113986. Parse *pParse, /* Parsing & code generating context */
  113987. WhereLoopBuilder *pBuilder,
  113988. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  113989. tRowcnt *pnRow /* Write the revised row estimate here */
  113990. ){
  113991. Index *p = pBuilder->pNew->u.btree.pIndex;
  113992. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  113993. int nRecValid = pBuilder->nRecValid;
  113994. int rc = SQLITE_OK; /* Subfunction return code */
  113995. tRowcnt nEst; /* Number of rows for a single term */
  113996. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  113997. int i; /* Loop counter */
  113998. assert( p->aSample!=0 );
  113999. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  114000. nEst = nRow0;
  114001. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  114002. nRowEst += nEst;
  114003. pBuilder->nRecValid = nRecValid;
  114004. }
  114005. if( rc==SQLITE_OK ){
  114006. if( nRowEst > nRow0 ) nRowEst = nRow0;
  114007. *pnRow = nRowEst;
  114008. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  114009. }
  114010. assert( pBuilder->nRecValid==nRecValid );
  114011. return rc;
  114012. }
  114013. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  114014. #ifdef WHERETRACE_ENABLED
  114015. /*
  114016. ** Print the content of a WhereTerm object
  114017. */
  114018. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  114019. if( pTerm==0 ){
  114020. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  114021. }else{
  114022. char zType[4];
  114023. memcpy(zType, "...", 4);
  114024. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  114025. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  114026. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  114027. sqlite3DebugPrintf(
  114028. "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
  114029. iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
  114030. pTerm->eOperator, pTerm->wtFlags);
  114031. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  114032. }
  114033. }
  114034. #endif
  114035. #ifdef WHERETRACE_ENABLED
  114036. /*
  114037. ** Print a WhereLoop object for debugging purposes
  114038. */
  114039. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  114040. WhereInfo *pWInfo = pWC->pWInfo;
  114041. int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
  114042. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  114043. Table *pTab = pItem->pTab;
  114044. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  114045. p->iTab, nb, p->maskSelf, nb, p->prereq);
  114046. sqlite3DebugPrintf(" %12s",
  114047. pItem->zAlias ? pItem->zAlias : pTab->zName);
  114048. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  114049. const char *zName;
  114050. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  114051. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  114052. int i = sqlite3Strlen30(zName) - 1;
  114053. while( zName[i]!='_' ) i--;
  114054. zName += i;
  114055. }
  114056. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  114057. }else{
  114058. sqlite3DebugPrintf("%20s","");
  114059. }
  114060. }else{
  114061. char *z;
  114062. if( p->u.vtab.idxStr ){
  114063. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  114064. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  114065. }else{
  114066. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  114067. }
  114068. sqlite3DebugPrintf(" %-19s", z);
  114069. sqlite3_free(z);
  114070. }
  114071. if( p->wsFlags & WHERE_SKIPSCAN ){
  114072. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
  114073. }else{
  114074. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  114075. }
  114076. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  114077. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  114078. int i;
  114079. for(i=0; i<p->nLTerm; i++){
  114080. whereTermPrint(p->aLTerm[i], i);
  114081. }
  114082. }
  114083. }
  114084. #endif
  114085. /*
  114086. ** Convert bulk memory into a valid WhereLoop that can be passed
  114087. ** to whereLoopClear harmlessly.
  114088. */
  114089. static void whereLoopInit(WhereLoop *p){
  114090. p->aLTerm = p->aLTermSpace;
  114091. p->nLTerm = 0;
  114092. p->nLSlot = ArraySize(p->aLTermSpace);
  114093. p->wsFlags = 0;
  114094. }
  114095. /*
  114096. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  114097. */
  114098. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  114099. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  114100. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  114101. sqlite3_free(p->u.vtab.idxStr);
  114102. p->u.vtab.needFree = 0;
  114103. p->u.vtab.idxStr = 0;
  114104. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  114105. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  114106. sqlite3DbFree(db, p->u.btree.pIndex);
  114107. p->u.btree.pIndex = 0;
  114108. }
  114109. }
  114110. }
  114111. /*
  114112. ** Deallocate internal memory used by a WhereLoop object
  114113. */
  114114. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  114115. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  114116. whereLoopClearUnion(db, p);
  114117. whereLoopInit(p);
  114118. }
  114119. /*
  114120. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  114121. */
  114122. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  114123. WhereTerm **paNew;
  114124. if( p->nLSlot>=n ) return SQLITE_OK;
  114125. n = (n+7)&~7;
  114126. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  114127. if( paNew==0 ) return SQLITE_NOMEM;
  114128. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  114129. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  114130. p->aLTerm = paNew;
  114131. p->nLSlot = n;
  114132. return SQLITE_OK;
  114133. }
  114134. /*
  114135. ** Transfer content from the second pLoop into the first.
  114136. */
  114137. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  114138. whereLoopClearUnion(db, pTo);
  114139. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  114140. memset(&pTo->u, 0, sizeof(pTo->u));
  114141. return SQLITE_NOMEM;
  114142. }
  114143. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  114144. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  114145. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  114146. pFrom->u.vtab.needFree = 0;
  114147. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  114148. pFrom->u.btree.pIndex = 0;
  114149. }
  114150. return SQLITE_OK;
  114151. }
  114152. /*
  114153. ** Delete a WhereLoop object
  114154. */
  114155. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  114156. whereLoopClear(db, p);
  114157. sqlite3DbFree(db, p);
  114158. }
  114159. /*
  114160. ** Free a WhereInfo structure
  114161. */
  114162. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  114163. if( ALWAYS(pWInfo) ){
  114164. int i;
  114165. for(i=0; i<pWInfo->nLevel; i++){
  114166. WhereLevel *pLevel = &pWInfo->a[i];
  114167. if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
  114168. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  114169. }
  114170. }
  114171. sqlite3WhereClauseClear(&pWInfo->sWC);
  114172. while( pWInfo->pLoops ){
  114173. WhereLoop *p = pWInfo->pLoops;
  114174. pWInfo->pLoops = p->pNextLoop;
  114175. whereLoopDelete(db, p);
  114176. }
  114177. sqlite3DbFree(db, pWInfo);
  114178. }
  114179. }
  114180. /*
  114181. ** Return TRUE if all of the following are true:
  114182. **
  114183. ** (1) X has the same or lower cost that Y
  114184. ** (2) X is a proper subset of Y
  114185. ** (3) X skips at least as many columns as Y
  114186. **
  114187. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  114188. ** than Y and that every WHERE clause term used by X is also used
  114189. ** by Y.
  114190. **
  114191. ** If X is a proper subset of Y then Y is a better choice and ought
  114192. ** to have a lower cost. This routine returns TRUE when that cost
  114193. ** relationship is inverted and needs to be adjusted. The third rule
  114194. ** was added because if X uses skip-scan less than Y it still might
  114195. ** deserve a lower cost even if it is a proper subset of Y.
  114196. */
  114197. static int whereLoopCheaperProperSubset(
  114198. const WhereLoop *pX, /* First WhereLoop to compare */
  114199. const WhereLoop *pY /* Compare against this WhereLoop */
  114200. ){
  114201. int i, j;
  114202. if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
  114203. return 0; /* X is not a subset of Y */
  114204. }
  114205. if( pY->nSkip > pX->nSkip ) return 0;
  114206. if( pX->rRun >= pY->rRun ){
  114207. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  114208. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  114209. }
  114210. for(i=pX->nLTerm-1; i>=0; i--){
  114211. if( pX->aLTerm[i]==0 ) continue;
  114212. for(j=pY->nLTerm-1; j>=0; j--){
  114213. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  114214. }
  114215. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  114216. }
  114217. return 1; /* All conditions meet */
  114218. }
  114219. /*
  114220. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  114221. ** that:
  114222. **
  114223. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  114224. ** subset of pTemplate
  114225. **
  114226. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  114227. ** is a proper subset.
  114228. **
  114229. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  114230. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  114231. ** also used by Y.
  114232. */
  114233. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  114234. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  114235. for(; p; p=p->pNextLoop){
  114236. if( p->iTab!=pTemplate->iTab ) continue;
  114237. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  114238. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  114239. /* Adjust pTemplate cost downward so that it is cheaper than its
  114240. ** subset p. */
  114241. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  114242. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
  114243. pTemplate->rRun = p->rRun;
  114244. pTemplate->nOut = p->nOut - 1;
  114245. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  114246. /* Adjust pTemplate cost upward so that it is costlier than p since
  114247. ** pTemplate is a proper subset of p */
  114248. WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
  114249. pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
  114250. pTemplate->rRun = p->rRun;
  114251. pTemplate->nOut = p->nOut + 1;
  114252. }
  114253. }
  114254. }
  114255. /*
  114256. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  114257. ** supplanted by pTemplate.
  114258. **
  114259. ** Return NULL if the WhereLoop list contains an entry that can supplant
  114260. ** pTemplate, in other words if pTemplate does not belong on the list.
  114261. **
  114262. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  114263. ** link that points to pX.
  114264. **
  114265. ** If pTemplate cannot supplant any existing element of the list but needs
  114266. ** to be added to the list, then return a pointer to the tail of the list.
  114267. */
  114268. static WhereLoop **whereLoopFindLesser(
  114269. WhereLoop **ppPrev,
  114270. const WhereLoop *pTemplate
  114271. ){
  114272. WhereLoop *p;
  114273. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  114274. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  114275. /* If either the iTab or iSortIdx values for two WhereLoop are different
  114276. ** then those WhereLoops need to be considered separately. Neither is
  114277. ** a candidate to replace the other. */
  114278. continue;
  114279. }
  114280. /* In the current implementation, the rSetup value is either zero
  114281. ** or the cost of building an automatic index (NlogN) and the NlogN
  114282. ** is the same for compatible WhereLoops. */
  114283. assert( p->rSetup==0 || pTemplate->rSetup==0
  114284. || p->rSetup==pTemplate->rSetup );
  114285. /* whereLoopAddBtree() always generates and inserts the automatic index
  114286. ** case first. Hence compatible candidate WhereLoops never have a larger
  114287. ** rSetup. Call this SETUP-INVARIANT */
  114288. assert( p->rSetup>=pTemplate->rSetup );
  114289. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  114290. ** UNIQUE constraint) with one or more == constraints is better
  114291. ** than an automatic index. Unless it is a skip-scan. */
  114292. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  114293. && (pTemplate->nSkip)==0
  114294. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  114295. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  114296. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  114297. ){
  114298. break;
  114299. }
  114300. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  114301. ** discarded. WhereLoop p is better if:
  114302. ** (1) p has no more dependencies than pTemplate, and
  114303. ** (2) p has an equal or lower cost than pTemplate
  114304. */
  114305. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  114306. && p->rSetup<=pTemplate->rSetup /* (2a) */
  114307. && p->rRun<=pTemplate->rRun /* (2b) */
  114308. && p->nOut<=pTemplate->nOut /* (2c) */
  114309. ){
  114310. return 0; /* Discard pTemplate */
  114311. }
  114312. /* If pTemplate is always better than p, then cause p to be overwritten
  114313. ** with pTemplate. pTemplate is better than p if:
  114314. ** (1) pTemplate has no more dependences than p, and
  114315. ** (2) pTemplate has an equal or lower cost than p.
  114316. */
  114317. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  114318. && p->rRun>=pTemplate->rRun /* (2a) */
  114319. && p->nOut>=pTemplate->nOut /* (2b) */
  114320. ){
  114321. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  114322. break; /* Cause p to be overwritten by pTemplate */
  114323. }
  114324. }
  114325. return ppPrev;
  114326. }
  114327. /*
  114328. ** Insert or replace a WhereLoop entry using the template supplied.
  114329. **
  114330. ** An existing WhereLoop entry might be overwritten if the new template
  114331. ** is better and has fewer dependencies. Or the template will be ignored
  114332. ** and no insert will occur if an existing WhereLoop is faster and has
  114333. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  114334. ** added based on the template.
  114335. **
  114336. ** If pBuilder->pOrSet is not NULL then we care about only the
  114337. ** prerequisites and rRun and nOut costs of the N best loops. That
  114338. ** information is gathered in the pBuilder->pOrSet object. This special
  114339. ** processing mode is used only for OR clause processing.
  114340. **
  114341. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  114342. ** still might overwrite similar loops with the new template if the
  114343. ** new template is better. Loops may be overwritten if the following
  114344. ** conditions are met:
  114345. **
  114346. ** (1) They have the same iTab.
  114347. ** (2) They have the same iSortIdx.
  114348. ** (3) The template has same or fewer dependencies than the current loop
  114349. ** (4) The template has the same or lower cost than the current loop
  114350. */
  114351. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  114352. WhereLoop **ppPrev, *p;
  114353. WhereInfo *pWInfo = pBuilder->pWInfo;
  114354. sqlite3 *db = pWInfo->pParse->db;
  114355. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  114356. ** and prereqs.
  114357. */
  114358. if( pBuilder->pOrSet!=0 ){
  114359. #if WHERETRACE_ENABLED
  114360. u16 n = pBuilder->pOrSet->n;
  114361. int x =
  114362. #endif
  114363. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  114364. pTemplate->nOut);
  114365. #if WHERETRACE_ENABLED /* 0x8 */
  114366. if( sqlite3WhereTrace & 0x8 ){
  114367. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  114368. whereLoopPrint(pTemplate, pBuilder->pWC);
  114369. }
  114370. #endif
  114371. return SQLITE_OK;
  114372. }
  114373. /* Look for an existing WhereLoop to replace with pTemplate
  114374. */
  114375. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  114376. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  114377. if( ppPrev==0 ){
  114378. /* There already exists a WhereLoop on the list that is better
  114379. ** than pTemplate, so just ignore pTemplate */
  114380. #if WHERETRACE_ENABLED /* 0x8 */
  114381. if( sqlite3WhereTrace & 0x8 ){
  114382. sqlite3DebugPrintf(" skip: ");
  114383. whereLoopPrint(pTemplate, pBuilder->pWC);
  114384. }
  114385. #endif
  114386. return SQLITE_OK;
  114387. }else{
  114388. p = *ppPrev;
  114389. }
  114390. /* If we reach this point it means that either p[] should be overwritten
  114391. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  114392. ** WhereLoop and insert it.
  114393. */
  114394. #if WHERETRACE_ENABLED /* 0x8 */
  114395. if( sqlite3WhereTrace & 0x8 ){
  114396. if( p!=0 ){
  114397. sqlite3DebugPrintf("replace: ");
  114398. whereLoopPrint(p, pBuilder->pWC);
  114399. }
  114400. sqlite3DebugPrintf(" add: ");
  114401. whereLoopPrint(pTemplate, pBuilder->pWC);
  114402. }
  114403. #endif
  114404. if( p==0 ){
  114405. /* Allocate a new WhereLoop to add to the end of the list */
  114406. *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  114407. if( p==0 ) return SQLITE_NOMEM;
  114408. whereLoopInit(p);
  114409. p->pNextLoop = 0;
  114410. }else{
  114411. /* We will be overwriting WhereLoop p[]. But before we do, first
  114412. ** go through the rest of the list and delete any other entries besides
  114413. ** p[] that are also supplated by pTemplate */
  114414. WhereLoop **ppTail = &p->pNextLoop;
  114415. WhereLoop *pToDel;
  114416. while( *ppTail ){
  114417. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  114418. if( ppTail==0 ) break;
  114419. pToDel = *ppTail;
  114420. if( pToDel==0 ) break;
  114421. *ppTail = pToDel->pNextLoop;
  114422. #if WHERETRACE_ENABLED /* 0x8 */
  114423. if( sqlite3WhereTrace & 0x8 ){
  114424. sqlite3DebugPrintf(" delete: ");
  114425. whereLoopPrint(pToDel, pBuilder->pWC);
  114426. }
  114427. #endif
  114428. whereLoopDelete(db, pToDel);
  114429. }
  114430. }
  114431. whereLoopXfer(db, p, pTemplate);
  114432. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  114433. Index *pIndex = p->u.btree.pIndex;
  114434. if( pIndex && pIndex->tnum==0 ){
  114435. p->u.btree.pIndex = 0;
  114436. }
  114437. }
  114438. return SQLITE_OK;
  114439. }
  114440. /*
  114441. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  114442. ** WHERE clause that reference the loop but which are not used by an
  114443. ** index.
  114444. *
  114445. ** For every WHERE clause term that is not used by the index
  114446. ** and which has a truth probability assigned by one of the likelihood(),
  114447. ** likely(), or unlikely() SQL functions, reduce the estimated number
  114448. ** of output rows by the probability specified.
  114449. **
  114450. ** TUNING: For every WHERE clause term that is not used by the index
  114451. ** and which does not have an assigned truth probability, heuristics
  114452. ** described below are used to try to estimate the truth probability.
  114453. ** TODO --> Perhaps this is something that could be improved by better
  114454. ** table statistics.
  114455. **
  114456. ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
  114457. ** value corresponds to -1 in LogEst notation, so this means decrement
  114458. ** the WhereLoop.nOut field for every such WHERE clause term.
  114459. **
  114460. ** Heuristic 2: If there exists one or more WHERE clause terms of the
  114461. ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
  114462. ** final output row estimate is no greater than 1/4 of the total number
  114463. ** of rows in the table. In other words, assume that x==EXPR will filter
  114464. ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
  114465. ** "x" column is boolean or else -1 or 0 or 1 is a common default value
  114466. ** on the "x" column and so in that case only cap the output row estimate
  114467. ** at 1/2 instead of 1/4.
  114468. */
  114469. static void whereLoopOutputAdjust(
  114470. WhereClause *pWC, /* The WHERE clause */
  114471. WhereLoop *pLoop, /* The loop to adjust downward */
  114472. LogEst nRow /* Number of rows in the entire table */
  114473. ){
  114474. WhereTerm *pTerm, *pX;
  114475. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  114476. int i, j, k;
  114477. LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
  114478. assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  114479. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  114480. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  114481. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  114482. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  114483. for(j=pLoop->nLTerm-1; j>=0; j--){
  114484. pX = pLoop->aLTerm[j];
  114485. if( pX==0 ) continue;
  114486. if( pX==pTerm ) break;
  114487. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  114488. }
  114489. if( j<0 ){
  114490. if( pTerm->truthProb<=0 ){
  114491. /* If a truth probability is specified using the likelihood() hints,
  114492. ** then use the probability provided by the application. */
  114493. pLoop->nOut += pTerm->truthProb;
  114494. }else{
  114495. /* In the absence of explicit truth probabilities, use heuristics to
  114496. ** guess a reasonable truth probability. */
  114497. pLoop->nOut--;
  114498. if( pTerm->eOperator&(WO_EQ|WO_IS) ){
  114499. Expr *pRight = pTerm->pExpr->pRight;
  114500. testcase( pTerm->pExpr->op==TK_IS );
  114501. if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
  114502. k = 10;
  114503. }else{
  114504. k = 20;
  114505. }
  114506. if( iReduce<k ) iReduce = k;
  114507. }
  114508. }
  114509. }
  114510. }
  114511. if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
  114512. }
  114513. /*
  114514. ** Adjust the cost C by the costMult facter T. This only occurs if
  114515. ** compiled with -DSQLITE_ENABLE_COSTMULT
  114516. */
  114517. #ifdef SQLITE_ENABLE_COSTMULT
  114518. # define ApplyCostMultiplier(C,T) C += T
  114519. #else
  114520. # define ApplyCostMultiplier(C,T)
  114521. #endif
  114522. /*
  114523. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  114524. ** index pIndex. Try to match one more.
  114525. **
  114526. ** When this function is called, pBuilder->pNew->nOut contains the
  114527. ** number of rows expected to be visited by filtering using the nEq
  114528. ** terms only. If it is modified, this value is restored before this
  114529. ** function returns.
  114530. **
  114531. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  114532. ** INTEGER PRIMARY KEY.
  114533. */
  114534. static int whereLoopAddBtreeIndex(
  114535. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  114536. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  114537. Index *pProbe, /* An index on pSrc */
  114538. LogEst nInMul /* log(Number of iterations due to IN) */
  114539. ){
  114540. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  114541. Parse *pParse = pWInfo->pParse; /* Parsing context */
  114542. sqlite3 *db = pParse->db; /* Database connection malloc context */
  114543. WhereLoop *pNew; /* Template WhereLoop under construction */
  114544. WhereTerm *pTerm; /* A WhereTerm under consideration */
  114545. int opMask; /* Valid operators for constraints */
  114546. WhereScan scan; /* Iterator for WHERE terms */
  114547. Bitmask saved_prereq; /* Original value of pNew->prereq */
  114548. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  114549. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  114550. u16 saved_nSkip; /* Original value of pNew->nSkip */
  114551. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  114552. LogEst saved_nOut; /* Original value of pNew->nOut */
  114553. int iCol; /* Index of the column in the table */
  114554. int rc = SQLITE_OK; /* Return code */
  114555. LogEst rSize; /* Number of rows in the table */
  114556. LogEst rLogSize; /* Logarithm of table size */
  114557. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  114558. pNew = pBuilder->pNew;
  114559. if( db->mallocFailed ) return SQLITE_NOMEM;
  114560. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  114561. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  114562. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  114563. opMask = WO_LT|WO_LE;
  114564. }else if( /*pProbe->tnum<=0 ||*/ (pSrc->jointype & JT_LEFT)!=0 ){
  114565. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  114566. }else{
  114567. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE|WO_ISNULL|WO_IS;
  114568. }
  114569. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  114570. assert( pNew->u.btree.nEq<pProbe->nColumn );
  114571. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  114572. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  114573. opMask, pProbe);
  114574. saved_nEq = pNew->u.btree.nEq;
  114575. saved_nSkip = pNew->nSkip;
  114576. saved_nLTerm = pNew->nLTerm;
  114577. saved_wsFlags = pNew->wsFlags;
  114578. saved_prereq = pNew->prereq;
  114579. saved_nOut = pNew->nOut;
  114580. pNew->rSetup = 0;
  114581. rSize = pProbe->aiRowLogEst[0];
  114582. rLogSize = estLog(rSize);
  114583. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  114584. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  114585. LogEst rCostIdx;
  114586. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  114587. int nIn = 0;
  114588. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114589. int nRecValid = pBuilder->nRecValid;
  114590. #endif
  114591. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  114592. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  114593. ){
  114594. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  114595. }
  114596. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  114597. /* Do not allow the upper bound of a LIKE optimization range constraint
  114598. ** to mix with a lower range bound from some other source */
  114599. if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
  114600. pNew->wsFlags = saved_wsFlags;
  114601. pNew->u.btree.nEq = saved_nEq;
  114602. pNew->nLTerm = saved_nLTerm;
  114603. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  114604. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  114605. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  114606. assert( nInMul==0
  114607. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  114608. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  114609. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  114610. );
  114611. if( eOp & WO_IN ){
  114612. Expr *pExpr = pTerm->pExpr;
  114613. pNew->wsFlags |= WHERE_COLUMN_IN;
  114614. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  114615. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  114616. nIn = 46; assert( 46==sqlite3LogEst(25) );
  114617. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  114618. /* "x IN (value, value, ...)" */
  114619. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  114620. }
  114621. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  114622. ** changes "x IN (?)" into "x=?". */
  114623. }else if( eOp & (WO_EQ|WO_IS) ){
  114624. pNew->wsFlags |= WHERE_COLUMN_EQ;
  114625. if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
  114626. if( iCol>=0 && pProbe->uniqNotNull==0 ){
  114627. pNew->wsFlags |= WHERE_UNQ_WANTED;
  114628. }else{
  114629. pNew->wsFlags |= WHERE_ONEROW;
  114630. }
  114631. }
  114632. }else if( eOp & WO_ISNULL ){
  114633. pNew->wsFlags |= WHERE_COLUMN_NULL;
  114634. }else if( eOp & (WO_GT|WO_GE) ){
  114635. testcase( eOp & WO_GT );
  114636. testcase( eOp & WO_GE );
  114637. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  114638. pBtm = pTerm;
  114639. pTop = 0;
  114640. if( pTerm->wtFlags & TERM_LIKEOPT ){
  114641. /* Range contraints that come from the LIKE optimization are
  114642. ** always used in pairs. */
  114643. pTop = &pTerm[1];
  114644. assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
  114645. assert( pTop->wtFlags & TERM_LIKEOPT );
  114646. assert( pTop->eOperator==WO_LT );
  114647. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  114648. pNew->aLTerm[pNew->nLTerm++] = pTop;
  114649. pNew->wsFlags |= WHERE_TOP_LIMIT;
  114650. }
  114651. }else{
  114652. assert( eOp & (WO_LT|WO_LE) );
  114653. testcase( eOp & WO_LT );
  114654. testcase( eOp & WO_LE );
  114655. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  114656. pTop = pTerm;
  114657. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  114658. pNew->aLTerm[pNew->nLTerm-2] : 0;
  114659. }
  114660. /* At this point pNew->nOut is set to the number of rows expected to
  114661. ** be visited by the index scan before considering term pTerm, or the
  114662. ** values of nIn and nInMul. In other words, assuming that all
  114663. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  114664. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  114665. assert( pNew->nOut==saved_nOut );
  114666. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  114667. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  114668. ** data, using some other estimate. */
  114669. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  114670. }else{
  114671. int nEq = ++pNew->u.btree.nEq;
  114672. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
  114673. assert( pNew->nOut==saved_nOut );
  114674. if( pTerm->truthProb<=0 && iCol>=0 ){
  114675. assert( (eOp & WO_IN) || nIn==0 );
  114676. testcase( eOp & WO_IN );
  114677. pNew->nOut += pTerm->truthProb;
  114678. pNew->nOut -= nIn;
  114679. }else{
  114680. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114681. tRowcnt nOut = 0;
  114682. if( nInMul==0
  114683. && pProbe->nSample
  114684. && pNew->u.btree.nEq<=pProbe->nSampleCol
  114685. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  114686. ){
  114687. Expr *pExpr = pTerm->pExpr;
  114688. if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
  114689. testcase( eOp & WO_EQ );
  114690. testcase( eOp & WO_IS );
  114691. testcase( eOp & WO_ISNULL );
  114692. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  114693. }else{
  114694. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  114695. }
  114696. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  114697. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  114698. if( nOut ){
  114699. pNew->nOut = sqlite3LogEst(nOut);
  114700. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  114701. pNew->nOut -= nIn;
  114702. }
  114703. }
  114704. if( nOut==0 )
  114705. #endif
  114706. {
  114707. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  114708. if( eOp & WO_ISNULL ){
  114709. /* TUNING: If there is no likelihood() value, assume that a
  114710. ** "col IS NULL" expression matches twice as many rows
  114711. ** as (col=?). */
  114712. pNew->nOut += 10;
  114713. }
  114714. }
  114715. }
  114716. }
  114717. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  114718. ** it to pNew->rRun, which is currently set to the cost of the index
  114719. ** seek only. Then, if this is a non-covering index, add the cost of
  114720. ** visiting the rows in the main table. */
  114721. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  114722. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  114723. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  114724. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  114725. }
  114726. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  114727. nOutUnadjusted = pNew->nOut;
  114728. pNew->rRun += nInMul + nIn;
  114729. pNew->nOut += nInMul + nIn;
  114730. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  114731. rc = whereLoopInsert(pBuilder, pNew);
  114732. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  114733. pNew->nOut = saved_nOut;
  114734. }else{
  114735. pNew->nOut = nOutUnadjusted;
  114736. }
  114737. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  114738. && pNew->u.btree.nEq<pProbe->nColumn
  114739. ){
  114740. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  114741. }
  114742. pNew->nOut = saved_nOut;
  114743. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  114744. pBuilder->nRecValid = nRecValid;
  114745. #endif
  114746. }
  114747. pNew->prereq = saved_prereq;
  114748. pNew->u.btree.nEq = saved_nEq;
  114749. pNew->nSkip = saved_nSkip;
  114750. pNew->wsFlags = saved_wsFlags;
  114751. pNew->nOut = saved_nOut;
  114752. pNew->nLTerm = saved_nLTerm;
  114753. /* Consider using a skip-scan if there are no WHERE clause constraints
  114754. ** available for the left-most terms of the index, and if the average
  114755. ** number of repeats in the left-most terms is at least 18.
  114756. **
  114757. ** The magic number 18 is selected on the basis that scanning 17 rows
  114758. ** is almost always quicker than an index seek (even though if the index
  114759. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  114760. ** the code). And, even if it is not, it should not be too much slower.
  114761. ** On the other hand, the extra seeks could end up being significantly
  114762. ** more expensive. */
  114763. assert( 42==sqlite3LogEst(18) );
  114764. if( saved_nEq==saved_nSkip
  114765. && saved_nEq+1<pProbe->nKeyCol
  114766. && pProbe->noSkipScan==0
  114767. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  114768. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  114769. ){
  114770. LogEst nIter;
  114771. pNew->u.btree.nEq++;
  114772. pNew->nSkip++;
  114773. pNew->aLTerm[pNew->nLTerm++] = 0;
  114774. pNew->wsFlags |= WHERE_SKIPSCAN;
  114775. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  114776. pNew->nOut -= nIter;
  114777. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  114778. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  114779. nIter += 5;
  114780. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  114781. pNew->nOut = saved_nOut;
  114782. pNew->u.btree.nEq = saved_nEq;
  114783. pNew->nSkip = saved_nSkip;
  114784. pNew->wsFlags = saved_wsFlags;
  114785. }
  114786. return rc;
  114787. }
  114788. /*
  114789. ** Return True if it is possible that pIndex might be useful in
  114790. ** implementing the ORDER BY clause in pBuilder.
  114791. **
  114792. ** Return False if pBuilder does not contain an ORDER BY clause or
  114793. ** if there is no way for pIndex to be useful in implementing that
  114794. ** ORDER BY clause.
  114795. */
  114796. static int indexMightHelpWithOrderBy(
  114797. WhereLoopBuilder *pBuilder,
  114798. Index *pIndex,
  114799. int iCursor
  114800. ){
  114801. ExprList *pOB;
  114802. int ii, jj;
  114803. if( pIndex->bUnordered ) return 0;
  114804. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  114805. for(ii=0; ii<pOB->nExpr; ii++){
  114806. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  114807. if( pExpr->op!=TK_COLUMN ) return 0;
  114808. if( pExpr->iTable==iCursor ){
  114809. if( pExpr->iColumn<0 ) return 1;
  114810. for(jj=0; jj<pIndex->nKeyCol; jj++){
  114811. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  114812. }
  114813. }
  114814. }
  114815. return 0;
  114816. }
  114817. /*
  114818. ** Return a bitmask where 1s indicate that the corresponding column of
  114819. ** the table is used by an index. Only the first 63 columns are considered.
  114820. */
  114821. static Bitmask columnsInIndex(Index *pIdx){
  114822. Bitmask m = 0;
  114823. int j;
  114824. for(j=pIdx->nColumn-1; j>=0; j--){
  114825. int x = pIdx->aiColumn[j];
  114826. if( x>=0 ){
  114827. testcase( x==BMS-1 );
  114828. testcase( x==BMS-2 );
  114829. if( x<BMS-1 ) m |= MASKBIT(x);
  114830. }
  114831. }
  114832. return m;
  114833. }
  114834. /* Check to see if a partial index with pPartIndexWhere can be used
  114835. ** in the current query. Return true if it can be and false if not.
  114836. */
  114837. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  114838. int i;
  114839. WhereTerm *pTerm;
  114840. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  114841. Expr *pExpr = pTerm->pExpr;
  114842. if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
  114843. && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
  114844. ){
  114845. return 1;
  114846. }
  114847. }
  114848. return 0;
  114849. }
  114850. /*
  114851. ** Add all WhereLoop objects for a single table of the join where the table
  114852. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  114853. ** a b-tree table, not a virtual table.
  114854. **
  114855. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  114856. ** are calculated as follows:
  114857. **
  114858. ** For a full scan, assuming the table (or index) contains nRow rows:
  114859. **
  114860. ** cost = nRow * 3.0 // full-table scan
  114861. ** cost = nRow * K // scan of covering index
  114862. ** cost = nRow * (K+3.0) // scan of non-covering index
  114863. **
  114864. ** where K is a value between 1.1 and 3.0 set based on the relative
  114865. ** estimated average size of the index and table records.
  114866. **
  114867. ** For an index scan, where nVisit is the number of index rows visited
  114868. ** by the scan, and nSeek is the number of seek operations required on
  114869. ** the index b-tree:
  114870. **
  114871. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  114872. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  114873. **
  114874. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  114875. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  114876. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  114877. **
  114878. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  114879. ** of uncertainty. For this reason, scoring is designed to pick plans that
  114880. ** "do the least harm" if the estimates are inaccurate. For example, a
  114881. ** log(nRow) factor is omitted from a non-covering index scan in order to
  114882. ** bias the scoring in favor of using an index, since the worst-case
  114883. ** performance of using an index is far better than the worst-case performance
  114884. ** of a full table scan.
  114885. */
  114886. static int whereLoopAddBtree(
  114887. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  114888. Bitmask mExtra /* Extra prerequesites for using this table */
  114889. ){
  114890. WhereInfo *pWInfo; /* WHERE analysis context */
  114891. Index *pProbe; /* An index we are evaluating */
  114892. Index sPk; /* A fake index object for the primary key */
  114893. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  114894. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  114895. SrcList *pTabList; /* The FROM clause */
  114896. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  114897. WhereLoop *pNew; /* Template WhereLoop object */
  114898. int rc = SQLITE_OK; /* Return code */
  114899. int iSortIdx = 1; /* Index number */
  114900. int b; /* A boolean value */
  114901. LogEst rSize; /* number of rows in the table */
  114902. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  114903. WhereClause *pWC; /* The parsed WHERE clause */
  114904. Table *pTab; /* Table being queried */
  114905. pNew = pBuilder->pNew;
  114906. pWInfo = pBuilder->pWInfo;
  114907. pTabList = pWInfo->pTabList;
  114908. pSrc = pTabList->a + pNew->iTab;
  114909. pTab = pSrc->pTab;
  114910. pWC = pBuilder->pWC;
  114911. assert( !IsVirtual(pSrc->pTab) );
  114912. if( pSrc->pIndex ){
  114913. /* An INDEXED BY clause specifies a particular index to use */
  114914. pProbe = pSrc->pIndex;
  114915. }else if( !HasRowid(pTab) ){
  114916. pProbe = pTab->pIndex;
  114917. }else{
  114918. /* There is no INDEXED BY clause. Create a fake Index object in local
  114919. ** variable sPk to represent the rowid primary key index. Make this
  114920. ** fake index the first in a chain of Index objects with all of the real
  114921. ** indices to follow */
  114922. Index *pFirst; /* First of real indices on the table */
  114923. memset(&sPk, 0, sizeof(Index));
  114924. sPk.nKeyCol = 1;
  114925. sPk.nColumn = 1;
  114926. sPk.aiColumn = &aiColumnPk;
  114927. sPk.aiRowLogEst = aiRowEstPk;
  114928. sPk.onError = OE_Replace;
  114929. sPk.pTable = pTab;
  114930. sPk.szIdxRow = pTab->szTabRow;
  114931. aiRowEstPk[0] = pTab->nRowLogEst;
  114932. aiRowEstPk[1] = 0;
  114933. pFirst = pSrc->pTab->pIndex;
  114934. if( pSrc->notIndexed==0 ){
  114935. /* The real indices of the table are only considered if the
  114936. ** NOT INDEXED qualifier is omitted from the FROM clause */
  114937. sPk.pNext = pFirst;
  114938. }
  114939. pProbe = &sPk;
  114940. }
  114941. rSize = pTab->nRowLogEst;
  114942. rLogSize = estLog(rSize);
  114943. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  114944. /* Automatic indexes */
  114945. if( !pBuilder->pOrSet /* Not part of an OR optimization */
  114946. && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
  114947. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  114948. && pSrc->pIndex==0 /* Has no INDEXED BY clause */
  114949. && !pSrc->notIndexed /* Has no NOT INDEXED clause */
  114950. && HasRowid(pTab) /* Is not a WITHOUT ROWID table. (FIXME: Why not?) */
  114951. && !pSrc->isCorrelated /* Not a correlated subquery */
  114952. && !pSrc->isRecursive /* Not a recursive common table expression. */
  114953. ){
  114954. /* Generate auto-index WhereLoops */
  114955. WhereTerm *pTerm;
  114956. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  114957. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  114958. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  114959. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  114960. pNew->u.btree.nEq = 1;
  114961. pNew->nSkip = 0;
  114962. pNew->u.btree.pIndex = 0;
  114963. pNew->nLTerm = 1;
  114964. pNew->aLTerm[0] = pTerm;
  114965. /* TUNING: One-time cost for computing the automatic index is
  114966. ** estimated to be X*N*log2(N) where N is the number of rows in
  114967. ** the table being indexed and where X is 7 (LogEst=28) for normal
  114968. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  114969. ** of X is smaller for views and subqueries so that the query planner
  114970. ** will be more aggressive about generating automatic indexes for
  114971. ** those objects, since there is no opportunity to add schema
  114972. ** indexes on subqueries and views. */
  114973. pNew->rSetup = rLogSize + rSize + 4;
  114974. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  114975. pNew->rSetup += 24;
  114976. }
  114977. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  114978. /* TUNING: Each index lookup yields 20 rows in the table. This
  114979. ** is more than the usual guess of 10 rows, since we have no way
  114980. ** of knowing how selective the index will ultimately be. It would
  114981. ** not be unreasonable to make this value much larger. */
  114982. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  114983. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  114984. pNew->wsFlags = WHERE_AUTO_INDEX;
  114985. pNew->prereq = mExtra | pTerm->prereqRight;
  114986. rc = whereLoopInsert(pBuilder, pNew);
  114987. }
  114988. }
  114989. }
  114990. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  114991. /* Loop over all indices
  114992. */
  114993. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  114994. if( pProbe->pPartIdxWhere!=0
  114995. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  114996. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  114997. continue; /* Partial index inappropriate for this query */
  114998. }
  114999. rSize = pProbe->aiRowLogEst[0];
  115000. pNew->u.btree.nEq = 0;
  115001. pNew->nSkip = 0;
  115002. pNew->nLTerm = 0;
  115003. pNew->iSortIdx = 0;
  115004. pNew->rSetup = 0;
  115005. pNew->prereq = mExtra;
  115006. pNew->nOut = rSize;
  115007. pNew->u.btree.pIndex = pProbe;
  115008. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  115009. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  115010. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  115011. if( pProbe->tnum<=0 ){
  115012. /* Integer primary key index */
  115013. pNew->wsFlags = WHERE_IPK;
  115014. /* Full table scan */
  115015. pNew->iSortIdx = b ? iSortIdx : 0;
  115016. /* TUNING: Cost of full table scan is (N*3.0). */
  115017. pNew->rRun = rSize + 16;
  115018. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  115019. whereLoopOutputAdjust(pWC, pNew, rSize);
  115020. rc = whereLoopInsert(pBuilder, pNew);
  115021. pNew->nOut = rSize;
  115022. if( rc ) break;
  115023. }else{
  115024. Bitmask m;
  115025. if( pProbe->isCovering ){
  115026. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  115027. m = 0;
  115028. }else{
  115029. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  115030. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  115031. }
  115032. /* Full scan via index */
  115033. if( b
  115034. || !HasRowid(pTab)
  115035. || ( m==0
  115036. && pProbe->bUnordered==0
  115037. && (pProbe->szIdxRow<pTab->szTabRow)
  115038. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  115039. && sqlite3GlobalConfig.bUseCis
  115040. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  115041. )
  115042. ){
  115043. pNew->iSortIdx = b ? iSortIdx : 0;
  115044. /* The cost of visiting the index rows is N*K, where K is
  115045. ** between 1.1 and 3.0, depending on the relative sizes of the
  115046. ** index and table rows. If this is a non-covering index scan,
  115047. ** also add the cost of visiting table rows (N*3.0). */
  115048. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  115049. if( m!=0 ){
  115050. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
  115051. }
  115052. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  115053. whereLoopOutputAdjust(pWC, pNew, rSize);
  115054. rc = whereLoopInsert(pBuilder, pNew);
  115055. pNew->nOut = rSize;
  115056. if( rc ) break;
  115057. }
  115058. }
  115059. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  115060. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  115061. sqlite3Stat4ProbeFree(pBuilder->pRec);
  115062. pBuilder->nRecValid = 0;
  115063. pBuilder->pRec = 0;
  115064. #endif
  115065. /* If there was an INDEXED BY clause, then only that one index is
  115066. ** considered. */
  115067. if( pSrc->pIndex ) break;
  115068. }
  115069. return rc;
  115070. }
  115071. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115072. /*
  115073. ** Add all WhereLoop objects for a table of the join identified by
  115074. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  115075. **
  115076. ** If there are no LEFT or CROSS JOIN joins in the query, both mExtra and
  115077. ** mUnusable are set to 0. Otherwise, mExtra is a mask of all FROM clause
  115078. ** entries that occur before the virtual table in the FROM clause and are
  115079. ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
  115080. ** mUnusable mask contains all FROM clause entries that occur after the
  115081. ** virtual table and are separated from it by at least one LEFT or
  115082. ** CROSS JOIN.
  115083. **
  115084. ** For example, if the query were:
  115085. **
  115086. ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
  115087. **
  115088. ** then mExtra corresponds to (t1, t2) and mUnusable to (t5, t6).
  115089. **
  115090. ** All the tables in mExtra must be scanned before the current virtual
  115091. ** table. So any terms for which all prerequisites are satisfied by
  115092. ** mExtra may be specified as "usable" in all calls to xBestIndex.
  115093. ** Conversely, all tables in mUnusable must be scanned after the current
  115094. ** virtual table, so any terms for which the prerequisites overlap with
  115095. ** mUnusable should always be configured as "not-usable" for xBestIndex.
  115096. */
  115097. static int whereLoopAddVirtual(
  115098. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  115099. Bitmask mExtra, /* Tables that must be scanned before this one */
  115100. Bitmask mUnusable /* Tables that must be scanned after this one */
  115101. ){
  115102. WhereInfo *pWInfo; /* WHERE analysis context */
  115103. Parse *pParse; /* The parsing context */
  115104. WhereClause *pWC; /* The WHERE clause */
  115105. struct SrcList_item *pSrc; /* The FROM clause term to search */
  115106. Table *pTab;
  115107. sqlite3 *db;
  115108. sqlite3_index_info *pIdxInfo;
  115109. struct sqlite3_index_constraint *pIdxCons;
  115110. struct sqlite3_index_constraint_usage *pUsage;
  115111. WhereTerm *pTerm;
  115112. int i, j;
  115113. int iTerm, mxTerm;
  115114. int nConstraint;
  115115. int seenIn = 0; /* True if an IN operator is seen */
  115116. int seenVar = 0; /* True if a non-constant constraint is seen */
  115117. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  115118. WhereLoop *pNew;
  115119. int rc = SQLITE_OK;
  115120. assert( (mExtra & mUnusable)==0 );
  115121. pWInfo = pBuilder->pWInfo;
  115122. pParse = pWInfo->pParse;
  115123. db = pParse->db;
  115124. pWC = pBuilder->pWC;
  115125. pNew = pBuilder->pNew;
  115126. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  115127. pTab = pSrc->pTab;
  115128. assert( IsVirtual(pTab) );
  115129. pIdxInfo = allocateIndexInfo(pParse, pWC, mUnusable, pSrc,pBuilder->pOrderBy);
  115130. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  115131. pNew->prereq = 0;
  115132. pNew->rSetup = 0;
  115133. pNew->wsFlags = WHERE_VIRTUALTABLE;
  115134. pNew->nLTerm = 0;
  115135. pNew->u.vtab.needFree = 0;
  115136. pUsage = pIdxInfo->aConstraintUsage;
  115137. nConstraint = pIdxInfo->nConstraint;
  115138. if( whereLoopResize(db, pNew, nConstraint) ){
  115139. sqlite3DbFree(db, pIdxInfo);
  115140. return SQLITE_NOMEM;
  115141. }
  115142. for(iPhase=0; iPhase<=3; iPhase++){
  115143. if( !seenIn && (iPhase&1)!=0 ){
  115144. iPhase++;
  115145. if( iPhase>3 ) break;
  115146. }
  115147. if( !seenVar && iPhase>1 ) break;
  115148. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  115149. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  115150. j = pIdxCons->iTermOffset;
  115151. pTerm = &pWC->a[j];
  115152. switch( iPhase ){
  115153. case 0: /* Constants without IN operator */
  115154. pIdxCons->usable = 0;
  115155. if( (pTerm->eOperator & WO_IN)!=0 ){
  115156. seenIn = 1;
  115157. }
  115158. if( (pTerm->prereqRight & ~mExtra)!=0 ){
  115159. seenVar = 1;
  115160. }else if( (pTerm->eOperator & WO_IN)==0 ){
  115161. pIdxCons->usable = 1;
  115162. }
  115163. break;
  115164. case 1: /* Constants with IN operators */
  115165. assert( seenIn );
  115166. pIdxCons->usable = (pTerm->prereqRight & ~mExtra)==0;
  115167. break;
  115168. case 2: /* Variables without IN */
  115169. assert( seenVar );
  115170. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  115171. break;
  115172. default: /* Variables with IN */
  115173. assert( seenVar && seenIn );
  115174. pIdxCons->usable = 1;
  115175. break;
  115176. }
  115177. }
  115178. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  115179. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  115180. pIdxInfo->idxStr = 0;
  115181. pIdxInfo->idxNum = 0;
  115182. pIdxInfo->needToFreeIdxStr = 0;
  115183. pIdxInfo->orderByConsumed = 0;
  115184. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  115185. pIdxInfo->estimatedRows = 25;
  115186. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  115187. if( rc ) goto whereLoopAddVtab_exit;
  115188. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  115189. pNew->prereq = mExtra;
  115190. mxTerm = -1;
  115191. assert( pNew->nLSlot>=nConstraint );
  115192. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  115193. pNew->u.vtab.omitMask = 0;
  115194. for(i=0; i<nConstraint; i++, pIdxCons++){
  115195. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  115196. j = pIdxCons->iTermOffset;
  115197. if( iTerm>=nConstraint
  115198. || j<0
  115199. || j>=pWC->nTerm
  115200. || pNew->aLTerm[iTerm]!=0
  115201. ){
  115202. rc = SQLITE_ERROR;
  115203. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  115204. goto whereLoopAddVtab_exit;
  115205. }
  115206. testcase( iTerm==nConstraint-1 );
  115207. testcase( j==0 );
  115208. testcase( j==pWC->nTerm-1 );
  115209. pTerm = &pWC->a[j];
  115210. pNew->prereq |= pTerm->prereqRight;
  115211. assert( iTerm<pNew->nLSlot );
  115212. pNew->aLTerm[iTerm] = pTerm;
  115213. if( iTerm>mxTerm ) mxTerm = iTerm;
  115214. testcase( iTerm==15 );
  115215. testcase( iTerm==16 );
  115216. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  115217. if( (pTerm->eOperator & WO_IN)!=0 ){
  115218. if( pUsage[i].omit==0 ){
  115219. /* Do not attempt to use an IN constraint if the virtual table
  115220. ** says that the equivalent EQ constraint cannot be safely omitted.
  115221. ** If we do attempt to use such a constraint, some rows might be
  115222. ** repeated in the output. */
  115223. break;
  115224. }
  115225. /* A virtual table that is constrained by an IN clause may not
  115226. ** consume the ORDER BY clause because (1) the order of IN terms
  115227. ** is not necessarily related to the order of output terms and
  115228. ** (2) Multiple outputs from a single IN value will not merge
  115229. ** together. */
  115230. pIdxInfo->orderByConsumed = 0;
  115231. }
  115232. }
  115233. }
  115234. if( i>=nConstraint ){
  115235. pNew->nLTerm = mxTerm+1;
  115236. assert( pNew->nLTerm<=pNew->nLSlot );
  115237. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  115238. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  115239. pIdxInfo->needToFreeIdxStr = 0;
  115240. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  115241. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  115242. pIdxInfo->nOrderBy : 0);
  115243. pNew->rSetup = 0;
  115244. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  115245. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  115246. whereLoopInsert(pBuilder, pNew);
  115247. if( pNew->u.vtab.needFree ){
  115248. sqlite3_free(pNew->u.vtab.idxStr);
  115249. pNew->u.vtab.needFree = 0;
  115250. }
  115251. }
  115252. }
  115253. whereLoopAddVtab_exit:
  115254. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  115255. sqlite3DbFree(db, pIdxInfo);
  115256. return rc;
  115257. }
  115258. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  115259. /*
  115260. ** Add WhereLoop entries to handle OR terms. This works for either
  115261. ** btrees or virtual tables.
  115262. */
  115263. static int whereLoopAddOr(
  115264. WhereLoopBuilder *pBuilder,
  115265. Bitmask mExtra,
  115266. Bitmask mUnusable
  115267. ){
  115268. WhereInfo *pWInfo = pBuilder->pWInfo;
  115269. WhereClause *pWC;
  115270. WhereLoop *pNew;
  115271. WhereTerm *pTerm, *pWCEnd;
  115272. int rc = SQLITE_OK;
  115273. int iCur;
  115274. WhereClause tempWC;
  115275. WhereLoopBuilder sSubBuild;
  115276. WhereOrSet sSum, sCur;
  115277. struct SrcList_item *pItem;
  115278. pWC = pBuilder->pWC;
  115279. pWCEnd = pWC->a + pWC->nTerm;
  115280. pNew = pBuilder->pNew;
  115281. memset(&sSum, 0, sizeof(sSum));
  115282. pItem = pWInfo->pTabList->a + pNew->iTab;
  115283. iCur = pItem->iCursor;
  115284. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  115285. if( (pTerm->eOperator & WO_OR)!=0
  115286. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  115287. ){
  115288. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  115289. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  115290. WhereTerm *pOrTerm;
  115291. int once = 1;
  115292. int i, j;
  115293. sSubBuild = *pBuilder;
  115294. sSubBuild.pOrderBy = 0;
  115295. sSubBuild.pOrSet = &sCur;
  115296. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  115297. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  115298. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  115299. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  115300. }else if( pOrTerm->leftCursor==iCur ){
  115301. tempWC.pWInfo = pWC->pWInfo;
  115302. tempWC.pOuter = pWC;
  115303. tempWC.op = TK_AND;
  115304. tempWC.nTerm = 1;
  115305. tempWC.a = pOrTerm;
  115306. sSubBuild.pWC = &tempWC;
  115307. }else{
  115308. continue;
  115309. }
  115310. sCur.n = 0;
  115311. #ifdef WHERETRACE_ENABLED
  115312. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  115313. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  115314. if( sqlite3WhereTrace & 0x400 ){
  115315. for(i=0; i<sSubBuild.pWC->nTerm; i++){
  115316. whereTermPrint(&sSubBuild.pWC->a[i], i);
  115317. }
  115318. }
  115319. #endif
  115320. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115321. if( IsVirtual(pItem->pTab) ){
  115322. rc = whereLoopAddVirtual(&sSubBuild, mExtra, mUnusable);
  115323. }else
  115324. #endif
  115325. {
  115326. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  115327. }
  115328. if( rc==SQLITE_OK ){
  115329. rc = whereLoopAddOr(&sSubBuild, mExtra, mUnusable);
  115330. }
  115331. assert( rc==SQLITE_OK || sCur.n==0 );
  115332. if( sCur.n==0 ){
  115333. sSum.n = 0;
  115334. break;
  115335. }else if( once ){
  115336. whereOrMove(&sSum, &sCur);
  115337. once = 0;
  115338. }else{
  115339. WhereOrSet sPrev;
  115340. whereOrMove(&sPrev, &sSum);
  115341. sSum.n = 0;
  115342. for(i=0; i<sPrev.n; i++){
  115343. for(j=0; j<sCur.n; j++){
  115344. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  115345. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  115346. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  115347. }
  115348. }
  115349. }
  115350. }
  115351. pNew->nLTerm = 1;
  115352. pNew->aLTerm[0] = pTerm;
  115353. pNew->wsFlags = WHERE_MULTI_OR;
  115354. pNew->rSetup = 0;
  115355. pNew->iSortIdx = 0;
  115356. memset(&pNew->u, 0, sizeof(pNew->u));
  115357. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  115358. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  115359. ** of all sub-scans required by the OR-scan. However, due to rounding
  115360. ** errors, it may be that the cost of the OR-scan is equal to its
  115361. ** most expensive sub-scan. Add the smallest possible penalty
  115362. ** (equivalent to multiplying the cost by 1.07) to ensure that
  115363. ** this does not happen. Otherwise, for WHERE clauses such as the
  115364. ** following where there is an index on "y":
  115365. **
  115366. ** WHERE likelihood(x=?, 0.99) OR y=?
  115367. **
  115368. ** the planner may elect to "OR" together a full-table scan and an
  115369. ** index lookup. And other similarly odd results. */
  115370. pNew->rRun = sSum.a[i].rRun + 1;
  115371. pNew->nOut = sSum.a[i].nOut;
  115372. pNew->prereq = sSum.a[i].prereq;
  115373. rc = whereLoopInsert(pBuilder, pNew);
  115374. }
  115375. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  115376. }
  115377. }
  115378. return rc;
  115379. }
  115380. /*
  115381. ** Add all WhereLoop objects for all tables
  115382. */
  115383. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  115384. WhereInfo *pWInfo = pBuilder->pWInfo;
  115385. Bitmask mExtra = 0;
  115386. Bitmask mPrior = 0;
  115387. int iTab;
  115388. SrcList *pTabList = pWInfo->pTabList;
  115389. struct SrcList_item *pItem;
  115390. struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
  115391. sqlite3 *db = pWInfo->pParse->db;
  115392. int rc = SQLITE_OK;
  115393. WhereLoop *pNew;
  115394. u8 priorJointype = 0;
  115395. /* Loop over the tables in the join, from left to right */
  115396. pNew = pBuilder->pNew;
  115397. whereLoopInit(pNew);
  115398. for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
  115399. Bitmask mUnusable = 0;
  115400. pNew->iTab = iTab;
  115401. pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
  115402. if( ((pItem->jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
  115403. /* This condition is true when pItem is the FROM clause term on the
  115404. ** right-hand-side of a LEFT or CROSS JOIN. */
  115405. mExtra = mPrior;
  115406. }
  115407. priorJointype = pItem->jointype;
  115408. if( IsVirtual(pItem->pTab) ){
  115409. struct SrcList_item *p;
  115410. for(p=&pItem[1]; p<pEnd; p++){
  115411. if( mUnusable || (p->jointype & (JT_LEFT|JT_CROSS)) ){
  115412. mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
  115413. }
  115414. }
  115415. rc = whereLoopAddVirtual(pBuilder, mExtra, mUnusable);
  115416. }else{
  115417. rc = whereLoopAddBtree(pBuilder, mExtra);
  115418. }
  115419. if( rc==SQLITE_OK ){
  115420. rc = whereLoopAddOr(pBuilder, mExtra, mUnusable);
  115421. }
  115422. mPrior |= pNew->maskSelf;
  115423. if( rc || db->mallocFailed ) break;
  115424. }
  115425. whereLoopClear(db, pNew);
  115426. return rc;
  115427. }
  115428. /*
  115429. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  115430. ** parameters) to see if it outputs rows in the requested ORDER BY
  115431. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  115432. **
  115433. ** N>0: N terms of the ORDER BY clause are satisfied
  115434. ** N==0: No terms of the ORDER BY clause are satisfied
  115435. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  115436. **
  115437. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  115438. ** strict. With GROUP BY and DISTINCT the only requirement is that
  115439. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  115440. ** and DISTINCT do not require rows to appear in any particular order as long
  115441. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  115442. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  115443. ** pOrderBy terms must be matched in strict left-to-right order.
  115444. */
  115445. static i8 wherePathSatisfiesOrderBy(
  115446. WhereInfo *pWInfo, /* The WHERE clause */
  115447. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  115448. WherePath *pPath, /* The WherePath to check */
  115449. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  115450. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  115451. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  115452. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  115453. ){
  115454. u8 revSet; /* True if rev is known */
  115455. u8 rev; /* Composite sort order */
  115456. u8 revIdx; /* Index sort order */
  115457. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  115458. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  115459. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  115460. u16 nKeyCol; /* Number of key columns in pIndex */
  115461. u16 nColumn; /* Total number of ordered columns in the index */
  115462. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  115463. int iLoop; /* Index of WhereLoop in pPath being processed */
  115464. int i, j; /* Loop counters */
  115465. int iCur; /* Cursor number for current WhereLoop */
  115466. int iColumn; /* A column number within table iCur */
  115467. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  115468. WhereTerm *pTerm; /* A single term of the WHERE clause */
  115469. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  115470. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  115471. Index *pIndex; /* The index associated with pLoop */
  115472. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  115473. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  115474. Bitmask obDone; /* Mask of all ORDER BY terms */
  115475. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  115476. Bitmask ready; /* Mask of inner loops */
  115477. /*
  115478. ** We say the WhereLoop is "one-row" if it generates no more than one
  115479. ** row of output. A WhereLoop is one-row if all of the following are true:
  115480. ** (a) All index columns match with WHERE_COLUMN_EQ.
  115481. ** (b) The index is unique
  115482. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  115483. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  115484. **
  115485. ** We say the WhereLoop is "order-distinct" if the set of columns from
  115486. ** that WhereLoop that are in the ORDER BY clause are different for every
  115487. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  115488. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  115489. ** is not order-distinct. To be order-distinct is not quite the same as being
  115490. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  115491. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  115492. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  115493. **
  115494. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  115495. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  115496. ** automatically order-distinct.
  115497. */
  115498. assert( pOrderBy!=0 );
  115499. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  115500. nOrderBy = pOrderBy->nExpr;
  115501. testcase( nOrderBy==BMS-1 );
  115502. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  115503. isOrderDistinct = 1;
  115504. obDone = MASKBIT(nOrderBy)-1;
  115505. orderDistinctMask = 0;
  115506. ready = 0;
  115507. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  115508. if( iLoop>0 ) ready |= pLoop->maskSelf;
  115509. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  115510. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  115511. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  115512. break;
  115513. }
  115514. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  115515. /* Mark off any ORDER BY term X that is a column in the table of
  115516. ** the current loop for which there is term in the WHERE
  115517. ** clause of the form X IS NULL or X=? that reference only outer
  115518. ** loops.
  115519. */
  115520. for(i=0; i<nOrderBy; i++){
  115521. if( MASKBIT(i) & obSat ) continue;
  115522. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  115523. if( pOBExpr->op!=TK_COLUMN ) continue;
  115524. if( pOBExpr->iTable!=iCur ) continue;
  115525. pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  115526. ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
  115527. if( pTerm==0 ) continue;
  115528. if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
  115529. const char *z1, *z2;
  115530. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  115531. if( !pColl ) pColl = db->pDfltColl;
  115532. z1 = pColl->zName;
  115533. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  115534. if( !pColl ) pColl = db->pDfltColl;
  115535. z2 = pColl->zName;
  115536. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  115537. testcase( pTerm->pExpr->op==TK_IS );
  115538. }
  115539. obSat |= MASKBIT(i);
  115540. }
  115541. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  115542. if( pLoop->wsFlags & WHERE_IPK ){
  115543. pIndex = 0;
  115544. nKeyCol = 0;
  115545. nColumn = 1;
  115546. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  115547. return 0;
  115548. }else{
  115549. nKeyCol = pIndex->nKeyCol;
  115550. nColumn = pIndex->nColumn;
  115551. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  115552. assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
  115553. isOrderDistinct = IsUniqueIndex(pIndex);
  115554. }
  115555. /* Loop through all columns of the index and deal with the ones
  115556. ** that are not constrained by == or IN.
  115557. */
  115558. rev = revSet = 0;
  115559. distinctColumns = 0;
  115560. for(j=0; j<nColumn; j++){
  115561. u8 bOnce; /* True to run the ORDER BY search loop */
  115562. /* Skip over == and IS NULL terms */
  115563. if( j<pLoop->u.btree.nEq
  115564. && pLoop->nSkip==0
  115565. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
  115566. ){
  115567. if( i & WO_ISNULL ){
  115568. testcase( isOrderDistinct );
  115569. isOrderDistinct = 0;
  115570. }
  115571. continue;
  115572. }
  115573. /* Get the column number in the table (iColumn) and sort order
  115574. ** (revIdx) for the j-th column of the index.
  115575. */
  115576. if( pIndex ){
  115577. iColumn = pIndex->aiColumn[j];
  115578. revIdx = pIndex->aSortOrder[j];
  115579. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  115580. }else{
  115581. iColumn = -1;
  115582. revIdx = 0;
  115583. }
  115584. /* An unconstrained column that might be NULL means that this
  115585. ** WhereLoop is not well-ordered
  115586. */
  115587. if( isOrderDistinct
  115588. && iColumn>=0
  115589. && j>=pLoop->u.btree.nEq
  115590. && pIndex->pTable->aCol[iColumn].notNull==0
  115591. ){
  115592. isOrderDistinct = 0;
  115593. }
  115594. /* Find the ORDER BY term that corresponds to the j-th column
  115595. ** of the index and mark that ORDER BY term off
  115596. */
  115597. bOnce = 1;
  115598. isMatch = 0;
  115599. for(i=0; bOnce && i<nOrderBy; i++){
  115600. if( MASKBIT(i) & obSat ) continue;
  115601. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  115602. testcase( wctrlFlags & WHERE_GROUPBY );
  115603. testcase( wctrlFlags & WHERE_DISTINCTBY );
  115604. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  115605. if( pOBExpr->op!=TK_COLUMN ) continue;
  115606. if( pOBExpr->iTable!=iCur ) continue;
  115607. if( pOBExpr->iColumn!=iColumn ) continue;
  115608. if( iColumn>=0 ){
  115609. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  115610. if( !pColl ) pColl = db->pDfltColl;
  115611. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  115612. }
  115613. isMatch = 1;
  115614. break;
  115615. }
  115616. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  115617. /* Make sure the sort order is compatible in an ORDER BY clause.
  115618. ** Sort order is irrelevant for a GROUP BY clause. */
  115619. if( revSet ){
  115620. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  115621. }else{
  115622. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  115623. if( rev ) *pRevMask |= MASKBIT(iLoop);
  115624. revSet = 1;
  115625. }
  115626. }
  115627. if( isMatch ){
  115628. if( iColumn<0 ){
  115629. testcase( distinctColumns==0 );
  115630. distinctColumns = 1;
  115631. }
  115632. obSat |= MASKBIT(i);
  115633. }else{
  115634. /* No match found */
  115635. if( j==0 || j<nKeyCol ){
  115636. testcase( isOrderDistinct!=0 );
  115637. isOrderDistinct = 0;
  115638. }
  115639. break;
  115640. }
  115641. } /* end Loop over all index columns */
  115642. if( distinctColumns ){
  115643. testcase( isOrderDistinct==0 );
  115644. isOrderDistinct = 1;
  115645. }
  115646. } /* end-if not one-row */
  115647. /* Mark off any other ORDER BY terms that reference pLoop */
  115648. if( isOrderDistinct ){
  115649. orderDistinctMask |= pLoop->maskSelf;
  115650. for(i=0; i<nOrderBy; i++){
  115651. Expr *p;
  115652. Bitmask mTerm;
  115653. if( MASKBIT(i) & obSat ) continue;
  115654. p = pOrderBy->a[i].pExpr;
  115655. mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
  115656. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  115657. if( (mTerm&~orderDistinctMask)==0 ){
  115658. obSat |= MASKBIT(i);
  115659. }
  115660. }
  115661. }
  115662. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  115663. if( obSat==obDone ) return (i8)nOrderBy;
  115664. if( !isOrderDistinct ){
  115665. for(i=nOrderBy-1; i>0; i--){
  115666. Bitmask m = MASKBIT(i) - 1;
  115667. if( (obSat&m)==m ) return i;
  115668. }
  115669. return 0;
  115670. }
  115671. return -1;
  115672. }
  115673. /*
  115674. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  115675. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  115676. ** BY clause - and so any order that groups rows as required satisfies the
  115677. ** request.
  115678. **
  115679. ** Normally, in this case it is not possible for the caller to determine
  115680. ** whether or not the rows are really being delivered in sorted order, or
  115681. ** just in some other order that provides the required grouping. However,
  115682. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  115683. ** this function may be called on the returned WhereInfo object. It returns
  115684. ** true if the rows really will be sorted in the specified order, or false
  115685. ** otherwise.
  115686. **
  115687. ** For example, assuming:
  115688. **
  115689. ** CREATE INDEX i1 ON t1(x, Y);
  115690. **
  115691. ** then
  115692. **
  115693. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  115694. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  115695. */
  115696. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  115697. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  115698. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  115699. return pWInfo->sorted;
  115700. }
  115701. #ifdef WHERETRACE_ENABLED
  115702. /* For debugging use only: */
  115703. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  115704. static char zName[65];
  115705. int i;
  115706. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  115707. if( pLast ) zName[i++] = pLast->cId;
  115708. zName[i] = 0;
  115709. return zName;
  115710. }
  115711. #endif
  115712. /*
  115713. ** Return the cost of sorting nRow rows, assuming that the keys have
  115714. ** nOrderby columns and that the first nSorted columns are already in
  115715. ** order.
  115716. */
  115717. static LogEst whereSortingCost(
  115718. WhereInfo *pWInfo,
  115719. LogEst nRow,
  115720. int nOrderBy,
  115721. int nSorted
  115722. ){
  115723. /* TUNING: Estimated cost of a full external sort, where N is
  115724. ** the number of rows to sort is:
  115725. **
  115726. ** cost = (3.0 * N * log(N)).
  115727. **
  115728. ** Or, if the order-by clause has X terms but only the last Y
  115729. ** terms are out of order, then block-sorting will reduce the
  115730. ** sorting cost to:
  115731. **
  115732. ** cost = (3.0 * N * log(N)) * (Y/X)
  115733. **
  115734. ** The (Y/X) term is implemented using stack variable rScale
  115735. ** below. */
  115736. LogEst rScale, rSortCost;
  115737. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  115738. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  115739. rSortCost = nRow + estLog(nRow) + rScale + 16;
  115740. /* TUNING: The cost of implementing DISTINCT using a B-TREE is
  115741. ** similar but with a larger constant of proportionality.
  115742. ** Multiply by an additional factor of 3.0. */
  115743. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  115744. rSortCost += 16;
  115745. }
  115746. return rSortCost;
  115747. }
  115748. /*
  115749. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  115750. ** attempts to find the lowest cost path that visits each WhereLoop
  115751. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  115752. **
  115753. ** Assume that the total number of output rows that will need to be sorted
  115754. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  115755. ** costs if nRowEst==0.
  115756. **
  115757. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  115758. ** error occurs.
  115759. */
  115760. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  115761. int mxChoice; /* Maximum number of simultaneous paths tracked */
  115762. int nLoop; /* Number of terms in the join */
  115763. Parse *pParse; /* Parsing context */
  115764. sqlite3 *db; /* The database connection */
  115765. int iLoop; /* Loop counter over the terms of the join */
  115766. int ii, jj; /* Loop counters */
  115767. int mxI = 0; /* Index of next entry to replace */
  115768. int nOrderBy; /* Number of ORDER BY clause terms */
  115769. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  115770. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  115771. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  115772. WherePath *aFrom; /* All nFrom paths at the previous level */
  115773. WherePath *aTo; /* The nTo best paths at the current level */
  115774. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  115775. WherePath *pTo; /* An element of aTo[] that we are working on */
  115776. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  115777. WhereLoop **pX; /* Used to divy up the pSpace memory */
  115778. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  115779. char *pSpace; /* Temporary memory used by this routine */
  115780. int nSpace; /* Bytes of space allocated at pSpace */
  115781. pParse = pWInfo->pParse;
  115782. db = pParse->db;
  115783. nLoop = pWInfo->nLevel;
  115784. /* TUNING: For simple queries, only the best path is tracked.
  115785. ** For 2-way joins, the 5 best paths are followed.
  115786. ** For joins of 3 or more tables, track the 10 best paths */
  115787. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  115788. assert( nLoop<=pWInfo->pTabList->nSrc );
  115789. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  115790. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  115791. ** case the purpose of this call is to estimate the number of rows returned
  115792. ** by the overall query. Once this estimate has been obtained, the caller
  115793. ** will invoke this function a second time, passing the estimate as the
  115794. ** nRowEst parameter. */
  115795. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  115796. nOrderBy = 0;
  115797. }else{
  115798. nOrderBy = pWInfo->pOrderBy->nExpr;
  115799. }
  115800. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  115801. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  115802. nSpace += sizeof(LogEst) * nOrderBy;
  115803. pSpace = sqlite3DbMallocRaw(db, nSpace);
  115804. if( pSpace==0 ) return SQLITE_NOMEM;
  115805. aTo = (WherePath*)pSpace;
  115806. aFrom = aTo+mxChoice;
  115807. memset(aFrom, 0, sizeof(aFrom[0]));
  115808. pX = (WhereLoop**)(aFrom+mxChoice);
  115809. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  115810. pFrom->aLoop = pX;
  115811. }
  115812. if( nOrderBy ){
  115813. /* If there is an ORDER BY clause and it is not being ignored, set up
  115814. ** space for the aSortCost[] array. Each element of the aSortCost array
  115815. ** is either zero - meaning it has not yet been initialized - or the
  115816. ** cost of sorting nRowEst rows of data where the first X terms of
  115817. ** the ORDER BY clause are already in order, where X is the array
  115818. ** index. */
  115819. aSortCost = (LogEst*)pX;
  115820. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  115821. }
  115822. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  115823. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  115824. /* Seed the search with a single WherePath containing zero WhereLoops.
  115825. **
  115826. ** TUNING: Do not let the number of iterations go above 28. If the cost
  115827. ** of computing an automatic index is not paid back within the first 28
  115828. ** rows, then do not use the automatic index. */
  115829. aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
  115830. nFrom = 1;
  115831. assert( aFrom[0].isOrdered==0 );
  115832. if( nOrderBy ){
  115833. /* If nLoop is zero, then there are no FROM terms in the query. Since
  115834. ** in this case the query may return a maximum of one row, the results
  115835. ** are already in the requested order. Set isOrdered to nOrderBy to
  115836. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  115837. ** -1, indicating that the result set may or may not be ordered,
  115838. ** depending on the loops added to the current plan. */
  115839. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  115840. }
  115841. /* Compute successively longer WherePaths using the previous generation
  115842. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  115843. ** best paths at each generation */
  115844. for(iLoop=0; iLoop<nLoop; iLoop++){
  115845. nTo = 0;
  115846. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  115847. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  115848. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  115849. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  115850. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  115851. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  115852. Bitmask maskNew; /* Mask of src visited by (..) */
  115853. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  115854. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  115855. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  115856. /* At this point, pWLoop is a candidate to be the next loop.
  115857. ** Compute its cost */
  115858. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  115859. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  115860. nOut = pFrom->nRow + pWLoop->nOut;
  115861. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  115862. if( isOrdered<0 ){
  115863. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  115864. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  115865. iLoop, pWLoop, &revMask);
  115866. }else{
  115867. revMask = pFrom->revLoop;
  115868. }
  115869. if( isOrdered>=0 && isOrdered<nOrderBy ){
  115870. if( aSortCost[isOrdered]==0 ){
  115871. aSortCost[isOrdered] = whereSortingCost(
  115872. pWInfo, nRowEst, nOrderBy, isOrdered
  115873. );
  115874. }
  115875. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  115876. WHERETRACE(0x002,
  115877. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  115878. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  115879. rUnsorted, rCost));
  115880. }else{
  115881. rCost = rUnsorted;
  115882. }
  115883. /* Check to see if pWLoop should be added to the set of
  115884. ** mxChoice best-so-far paths.
  115885. **
  115886. ** First look for an existing path among best-so-far paths
  115887. ** that covers the same set of loops and has the same isOrdered
  115888. ** setting as the current path candidate.
  115889. **
  115890. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  115891. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  115892. ** of legal values for isOrdered, -1..64.
  115893. */
  115894. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  115895. if( pTo->maskLoop==maskNew
  115896. && ((pTo->isOrdered^isOrdered)&0x80)==0
  115897. ){
  115898. testcase( jj==nTo-1 );
  115899. break;
  115900. }
  115901. }
  115902. if( jj>=nTo ){
  115903. /* None of the existing best-so-far paths match the candidate. */
  115904. if( nTo>=mxChoice
  115905. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  115906. ){
  115907. /* The current candidate is no better than any of the mxChoice
  115908. ** paths currently in the best-so-far buffer. So discard
  115909. ** this candidate as not viable. */
  115910. #ifdef WHERETRACE_ENABLED /* 0x4 */
  115911. if( sqlite3WhereTrace&0x4 ){
  115912. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  115913. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  115914. isOrdered>=0 ? isOrdered+'0' : '?');
  115915. }
  115916. #endif
  115917. continue;
  115918. }
  115919. /* If we reach this points it means that the new candidate path
  115920. ** needs to be added to the set of best-so-far paths. */
  115921. if( nTo<mxChoice ){
  115922. /* Increase the size of the aTo set by one */
  115923. jj = nTo++;
  115924. }else{
  115925. /* New path replaces the prior worst to keep count below mxChoice */
  115926. jj = mxI;
  115927. }
  115928. pTo = &aTo[jj];
  115929. #ifdef WHERETRACE_ENABLED /* 0x4 */
  115930. if( sqlite3WhereTrace&0x4 ){
  115931. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  115932. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  115933. isOrdered>=0 ? isOrdered+'0' : '?');
  115934. }
  115935. #endif
  115936. }else{
  115937. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  115938. ** same set of loops and has the sam isOrdered setting as the
  115939. ** candidate path. Check to see if the candidate should replace
  115940. ** pTo or if the candidate should be skipped */
  115941. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  115942. #ifdef WHERETRACE_ENABLED /* 0x4 */
  115943. if( sqlite3WhereTrace&0x4 ){
  115944. sqlite3DebugPrintf(
  115945. "Skip %s cost=%-3d,%3d order=%c",
  115946. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  115947. isOrdered>=0 ? isOrdered+'0' : '?');
  115948. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  115949. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  115950. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  115951. }
  115952. #endif
  115953. /* Discard the candidate path from further consideration */
  115954. testcase( pTo->rCost==rCost );
  115955. continue;
  115956. }
  115957. testcase( pTo->rCost==rCost+1 );
  115958. /* Control reaches here if the candidate path is better than the
  115959. ** pTo path. Replace pTo with the candidate. */
  115960. #ifdef WHERETRACE_ENABLED /* 0x4 */
  115961. if( sqlite3WhereTrace&0x4 ){
  115962. sqlite3DebugPrintf(
  115963. "Update %s cost=%-3d,%3d order=%c",
  115964. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  115965. isOrdered>=0 ? isOrdered+'0' : '?');
  115966. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  115967. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  115968. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  115969. }
  115970. #endif
  115971. }
  115972. /* pWLoop is a winner. Add it to the set of best so far */
  115973. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  115974. pTo->revLoop = revMask;
  115975. pTo->nRow = nOut;
  115976. pTo->rCost = rCost;
  115977. pTo->rUnsorted = rUnsorted;
  115978. pTo->isOrdered = isOrdered;
  115979. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  115980. pTo->aLoop[iLoop] = pWLoop;
  115981. if( nTo>=mxChoice ){
  115982. mxI = 0;
  115983. mxCost = aTo[0].rCost;
  115984. mxUnsorted = aTo[0].nRow;
  115985. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  115986. if( pTo->rCost>mxCost
  115987. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  115988. ){
  115989. mxCost = pTo->rCost;
  115990. mxUnsorted = pTo->rUnsorted;
  115991. mxI = jj;
  115992. }
  115993. }
  115994. }
  115995. }
  115996. }
  115997. #ifdef WHERETRACE_ENABLED /* >=2 */
  115998. if( sqlite3WhereTrace & 0x02 ){
  115999. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  116000. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  116001. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  116002. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  116003. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  116004. if( pTo->isOrdered>0 ){
  116005. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  116006. }else{
  116007. sqlite3DebugPrintf("\n");
  116008. }
  116009. }
  116010. }
  116011. #endif
  116012. /* Swap the roles of aFrom and aTo for the next generation */
  116013. pFrom = aTo;
  116014. aTo = aFrom;
  116015. aFrom = pFrom;
  116016. nFrom = nTo;
  116017. }
  116018. if( nFrom==0 ){
  116019. sqlite3ErrorMsg(pParse, "no query solution");
  116020. sqlite3DbFree(db, pSpace);
  116021. return SQLITE_ERROR;
  116022. }
  116023. /* Find the lowest cost path. pFrom will be left pointing to that path */
  116024. pFrom = aFrom;
  116025. for(ii=1; ii<nFrom; ii++){
  116026. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  116027. }
  116028. assert( pWInfo->nLevel==nLoop );
  116029. /* Load the lowest cost path into pWInfo */
  116030. for(iLoop=0; iLoop<nLoop; iLoop++){
  116031. WhereLevel *pLevel = pWInfo->a + iLoop;
  116032. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  116033. pLevel->iFrom = pWLoop->iTab;
  116034. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  116035. }
  116036. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  116037. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  116038. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  116039. && nRowEst
  116040. ){
  116041. Bitmask notUsed;
  116042. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  116043. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  116044. if( rc==pWInfo->pResultSet->nExpr ){
  116045. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  116046. }
  116047. }
  116048. if( pWInfo->pOrderBy ){
  116049. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  116050. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  116051. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  116052. }
  116053. }else{
  116054. pWInfo->nOBSat = pFrom->isOrdered;
  116055. if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
  116056. pWInfo->revMask = pFrom->revLoop;
  116057. }
  116058. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  116059. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
  116060. ){
  116061. Bitmask revMask = 0;
  116062. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  116063. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  116064. );
  116065. assert( pWInfo->sorted==0 );
  116066. if( nOrder==pWInfo->pOrderBy->nExpr ){
  116067. pWInfo->sorted = 1;
  116068. pWInfo->revMask = revMask;
  116069. }
  116070. }
  116071. }
  116072. pWInfo->nRowOut = pFrom->nRow;
  116073. /* Free temporary memory and return success */
  116074. sqlite3DbFree(db, pSpace);
  116075. return SQLITE_OK;
  116076. }
  116077. /*
  116078. ** Most queries use only a single table (they are not joins) and have
  116079. ** simple == constraints against indexed fields. This routine attempts
  116080. ** to plan those simple cases using much less ceremony than the
  116081. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  116082. ** times for the common case.
  116083. **
  116084. ** Return non-zero on success, if this query can be handled by this
  116085. ** no-frills query planner. Return zero if this query needs the
  116086. ** general-purpose query planner.
  116087. */
  116088. static int whereShortCut(WhereLoopBuilder *pBuilder){
  116089. WhereInfo *pWInfo;
  116090. struct SrcList_item *pItem;
  116091. WhereClause *pWC;
  116092. WhereTerm *pTerm;
  116093. WhereLoop *pLoop;
  116094. int iCur;
  116095. int j;
  116096. Table *pTab;
  116097. Index *pIdx;
  116098. pWInfo = pBuilder->pWInfo;
  116099. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  116100. assert( pWInfo->pTabList->nSrc>=1 );
  116101. pItem = pWInfo->pTabList->a;
  116102. pTab = pItem->pTab;
  116103. if( IsVirtual(pTab) ) return 0;
  116104. if( pItem->zIndexedBy ) return 0;
  116105. iCur = pItem->iCursor;
  116106. pWC = &pWInfo->sWC;
  116107. pLoop = pBuilder->pNew;
  116108. pLoop->wsFlags = 0;
  116109. pLoop->nSkip = 0;
  116110. pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
  116111. if( pTerm ){
  116112. testcase( pTerm->eOperator & WO_IS );
  116113. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  116114. pLoop->aLTerm[0] = pTerm;
  116115. pLoop->nLTerm = 1;
  116116. pLoop->u.btree.nEq = 1;
  116117. /* TUNING: Cost of a rowid lookup is 10 */
  116118. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  116119. }else{
  116120. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  116121. int opMask;
  116122. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  116123. if( !IsUniqueIndex(pIdx)
  116124. || pIdx->pPartIdxWhere!=0
  116125. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  116126. ) continue;
  116127. opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
  116128. for(j=0; j<pIdx->nKeyCol; j++){
  116129. pTerm = sqlite3WhereFindTerm(pWC, iCur, pIdx->aiColumn[j], 0, opMask, pIdx);
  116130. if( pTerm==0 ) break;
  116131. testcase( pTerm->eOperator & WO_IS );
  116132. pLoop->aLTerm[j] = pTerm;
  116133. }
  116134. if( j!=pIdx->nKeyCol ) continue;
  116135. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  116136. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  116137. pLoop->wsFlags |= WHERE_IDX_ONLY;
  116138. }
  116139. pLoop->nLTerm = j;
  116140. pLoop->u.btree.nEq = j;
  116141. pLoop->u.btree.pIndex = pIdx;
  116142. /* TUNING: Cost of a unique index lookup is 15 */
  116143. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  116144. break;
  116145. }
  116146. }
  116147. if( pLoop->wsFlags ){
  116148. pLoop->nOut = (LogEst)1;
  116149. pWInfo->a[0].pWLoop = pLoop;
  116150. pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
  116151. pWInfo->a[0].iTabCur = iCur;
  116152. pWInfo->nRowOut = 1;
  116153. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  116154. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  116155. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  116156. }
  116157. #ifdef SQLITE_DEBUG
  116158. pLoop->cId = '0';
  116159. #endif
  116160. return 1;
  116161. }
  116162. return 0;
  116163. }
  116164. /*
  116165. ** Generate the beginning of the loop used for WHERE clause processing.
  116166. ** The return value is a pointer to an opaque structure that contains
  116167. ** information needed to terminate the loop. Later, the calling routine
  116168. ** should invoke sqlite3WhereEnd() with the return value of this function
  116169. ** in order to complete the WHERE clause processing.
  116170. **
  116171. ** If an error occurs, this routine returns NULL.
  116172. **
  116173. ** The basic idea is to do a nested loop, one loop for each table in
  116174. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  116175. ** same as a SELECT with only a single table in the FROM clause.) For
  116176. ** example, if the SQL is this:
  116177. **
  116178. ** SELECT * FROM t1, t2, t3 WHERE ...;
  116179. **
  116180. ** Then the code generated is conceptually like the following:
  116181. **
  116182. ** foreach row1 in t1 do \ Code generated
  116183. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  116184. ** foreach row3 in t3 do /
  116185. ** ...
  116186. ** end \ Code generated
  116187. ** end |-- by sqlite3WhereEnd()
  116188. ** end /
  116189. **
  116190. ** Note that the loops might not be nested in the order in which they
  116191. ** appear in the FROM clause if a different order is better able to make
  116192. ** use of indices. Note also that when the IN operator appears in
  116193. ** the WHERE clause, it might result in additional nested loops for
  116194. ** scanning through all values on the right-hand side of the IN.
  116195. **
  116196. ** There are Btree cursors associated with each table. t1 uses cursor
  116197. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  116198. ** And so forth. This routine generates code to open those VDBE cursors
  116199. ** and sqlite3WhereEnd() generates the code to close them.
  116200. **
  116201. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  116202. ** in pTabList pointing at their appropriate entries. The [...] code
  116203. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  116204. ** data from the various tables of the loop.
  116205. **
  116206. ** If the WHERE clause is empty, the foreach loops must each scan their
  116207. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  116208. ** the tables have indices and there are terms in the WHERE clause that
  116209. ** refer to those indices, a complete table scan can be avoided and the
  116210. ** code will run much faster. Most of the work of this routine is checking
  116211. ** to see if there are indices that can be used to speed up the loop.
  116212. **
  116213. ** Terms of the WHERE clause are also used to limit which rows actually
  116214. ** make it to the "..." in the middle of the loop. After each "foreach",
  116215. ** terms of the WHERE clause that use only terms in that loop and outer
  116216. ** loops are evaluated and if false a jump is made around all subsequent
  116217. ** inner loops (or around the "..." if the test occurs within the inner-
  116218. ** most loop)
  116219. **
  116220. ** OUTER JOINS
  116221. **
  116222. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  116223. **
  116224. ** foreach row1 in t1 do
  116225. ** flag = 0
  116226. ** foreach row2 in t2 do
  116227. ** start:
  116228. ** ...
  116229. ** flag = 1
  116230. ** end
  116231. ** if flag==0 then
  116232. ** move the row2 cursor to a null row
  116233. ** goto start
  116234. ** fi
  116235. ** end
  116236. **
  116237. ** ORDER BY CLAUSE PROCESSING
  116238. **
  116239. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  116240. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  116241. ** if there is one. If there is no ORDER BY clause or if this routine
  116242. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  116243. **
  116244. ** The iIdxCur parameter is the cursor number of an index. If
  116245. ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
  116246. ** to use for OR clause processing. The WHERE clause should use this
  116247. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  116248. ** the first cursor in an array of cursors for all indices. iIdxCur should
  116249. ** be used to compute the appropriate cursor depending on which index is
  116250. ** used.
  116251. */
  116252. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  116253. Parse *pParse, /* The parser context */
  116254. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  116255. Expr *pWhere, /* The WHERE clause */
  116256. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  116257. ExprList *pResultSet, /* Result set of the query */
  116258. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  116259. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  116260. ){
  116261. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  116262. int nTabList; /* Number of elements in pTabList */
  116263. WhereInfo *pWInfo; /* Will become the return value of this function */
  116264. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  116265. Bitmask notReady; /* Cursors that are not yet positioned */
  116266. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  116267. WhereMaskSet *pMaskSet; /* The expression mask set */
  116268. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  116269. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  116270. int ii; /* Loop counter */
  116271. sqlite3 *db; /* Database connection */
  116272. int rc; /* Return code */
  116273. /* Variable initialization */
  116274. db = pParse->db;
  116275. memset(&sWLB, 0, sizeof(sWLB));
  116276. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  116277. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  116278. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  116279. sWLB.pOrderBy = pOrderBy;
  116280. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  116281. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  116282. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  116283. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  116284. }
  116285. /* The number of tables in the FROM clause is limited by the number of
  116286. ** bits in a Bitmask
  116287. */
  116288. testcase( pTabList->nSrc==BMS );
  116289. if( pTabList->nSrc>BMS ){
  116290. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  116291. return 0;
  116292. }
  116293. /* This function normally generates a nested loop for all tables in
  116294. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  116295. ** only generate code for the first table in pTabList and assume that
  116296. ** any cursors associated with subsequent tables are uninitialized.
  116297. */
  116298. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  116299. /* Allocate and initialize the WhereInfo structure that will become the
  116300. ** return value. A single allocation is used to store the WhereInfo
  116301. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  116302. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  116303. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  116304. ** some architectures. Hence the ROUND8() below.
  116305. */
  116306. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  116307. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  116308. if( db->mallocFailed ){
  116309. sqlite3DbFree(db, pWInfo);
  116310. pWInfo = 0;
  116311. goto whereBeginError;
  116312. }
  116313. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  116314. pWInfo->nLevel = nTabList;
  116315. pWInfo->pParse = pParse;
  116316. pWInfo->pTabList = pTabList;
  116317. pWInfo->pOrderBy = pOrderBy;
  116318. pWInfo->pResultSet = pResultSet;
  116319. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  116320. pWInfo->wctrlFlags = wctrlFlags;
  116321. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  116322. pMaskSet = &pWInfo->sMaskSet;
  116323. sWLB.pWInfo = pWInfo;
  116324. sWLB.pWC = &pWInfo->sWC;
  116325. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  116326. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  116327. whereLoopInit(sWLB.pNew);
  116328. #ifdef SQLITE_DEBUG
  116329. sWLB.pNew->cId = '*';
  116330. #endif
  116331. /* Split the WHERE clause into separate subexpressions where each
  116332. ** subexpression is separated by an AND operator.
  116333. */
  116334. initMaskSet(pMaskSet);
  116335. sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
  116336. sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
  116337. /* Special case: a WHERE clause that is constant. Evaluate the
  116338. ** expression and either jump over all of the code or fall thru.
  116339. */
  116340. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  116341. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  116342. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  116343. SQLITE_JUMPIFNULL);
  116344. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  116345. }
  116346. }
  116347. /* Special case: No FROM clause
  116348. */
  116349. if( nTabList==0 ){
  116350. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  116351. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  116352. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  116353. }
  116354. }
  116355. /* Assign a bit from the bitmask to every term in the FROM clause.
  116356. **
  116357. ** When assigning bitmask values to FROM clause cursors, it must be
  116358. ** the case that if X is the bitmask for the N-th FROM clause term then
  116359. ** the bitmask for all FROM clause terms to the left of the N-th term
  116360. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  116361. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  116362. ** of the join. Subtracting one from the right table bitmask gives a
  116363. ** bitmask for all tables to the left of the join. Knowing the bitmask
  116364. ** for all tables to the left of a left join is important. Ticket #3015.
  116365. **
  116366. ** Note that bitmasks are created for all pTabList->nSrc tables in
  116367. ** pTabList, not just the first nTabList tables. nTabList is normally
  116368. ** equal to pTabList->nSrc but might be shortened to 1 if the
  116369. ** WHERE_ONETABLE_ONLY flag is set.
  116370. */
  116371. for(ii=0; ii<pTabList->nSrc; ii++){
  116372. createMask(pMaskSet, pTabList->a[ii].iCursor);
  116373. }
  116374. #ifndef NDEBUG
  116375. {
  116376. Bitmask toTheLeft = 0;
  116377. for(ii=0; ii<pTabList->nSrc; ii++){
  116378. Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
  116379. assert( (m-1)==toTheLeft );
  116380. toTheLeft |= m;
  116381. }
  116382. }
  116383. #endif
  116384. /* Analyze all of the subexpressions. */
  116385. sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
  116386. if( db->mallocFailed ) goto whereBeginError;
  116387. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  116388. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  116389. /* The DISTINCT marking is pointless. Ignore it. */
  116390. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  116391. }else if( pOrderBy==0 ){
  116392. /* Try to ORDER BY the result set to make distinct processing easier */
  116393. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  116394. pWInfo->pOrderBy = pResultSet;
  116395. }
  116396. }
  116397. /* Construct the WhereLoop objects */
  116398. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  116399. #if defined(WHERETRACE_ENABLED)
  116400. if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
  116401. int i;
  116402. for(i=0; i<sWLB.pWC->nTerm; i++){
  116403. whereTermPrint(&sWLB.pWC->a[i], i);
  116404. }
  116405. }
  116406. #endif
  116407. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  116408. rc = whereLoopAddAll(&sWLB);
  116409. if( rc ) goto whereBeginError;
  116410. #ifdef WHERETRACE_ENABLED
  116411. if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
  116412. WhereLoop *p;
  116413. int i;
  116414. static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  116415. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  116416. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  116417. p->cId = zLabel[i%sizeof(zLabel)];
  116418. whereLoopPrint(p, sWLB.pWC);
  116419. }
  116420. }
  116421. #endif
  116422. wherePathSolver(pWInfo, 0);
  116423. if( db->mallocFailed ) goto whereBeginError;
  116424. if( pWInfo->pOrderBy ){
  116425. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  116426. if( db->mallocFailed ) goto whereBeginError;
  116427. }
  116428. }
  116429. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  116430. pWInfo->revMask = (Bitmask)(-1);
  116431. }
  116432. if( pParse->nErr || NEVER(db->mallocFailed) ){
  116433. goto whereBeginError;
  116434. }
  116435. #ifdef WHERETRACE_ENABLED
  116436. if( sqlite3WhereTrace ){
  116437. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  116438. if( pWInfo->nOBSat>0 ){
  116439. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  116440. }
  116441. switch( pWInfo->eDistinct ){
  116442. case WHERE_DISTINCT_UNIQUE: {
  116443. sqlite3DebugPrintf(" DISTINCT=unique");
  116444. break;
  116445. }
  116446. case WHERE_DISTINCT_ORDERED: {
  116447. sqlite3DebugPrintf(" DISTINCT=ordered");
  116448. break;
  116449. }
  116450. case WHERE_DISTINCT_UNORDERED: {
  116451. sqlite3DebugPrintf(" DISTINCT=unordered");
  116452. break;
  116453. }
  116454. }
  116455. sqlite3DebugPrintf("\n");
  116456. for(ii=0; ii<pWInfo->nLevel; ii++){
  116457. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  116458. }
  116459. }
  116460. #endif
  116461. /* Attempt to omit tables from the join that do not effect the result */
  116462. if( pWInfo->nLevel>=2
  116463. && pResultSet!=0
  116464. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  116465. ){
  116466. Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pResultSet);
  116467. if( sWLB.pOrderBy ){
  116468. tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
  116469. }
  116470. while( pWInfo->nLevel>=2 ){
  116471. WhereTerm *pTerm, *pEnd;
  116472. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  116473. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  116474. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  116475. && (pLoop->wsFlags & WHERE_ONEROW)==0
  116476. ){
  116477. break;
  116478. }
  116479. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  116480. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  116481. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  116482. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  116483. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  116484. ){
  116485. break;
  116486. }
  116487. }
  116488. if( pTerm<pEnd ) break;
  116489. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  116490. pWInfo->nLevel--;
  116491. nTabList--;
  116492. }
  116493. }
  116494. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  116495. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  116496. /* If the caller is an UPDATE or DELETE statement that is requesting
  116497. ** to use a one-pass algorithm, determine if this is appropriate.
  116498. ** The one-pass algorithm only works if the WHERE clause constrains
  116499. ** the statement to update or delete a single row.
  116500. */
  116501. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  116502. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  116503. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  116504. pWInfo->okOnePass = 1;
  116505. if( HasRowid(pTabList->a[0].pTab) ){
  116506. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  116507. }
  116508. }
  116509. /* Open all tables in the pTabList and any indices selected for
  116510. ** searching those tables.
  116511. */
  116512. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  116513. Table *pTab; /* Table to open */
  116514. int iDb; /* Index of database containing table/index */
  116515. struct SrcList_item *pTabItem;
  116516. pTabItem = &pTabList->a[pLevel->iFrom];
  116517. pTab = pTabItem->pTab;
  116518. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  116519. pLoop = pLevel->pWLoop;
  116520. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  116521. /* Do nothing */
  116522. }else
  116523. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116524. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  116525. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  116526. int iCur = pTabItem->iCursor;
  116527. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  116528. }else if( IsVirtual(pTab) ){
  116529. /* noop */
  116530. }else
  116531. #endif
  116532. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  116533. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  116534. int op = OP_OpenRead;
  116535. if( pWInfo->okOnePass ){
  116536. op = OP_OpenWrite;
  116537. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  116538. };
  116539. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  116540. assert( pTabItem->iCursor==pLevel->iTabCur );
  116541. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  116542. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  116543. if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
  116544. Bitmask b = pTabItem->colUsed;
  116545. int n = 0;
  116546. for(; b; b=b>>1, n++){}
  116547. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  116548. SQLITE_INT_TO_PTR(n), P4_INT32);
  116549. assert( n<=pTab->nCol );
  116550. }
  116551. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  116552. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
  116553. (const u8*)&pTabItem->colUsed, P4_INT64);
  116554. #endif
  116555. }else{
  116556. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  116557. }
  116558. if( pLoop->wsFlags & WHERE_INDEXED ){
  116559. Index *pIx = pLoop->u.btree.pIndex;
  116560. int iIndexCur;
  116561. int op = OP_OpenRead;
  116562. /* iIdxCur is always set if to a positive value if ONEPASS is possible */
  116563. assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  116564. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  116565. && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
  116566. ){
  116567. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  116568. ** WITHOUT ROWID table. No need for a separate index */
  116569. iIndexCur = pLevel->iTabCur;
  116570. op = 0;
  116571. }else if( pWInfo->okOnePass ){
  116572. Index *pJ = pTabItem->pTab->pIndex;
  116573. iIndexCur = iIdxCur;
  116574. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  116575. while( ALWAYS(pJ) && pJ!=pIx ){
  116576. iIndexCur++;
  116577. pJ = pJ->pNext;
  116578. }
  116579. op = OP_OpenWrite;
  116580. pWInfo->aiCurOnePass[1] = iIndexCur;
  116581. }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
  116582. iIndexCur = iIdxCur;
  116583. if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
  116584. }else{
  116585. iIndexCur = pParse->nTab++;
  116586. }
  116587. pLevel->iIdxCur = iIndexCur;
  116588. assert( pIx->pSchema==pTab->pSchema );
  116589. assert( iIndexCur>=0 );
  116590. if( op ){
  116591. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  116592. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  116593. if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
  116594. && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
  116595. && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
  116596. ){
  116597. sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
  116598. }
  116599. VdbeComment((v, "%s", pIx->zName));
  116600. #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
  116601. {
  116602. u64 colUsed = 0;
  116603. int ii, jj;
  116604. for(ii=0; ii<pIx->nColumn; ii++){
  116605. jj = pIx->aiColumn[ii];
  116606. if( jj<0 ) continue;
  116607. if( jj>63 ) jj = 63;
  116608. if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
  116609. colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
  116610. }
  116611. sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
  116612. (u8*)&colUsed, P4_INT64);
  116613. }
  116614. #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
  116615. }
  116616. }
  116617. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  116618. }
  116619. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  116620. if( db->mallocFailed ) goto whereBeginError;
  116621. /* Generate the code to do the search. Each iteration of the for
  116622. ** loop below generates code for a single nested loop of the VM
  116623. ** program.
  116624. */
  116625. notReady = ~(Bitmask)0;
  116626. for(ii=0; ii<nTabList; ii++){
  116627. int addrExplain;
  116628. int wsFlags;
  116629. pLevel = &pWInfo->a[ii];
  116630. wsFlags = pLevel->pWLoop->wsFlags;
  116631. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  116632. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  116633. constructAutomaticIndex(pParse, &pWInfo->sWC,
  116634. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  116635. if( db->mallocFailed ) goto whereBeginError;
  116636. }
  116637. #endif
  116638. addrExplain = sqlite3WhereExplainOneScan(
  116639. pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
  116640. );
  116641. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  116642. notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
  116643. pWInfo->iContinue = pLevel->addrCont;
  116644. if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
  116645. sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
  116646. }
  116647. }
  116648. /* Done. */
  116649. VdbeModuleComment((v, "Begin WHERE-core"));
  116650. return pWInfo;
  116651. /* Jump here if malloc fails */
  116652. whereBeginError:
  116653. if( pWInfo ){
  116654. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  116655. whereInfoFree(db, pWInfo);
  116656. }
  116657. return 0;
  116658. }
  116659. /*
  116660. ** Generate the end of the WHERE loop. See comments on
  116661. ** sqlite3WhereBegin() for additional information.
  116662. */
  116663. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  116664. Parse *pParse = pWInfo->pParse;
  116665. Vdbe *v = pParse->pVdbe;
  116666. int i;
  116667. WhereLevel *pLevel;
  116668. WhereLoop *pLoop;
  116669. SrcList *pTabList = pWInfo->pTabList;
  116670. sqlite3 *db = pParse->db;
  116671. /* Generate loop termination code.
  116672. */
  116673. VdbeModuleComment((v, "End WHERE-core"));
  116674. sqlite3ExprCacheClear(pParse);
  116675. for(i=pWInfo->nLevel-1; i>=0; i--){
  116676. int addr;
  116677. pLevel = &pWInfo->a[i];
  116678. pLoop = pLevel->pWLoop;
  116679. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  116680. if( pLevel->op!=OP_Noop ){
  116681. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  116682. sqlite3VdbeChangeP5(v, pLevel->p5);
  116683. VdbeCoverage(v);
  116684. VdbeCoverageIf(v, pLevel->op==OP_Next);
  116685. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  116686. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  116687. }
  116688. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  116689. struct InLoop *pIn;
  116690. int j;
  116691. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  116692. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  116693. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  116694. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  116695. VdbeCoverage(v);
  116696. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  116697. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  116698. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  116699. }
  116700. }
  116701. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  116702. if( pLevel->addrSkip ){
  116703. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
  116704. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  116705. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  116706. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  116707. }
  116708. if( pLevel->addrLikeRep ){
  116709. int op;
  116710. if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
  116711. op = OP_DecrJumpZero;
  116712. }else{
  116713. op = OP_JumpZeroIncr;
  116714. }
  116715. sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
  116716. VdbeCoverage(v);
  116717. }
  116718. if( pLevel->iLeftJoin ){
  116719. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  116720. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  116721. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  116722. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  116723. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  116724. }
  116725. if( pLoop->wsFlags & WHERE_INDEXED ){
  116726. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  116727. }
  116728. if( pLevel->op==OP_Return ){
  116729. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  116730. }else{
  116731. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  116732. }
  116733. sqlite3VdbeJumpHere(v, addr);
  116734. }
  116735. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  116736. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  116737. }
  116738. /* The "break" point is here, just past the end of the outer loop.
  116739. ** Set it.
  116740. */
  116741. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  116742. assert( pWInfo->nLevel<=pTabList->nSrc );
  116743. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  116744. int k, last;
  116745. VdbeOp *pOp;
  116746. Index *pIdx = 0;
  116747. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  116748. Table *pTab = pTabItem->pTab;
  116749. assert( pTab!=0 );
  116750. pLoop = pLevel->pWLoop;
  116751. /* For a co-routine, change all OP_Column references to the table of
  116752. ** the co-routine into OP_Copy of result contained in a register.
  116753. ** OP_Rowid becomes OP_Null.
  116754. */
  116755. if( pTabItem->viaCoroutine && !db->mallocFailed ){
  116756. translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
  116757. pTabItem->regResult);
  116758. continue;
  116759. }
  116760. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  116761. ** Except, do not close cursors that will be reused by the OR optimization
  116762. ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
  116763. ** created for the ONEPASS optimization.
  116764. */
  116765. if( (pTab->tabFlags & TF_Ephemeral)==0
  116766. && pTab->pSelect==0
  116767. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  116768. ){
  116769. int ws = pLoop->wsFlags;
  116770. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  116771. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  116772. }
  116773. if( (ws & WHERE_INDEXED)!=0
  116774. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  116775. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  116776. ){
  116777. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  116778. }
  116779. }
  116780. /* If this scan uses an index, make VDBE code substitutions to read data
  116781. ** from the index instead of from the table where possible. In some cases
  116782. ** this optimization prevents the table from ever being read, which can
  116783. ** yield a significant performance boost.
  116784. **
  116785. ** Calls to the code generator in between sqlite3WhereBegin and
  116786. ** sqlite3WhereEnd will have created code that references the table
  116787. ** directly. This loop scans all that code looking for opcodes
  116788. ** that reference the table and converts them into opcodes that
  116789. ** reference the index.
  116790. */
  116791. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  116792. pIdx = pLoop->u.btree.pIndex;
  116793. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  116794. pIdx = pLevel->u.pCovidx;
  116795. }
  116796. if( pIdx && !db->mallocFailed ){
  116797. last = sqlite3VdbeCurrentAddr(v);
  116798. k = pLevel->addrBody;
  116799. pOp = sqlite3VdbeGetOp(v, k);
  116800. for(; k<last; k++, pOp++){
  116801. if( pOp->p1!=pLevel->iTabCur ) continue;
  116802. if( pOp->opcode==OP_Column ){
  116803. int x = pOp->p2;
  116804. assert( pIdx->pTable==pTab );
  116805. if( !HasRowid(pTab) ){
  116806. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  116807. x = pPk->aiColumn[x];
  116808. }
  116809. x = sqlite3ColumnOfIndex(pIdx, x);
  116810. if( x>=0 ){
  116811. pOp->p2 = x;
  116812. pOp->p1 = pLevel->iIdxCur;
  116813. }
  116814. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
  116815. }else if( pOp->opcode==OP_Rowid ){
  116816. pOp->p1 = pLevel->iIdxCur;
  116817. pOp->opcode = OP_IdxRowid;
  116818. }
  116819. }
  116820. }
  116821. }
  116822. /* Final cleanup
  116823. */
  116824. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  116825. whereInfoFree(db, pWInfo);
  116826. return;
  116827. }
  116828. /************** End of where.c ***********************************************/
  116829. /************** Begin file parse.c *******************************************/
  116830. /* Driver template for the LEMON parser generator.
  116831. ** The author disclaims copyright to this source code.
  116832. **
  116833. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  116834. ** The only modifications are the addition of a couple of NEVER()
  116835. ** macros to disable tests that are needed in the case of a general
  116836. ** LALR(1) grammar but which are always false in the
  116837. ** specific grammar used by SQLite.
  116838. */
  116839. /* First off, code is included that follows the "include" declaration
  116840. ** in the input grammar file. */
  116841. /* #include <stdio.h> */
  116842. /* #include "sqliteInt.h" */
  116843. /*
  116844. ** Disable all error recovery processing in the parser push-down
  116845. ** automaton.
  116846. */
  116847. #define YYNOERRORRECOVERY 1
  116848. /*
  116849. ** Make yytestcase() the same as testcase()
  116850. */
  116851. #define yytestcase(X) testcase(X)
  116852. /*
  116853. ** An instance of this structure holds information about the
  116854. ** LIMIT clause of a SELECT statement.
  116855. */
  116856. struct LimitVal {
  116857. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  116858. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  116859. };
  116860. /*
  116861. ** An instance of this structure is used to store the LIKE,
  116862. ** GLOB, NOT LIKE, and NOT GLOB operators.
  116863. */
  116864. struct LikeOp {
  116865. Token eOperator; /* "like" or "glob" or "regexp" */
  116866. int bNot; /* True if the NOT keyword is present */
  116867. };
  116868. /*
  116869. ** An instance of the following structure describes the event of a
  116870. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  116871. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  116872. **
  116873. ** UPDATE ON (a,b,c)
  116874. **
  116875. ** Then the "b" IdList records the list "a,b,c".
  116876. */
  116877. struct TrigEvent { int a; IdList * b; };
  116878. /*
  116879. ** An instance of this structure holds the ATTACH key and the key type.
  116880. */
  116881. struct AttachKey { int type; Token key; };
  116882. /*
  116883. ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
  116884. ** all elements in the list. And make sure list length does not exceed
  116885. ** SQLITE_LIMIT_COMPOUND_SELECT.
  116886. */
  116887. static void parserDoubleLinkSelect(Parse *pParse, Select *p){
  116888. if( p->pPrior ){
  116889. Select *pNext = 0, *pLoop;
  116890. int mxSelect, cnt = 0;
  116891. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  116892. pLoop->pNext = pNext;
  116893. pLoop->selFlags |= SF_Compound;
  116894. }
  116895. if( (p->selFlags & SF_MultiValue)==0 &&
  116896. (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
  116897. cnt>mxSelect
  116898. ){
  116899. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  116900. }
  116901. }
  116902. }
  116903. /* This is a utility routine used to set the ExprSpan.zStart and
  116904. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  116905. ** range of text beginning with pStart and going to the end of pEnd.
  116906. */
  116907. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  116908. pOut->zStart = pStart->z;
  116909. pOut->zEnd = &pEnd->z[pEnd->n];
  116910. }
  116911. /* Construct a new Expr object from a single identifier. Use the
  116912. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  116913. ** that created the expression.
  116914. */
  116915. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  116916. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  116917. pOut->zStart = pValue->z;
  116918. pOut->zEnd = &pValue->z[pValue->n];
  116919. }
  116920. /* This routine constructs a binary expression node out of two ExprSpan
  116921. ** objects and uses the result to populate a new ExprSpan object.
  116922. */
  116923. static void spanBinaryExpr(
  116924. ExprSpan *pOut, /* Write the result here */
  116925. Parse *pParse, /* The parsing context. Errors accumulate here */
  116926. int op, /* The binary operation */
  116927. ExprSpan *pLeft, /* The left operand */
  116928. ExprSpan *pRight /* The right operand */
  116929. ){
  116930. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  116931. pOut->zStart = pLeft->zStart;
  116932. pOut->zEnd = pRight->zEnd;
  116933. }
  116934. /* Construct an expression node for a unary postfix operator
  116935. */
  116936. static void spanUnaryPostfix(
  116937. ExprSpan *pOut, /* Write the new expression node here */
  116938. Parse *pParse, /* Parsing context to record errors */
  116939. int op, /* The operator */
  116940. ExprSpan *pOperand, /* The operand */
  116941. Token *pPostOp /* The operand token for setting the span */
  116942. ){
  116943. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  116944. pOut->zStart = pOperand->zStart;
  116945. pOut->zEnd = &pPostOp->z[pPostOp->n];
  116946. }
  116947. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  116948. ** unary TK_ISNULL or TK_NOTNULL expression. */
  116949. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  116950. sqlite3 *db = pParse->db;
  116951. if( pY && pA && pY->op==TK_NULL ){
  116952. pA->op = (u8)op;
  116953. sqlite3ExprDelete(db, pA->pRight);
  116954. pA->pRight = 0;
  116955. }
  116956. }
  116957. /* Construct an expression node for a unary prefix operator
  116958. */
  116959. static void spanUnaryPrefix(
  116960. ExprSpan *pOut, /* Write the new expression node here */
  116961. Parse *pParse, /* Parsing context to record errors */
  116962. int op, /* The operator */
  116963. ExprSpan *pOperand, /* The operand */
  116964. Token *pPreOp /* The operand token for setting the span */
  116965. ){
  116966. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  116967. pOut->zStart = pPreOp->z;
  116968. pOut->zEnd = pOperand->zEnd;
  116969. }
  116970. /* Next is all token values, in a form suitable for use by makeheaders.
  116971. ** This section will be null unless lemon is run with the -m switch.
  116972. */
  116973. /*
  116974. ** These constants (all generated automatically by the parser generator)
  116975. ** specify the various kinds of tokens (terminals) that the parser
  116976. ** understands.
  116977. **
  116978. ** Each symbol here is a terminal symbol in the grammar.
  116979. */
  116980. /* Make sure the INTERFACE macro is defined.
  116981. */
  116982. #ifndef INTERFACE
  116983. # define INTERFACE 1
  116984. #endif
  116985. /* The next thing included is series of defines which control
  116986. ** various aspects of the generated parser.
  116987. ** YYCODETYPE is the data type used for storing terminal
  116988. ** and nonterminal numbers. "unsigned char" is
  116989. ** used if there are fewer than 250 terminals
  116990. ** and nonterminals. "int" is used otherwise.
  116991. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  116992. ** to no legal terminal or nonterminal number. This
  116993. ** number is used to fill in empty slots of the hash
  116994. ** table.
  116995. ** YYFALLBACK If defined, this indicates that one or more tokens
  116996. ** have fall-back values which should be used if the
  116997. ** original value of the token will not parse.
  116998. ** YYACTIONTYPE is the data type used for storing terminal
  116999. ** and nonterminal numbers. "unsigned char" is
  117000. ** used if there are fewer than 250 rules and
  117001. ** states combined. "int" is used otherwise.
  117002. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  117003. ** directly to the parser from the tokenizer.
  117004. ** YYMINORTYPE is the data type used for all minor tokens.
  117005. ** This is typically a union of many types, one of
  117006. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  117007. ** for base tokens is called "yy0".
  117008. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  117009. ** zero the stack is dynamically sized using realloc()
  117010. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  117011. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  117012. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  117013. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  117014. ** YYNSTATE the combined number of states.
  117015. ** YYNRULE the number of rules in the grammar
  117016. ** YYERRORSYMBOL is the code number of the error symbol. If not
  117017. ** defined, then do no error processing.
  117018. */
  117019. #define YYCODETYPE unsigned char
  117020. #define YYNOCODE 254
  117021. #define YYACTIONTYPE unsigned short int
  117022. #define YYWILDCARD 70
  117023. #define sqlite3ParserTOKENTYPE Token
  117024. typedef union {
  117025. int yyinit;
  117026. sqlite3ParserTOKENTYPE yy0;
  117027. Select* yy3;
  117028. ExprList* yy14;
  117029. With* yy59;
  117030. SrcList* yy65;
  117031. struct LikeOp yy96;
  117032. Expr* yy132;
  117033. u8 yy186;
  117034. int yy328;
  117035. ExprSpan yy346;
  117036. struct TrigEvent yy378;
  117037. u16 yy381;
  117038. IdList* yy408;
  117039. struct {int value; int mask;} yy429;
  117040. TriggerStep* yy473;
  117041. struct LimitVal yy476;
  117042. } YYMINORTYPE;
  117043. #ifndef YYSTACKDEPTH
  117044. #define YYSTACKDEPTH 100
  117045. #endif
  117046. #define sqlite3ParserARG_SDECL Parse *pParse;
  117047. #define sqlite3ParserARG_PDECL ,Parse *pParse
  117048. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  117049. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  117050. #define YYNSTATE 642
  117051. #define YYNRULE 327
  117052. #define YYFALLBACK 1
  117053. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  117054. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  117055. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  117056. /* The yyzerominor constant is used to initialize instances of
  117057. ** YYMINORTYPE objects to zero. */
  117058. static const YYMINORTYPE yyzerominor = { 0 };
  117059. /* Define the yytestcase() macro to be a no-op if is not already defined
  117060. ** otherwise.
  117061. **
  117062. ** Applications can choose to define yytestcase() in the %include section
  117063. ** to a macro that can assist in verifying code coverage. For production
  117064. ** code the yytestcase() macro should be turned off. But it is useful
  117065. ** for testing.
  117066. */
  117067. #ifndef yytestcase
  117068. # define yytestcase(X)
  117069. #endif
  117070. /* Next are the tables used to determine what action to take based on the
  117071. ** current state and lookahead token. These tables are used to implement
  117072. ** functions that take a state number and lookahead value and return an
  117073. ** action integer.
  117074. **
  117075. ** Suppose the action integer is N. Then the action is determined as
  117076. ** follows
  117077. **
  117078. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  117079. ** token onto the stack and goto state N.
  117080. **
  117081. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  117082. **
  117083. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  117084. **
  117085. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  117086. **
  117087. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  117088. ** slots in the yy_action[] table.
  117089. **
  117090. ** The action table is constructed as a single large table named yy_action[].
  117091. ** Given state S and lookahead X, the action is computed as
  117092. **
  117093. ** yy_action[ yy_shift_ofst[S] + X ]
  117094. **
  117095. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  117096. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  117097. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  117098. ** and that yy_default[S] should be used instead.
  117099. **
  117100. ** The formula above is for computing the action when the lookahead is
  117101. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  117102. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  117103. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  117104. ** YY_SHIFT_USE_DFLT.
  117105. **
  117106. ** The following are the tables generated in this section:
  117107. **
  117108. ** yy_action[] A single table containing all actions.
  117109. ** yy_lookahead[] A table containing the lookahead for each entry in
  117110. ** yy_action. Used to detect hash collisions.
  117111. ** yy_shift_ofst[] For each state, the offset into yy_action for
  117112. ** shifting terminals.
  117113. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  117114. ** shifting non-terminals after a reduce.
  117115. ** yy_default[] Default action for each state.
  117116. */
  117117. #define YY_ACTTAB_COUNT (1497)
  117118. static const YYACTIONTYPE yy_action[] = {
  117119. /* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
  117120. /* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
  117121. /* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
  117122. /* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
  117123. /* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
  117124. /* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
  117125. /* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
  117126. /* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
  117127. /* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
  117128. /* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
  117129. /* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
  117130. /* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
  117131. /* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
  117132. /* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  117133. /* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
  117134. /* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
  117135. /* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
  117136. /* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
  117137. /* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
  117138. /* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
  117139. /* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
  117140. /* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
  117141. /* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  117142. /* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
  117143. /* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
  117144. /* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
  117145. /* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
  117146. /* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
  117147. /* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
  117148. /* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
  117149. /* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
  117150. /* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
  117151. /* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
  117152. /* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
  117153. /* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
  117154. /* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
  117155. /* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
  117156. /* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
  117157. /* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
  117158. /* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
  117159. /* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
  117160. /* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
  117161. /* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
  117162. /* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
  117163. /* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
  117164. /* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
  117165. /* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
  117166. /* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
  117167. /* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
  117168. /* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  117169. /* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
  117170. /* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
  117171. /* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
  117172. /* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
  117173. /* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
  117174. /* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
  117175. /* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
  117176. /* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
  117177. /* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
  117178. /* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
  117179. /* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
  117180. /* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
  117181. /* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
  117182. /* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
  117183. /* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
  117184. /* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
  117185. /* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
  117186. /* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
  117187. /* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
  117188. /* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
  117189. /* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
  117190. /* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
  117191. /* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  117192. /* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  117193. /* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
  117194. /* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
  117195. /* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
  117196. /* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
  117197. /* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
  117198. /* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
  117199. /* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
  117200. /* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  117201. /* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
  117202. /* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
  117203. /* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
  117204. /* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
  117205. /* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
  117206. /* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
  117207. /* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
  117208. /* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
  117209. /* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  117210. /* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
  117211. /* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
  117212. /* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
  117213. /* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
  117214. /* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  117215. /* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  117216. /* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
  117217. /* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
  117218. /* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
  117219. /* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
  117220. /* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
  117221. /* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
  117222. /* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
  117223. /* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
  117224. /* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
  117225. /* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
  117226. /* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
  117227. /* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
  117228. /* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
  117229. /* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
  117230. /* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
  117231. /* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
  117232. /* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
  117233. /* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
  117234. /* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
  117235. /* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
  117236. /* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
  117237. /* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
  117238. /* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
  117239. /* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
  117240. /* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
  117241. /* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
  117242. /* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
  117243. /* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
  117244. /* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
  117245. /* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
  117246. /* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
  117247. /* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
  117248. /* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
  117249. /* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
  117250. /* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
  117251. /* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
  117252. /* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
  117253. /* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
  117254. /* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
  117255. /* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
  117256. /* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
  117257. /* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
  117258. /* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
  117259. /* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
  117260. /* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
  117261. /* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
  117262. /* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
  117263. /* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
  117264. /* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
  117265. /* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
  117266. /* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
  117267. /* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
  117268. /* 1490 */ 971, 971, 971, 971, 971, 971, 338,
  117269. };
  117270. static const YYCODETYPE yy_lookahead[] = {
  117271. /* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
  117272. /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  117273. /* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
  117274. /* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
  117275. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
  117276. /* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
  117277. /* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
  117278. /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
  117279. /* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
  117280. /* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
  117281. /* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
  117282. /* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
  117283. /* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
  117284. /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  117285. /* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
  117286. /* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
  117287. /* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
  117288. /* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
  117289. /* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
  117290. /* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
  117291. /* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
  117292. /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
  117293. /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  117294. /* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
  117295. /* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
  117296. /* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
  117297. /* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
  117298. /* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
  117299. /* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
  117300. /* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
  117301. /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
  117302. /* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
  117303. /* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
  117304. /* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
  117305. /* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
  117306. /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
  117307. /* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
  117308. /* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
  117309. /* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
  117310. /* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
  117311. /* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
  117312. /* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  117313. /* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
  117314. /* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
  117315. /* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
  117316. /* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
  117317. /* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
  117318. /* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
  117319. /* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
  117320. /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  117321. /* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
  117322. /* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
  117323. /* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
  117324. /* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
  117325. /* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
  117326. /* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
  117327. /* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
  117328. /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
  117329. /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  117330. /* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
  117331. /* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
  117332. /* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
  117333. /* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
  117334. /* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
  117335. /* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
  117336. /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
  117337. /* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
  117338. /* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
  117339. /* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
  117340. /* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
  117341. /* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
  117342. /* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
  117343. /* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  117344. /* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  117345. /* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
  117346. /* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
  117347. /* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
  117348. /* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
  117349. /* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
  117350. /* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
  117351. /* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
  117352. /* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  117353. /* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
  117354. /* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
  117355. /* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
  117356. /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  117357. /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  117358. /* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
  117359. /* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
  117360. /* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
  117361. /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  117362. /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  117363. /* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
  117364. /* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
  117365. /* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
  117366. /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  117367. /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  117368. /* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
  117369. /* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
  117370. /* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
  117371. /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  117372. /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  117373. /* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
  117374. /* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
  117375. /* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
  117376. /* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
  117377. /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
  117378. /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
  117379. /* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
  117380. /* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
  117381. /* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
  117382. /* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
  117383. /* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
  117384. /* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
  117385. /* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
  117386. /* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
  117387. /* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
  117388. /* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
  117389. /* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
  117390. /* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
  117391. /* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
  117392. /* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
  117393. /* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
  117394. /* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
  117395. /* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
  117396. /* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
  117397. /* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
  117398. /* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
  117399. /* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
  117400. /* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
  117401. /* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
  117402. /* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
  117403. /* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
  117404. /* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
  117405. /* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
  117406. /* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
  117407. /* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
  117408. /* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
  117409. /* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
  117410. /* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
  117411. /* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
  117412. /* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
  117413. /* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
  117414. /* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
  117415. /* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
  117416. /* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
  117417. /* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
  117418. /* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
  117419. /* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
  117420. /* 1490 */ 253, 253, 253, 253, 253, 253, 141,
  117421. };
  117422. #define YY_SHIFT_USE_DFLT (-86)
  117423. #define YY_SHIFT_COUNT (429)
  117424. #define YY_SHIFT_MIN (-85)
  117425. #define YY_SHIFT_MAX (1383)
  117426. static const short yy_shift_ofst[] = {
  117427. /* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
  117428. /* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
  117429. /* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
  117430. /* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
  117431. /* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
  117432. /* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  117433. /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  117434. /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  117435. /* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  117436. /* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
  117437. /* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
  117438. /* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
  117439. /* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
  117440. /* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  117441. /* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
  117442. /* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
  117443. /* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
  117444. /* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  117445. /* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
  117446. /* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
  117447. /* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
  117448. /* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
  117449. /* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
  117450. /* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
  117451. /* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
  117452. /* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
  117453. /* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
  117454. /* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
  117455. /* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
  117456. /* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
  117457. /* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
  117458. /* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
  117459. /* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
  117460. /* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
  117461. /* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
  117462. /* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
  117463. /* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
  117464. /* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
  117465. /* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
  117466. /* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
  117467. /* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
  117468. /* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
  117469. /* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
  117470. };
  117471. #define YY_REDUCE_USE_DFLT (-110)
  117472. #define YY_REDUCE_COUNT (305)
  117473. #define YY_REDUCE_MIN (-109)
  117474. #define YY_REDUCE_MAX (1323)
  117475. static const short yy_reduce_ofst[] = {
  117476. /* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
  117477. /* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
  117478. /* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
  117479. /* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  117480. /* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  117481. /* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
  117482. /* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
  117483. /* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
  117484. /* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
  117485. /* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
  117486. /* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
  117487. /* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
  117488. /* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
  117489. /* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
  117490. /* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
  117491. /* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
  117492. /* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
  117493. /* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
  117494. /* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
  117495. /* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
  117496. /* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
  117497. /* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
  117498. /* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
  117499. /* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
  117500. /* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
  117501. /* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
  117502. /* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
  117503. /* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
  117504. /* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
  117505. /* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
  117506. /* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
  117507. };
  117508. static const YYACTIONTYPE yy_default[] = {
  117509. /* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
  117510. /* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
  117511. /* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
  117512. /* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
  117513. /* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
  117514. /* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117515. /* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117516. /* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117517. /* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117518. /* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
  117519. /* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
  117520. /* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
  117521. /* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117522. /* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117523. /* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
  117524. /* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
  117525. /* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
  117526. /* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117527. /* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117528. /* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117529. /* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
  117530. /* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
  117531. /* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
  117532. /* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
  117533. /* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
  117534. /* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
  117535. /* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
  117536. /* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
  117537. /* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
  117538. /* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
  117539. /* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
  117540. /* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
  117541. /* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117542. /* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
  117543. /* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117544. /* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
  117545. /* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
  117546. /* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  117547. /* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
  117548. /* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
  117549. /* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
  117550. /* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
  117551. /* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
  117552. /* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
  117553. /* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
  117554. /* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
  117555. /* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
  117556. /* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
  117557. /* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
  117558. /* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
  117559. /* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
  117560. /* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
  117561. /* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
  117562. /* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
  117563. /* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
  117564. /* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
  117565. /* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
  117566. /* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
  117567. /* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
  117568. /* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
  117569. /* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
  117570. /* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
  117571. /* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
  117572. /* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
  117573. /* 640 */ 645, 643,
  117574. };
  117575. /* The next table maps tokens into fallback tokens. If a construct
  117576. ** like the following:
  117577. **
  117578. ** %fallback ID X Y Z.
  117579. **
  117580. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  117581. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  117582. ** but it does not parse, the type of the token is changed to ID and
  117583. ** the parse is retried before an error is thrown.
  117584. */
  117585. #ifdef YYFALLBACK
  117586. static const YYCODETYPE yyFallback[] = {
  117587. 0, /* $ => nothing */
  117588. 0, /* SEMI => nothing */
  117589. 27, /* EXPLAIN => ID */
  117590. 27, /* QUERY => ID */
  117591. 27, /* PLAN => ID */
  117592. 27, /* BEGIN => ID */
  117593. 0, /* TRANSACTION => nothing */
  117594. 27, /* DEFERRED => ID */
  117595. 27, /* IMMEDIATE => ID */
  117596. 27, /* EXCLUSIVE => ID */
  117597. 0, /* COMMIT => nothing */
  117598. 27, /* END => ID */
  117599. 27, /* ROLLBACK => ID */
  117600. 27, /* SAVEPOINT => ID */
  117601. 27, /* RELEASE => ID */
  117602. 0, /* TO => nothing */
  117603. 0, /* TABLE => nothing */
  117604. 0, /* CREATE => nothing */
  117605. 27, /* IF => ID */
  117606. 0, /* NOT => nothing */
  117607. 0, /* EXISTS => nothing */
  117608. 27, /* TEMP => ID */
  117609. 0, /* LP => nothing */
  117610. 0, /* RP => nothing */
  117611. 0, /* AS => nothing */
  117612. 27, /* WITHOUT => ID */
  117613. 0, /* COMMA => nothing */
  117614. 0, /* ID => nothing */
  117615. 0, /* INDEXED => nothing */
  117616. 27, /* ABORT => ID */
  117617. 27, /* ACTION => ID */
  117618. 27, /* AFTER => ID */
  117619. 27, /* ANALYZE => ID */
  117620. 27, /* ASC => ID */
  117621. 27, /* ATTACH => ID */
  117622. 27, /* BEFORE => ID */
  117623. 27, /* BY => ID */
  117624. 27, /* CASCADE => ID */
  117625. 27, /* CAST => ID */
  117626. 27, /* COLUMNKW => ID */
  117627. 27, /* CONFLICT => ID */
  117628. 27, /* DATABASE => ID */
  117629. 27, /* DESC => ID */
  117630. 27, /* DETACH => ID */
  117631. 27, /* EACH => ID */
  117632. 27, /* FAIL => ID */
  117633. 27, /* FOR => ID */
  117634. 27, /* IGNORE => ID */
  117635. 27, /* INITIALLY => ID */
  117636. 27, /* INSTEAD => ID */
  117637. 27, /* LIKE_KW => ID */
  117638. 27, /* MATCH => ID */
  117639. 27, /* NO => ID */
  117640. 27, /* KEY => ID */
  117641. 27, /* OF => ID */
  117642. 27, /* OFFSET => ID */
  117643. 27, /* PRAGMA => ID */
  117644. 27, /* RAISE => ID */
  117645. 27, /* RECURSIVE => ID */
  117646. 27, /* REPLACE => ID */
  117647. 27, /* RESTRICT => ID */
  117648. 27, /* ROW => ID */
  117649. 27, /* TRIGGER => ID */
  117650. 27, /* VACUUM => ID */
  117651. 27, /* VIEW => ID */
  117652. 27, /* VIRTUAL => ID */
  117653. 27, /* WITH => ID */
  117654. 27, /* REINDEX => ID */
  117655. 27, /* RENAME => ID */
  117656. 27, /* CTIME_KW => ID */
  117657. };
  117658. #endif /* YYFALLBACK */
  117659. /* The following structure represents a single element of the
  117660. ** parser's stack. Information stored includes:
  117661. **
  117662. ** + The state number for the parser at this level of the stack.
  117663. **
  117664. ** + The value of the token stored at this level of the stack.
  117665. ** (In other words, the "major" token.)
  117666. **
  117667. ** + The semantic value stored at this level of the stack. This is
  117668. ** the information used by the action routines in the grammar.
  117669. ** It is sometimes called the "minor" token.
  117670. */
  117671. struct yyStackEntry {
  117672. YYACTIONTYPE stateno; /* The state-number */
  117673. YYCODETYPE major; /* The major token value. This is the code
  117674. ** number for the token at this stack level */
  117675. YYMINORTYPE minor; /* The user-supplied minor token value. This
  117676. ** is the value of the token */
  117677. };
  117678. typedef struct yyStackEntry yyStackEntry;
  117679. /* The state of the parser is completely contained in an instance of
  117680. ** the following structure */
  117681. struct yyParser {
  117682. int yyidx; /* Index of top element in stack */
  117683. #ifdef YYTRACKMAXSTACKDEPTH
  117684. int yyidxMax; /* Maximum value of yyidx */
  117685. #endif
  117686. int yyerrcnt; /* Shifts left before out of the error */
  117687. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  117688. #if YYSTACKDEPTH<=0
  117689. int yystksz; /* Current side of the stack */
  117690. yyStackEntry *yystack; /* The parser's stack */
  117691. #else
  117692. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  117693. #endif
  117694. };
  117695. typedef struct yyParser yyParser;
  117696. #ifndef NDEBUG
  117697. /* #include <stdio.h> */
  117698. static FILE *yyTraceFILE = 0;
  117699. static char *yyTracePrompt = 0;
  117700. #endif /* NDEBUG */
  117701. #ifndef NDEBUG
  117702. /*
  117703. ** Turn parser tracing on by giving a stream to which to write the trace
  117704. ** and a prompt to preface each trace message. Tracing is turned off
  117705. ** by making either argument NULL
  117706. **
  117707. ** Inputs:
  117708. ** <ul>
  117709. ** <li> A FILE* to which trace output should be written.
  117710. ** If NULL, then tracing is turned off.
  117711. ** <li> A prefix string written at the beginning of every
  117712. ** line of trace output. If NULL, then tracing is
  117713. ** turned off.
  117714. ** </ul>
  117715. **
  117716. ** Outputs:
  117717. ** None.
  117718. */
  117719. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  117720. yyTraceFILE = TraceFILE;
  117721. yyTracePrompt = zTracePrompt;
  117722. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  117723. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  117724. }
  117725. #endif /* NDEBUG */
  117726. #ifndef NDEBUG
  117727. /* For tracing shifts, the names of all terminals and nonterminals
  117728. ** are required. The following table supplies these names */
  117729. static const char *const yyTokenName[] = {
  117730. "$", "SEMI", "EXPLAIN", "QUERY",
  117731. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  117732. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  117733. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  117734. "TABLE", "CREATE", "IF", "NOT",
  117735. "EXISTS", "TEMP", "LP", "RP",
  117736. "AS", "WITHOUT", "COMMA", "ID",
  117737. "INDEXED", "ABORT", "ACTION", "AFTER",
  117738. "ANALYZE", "ASC", "ATTACH", "BEFORE",
  117739. "BY", "CASCADE", "CAST", "COLUMNKW",
  117740. "CONFLICT", "DATABASE", "DESC", "DETACH",
  117741. "EACH", "FAIL", "FOR", "IGNORE",
  117742. "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
  117743. "NO", "KEY", "OF", "OFFSET",
  117744. "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
  117745. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  117746. "VIEW", "VIRTUAL", "WITH", "REINDEX",
  117747. "RENAME", "CTIME_KW", "ANY", "OR",
  117748. "AND", "IS", "BETWEEN", "IN",
  117749. "ISNULL", "NOTNULL", "NE", "EQ",
  117750. "GT", "LE", "LT", "GE",
  117751. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  117752. "RSHIFT", "PLUS", "MINUS", "STAR",
  117753. "SLASH", "REM", "CONCAT", "COLLATE",
  117754. "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
  117755. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  117756. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  117757. "INSERT", "DELETE", "UPDATE", "SET",
  117758. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  117759. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  117760. "VALUES", "DISTINCT", "DOT", "FROM",
  117761. "JOIN", "USING", "ORDER", "GROUP",
  117762. "HAVING", "LIMIT", "WHERE", "INTO",
  117763. "INTEGER", "FLOAT", "BLOB", "VARIABLE",
  117764. "CASE", "WHEN", "THEN", "ELSE",
  117765. "INDEX", "ALTER", "ADD", "error",
  117766. "input", "cmdlist", "ecmd", "explain",
  117767. "cmdx", "cmd", "transtype", "trans_opt",
  117768. "nm", "savepoint_opt", "create_table", "create_table_args",
  117769. "createkw", "temp", "ifnotexists", "dbnm",
  117770. "columnlist", "conslist_opt", "table_options", "select",
  117771. "column", "columnid", "type", "carglist",
  117772. "typetoken", "typename", "signed", "plus_num",
  117773. "minus_num", "ccons", "term", "expr",
  117774. "onconf", "sortorder", "autoinc", "idxlist_opt",
  117775. "refargs", "defer_subclause", "refarg", "refact",
  117776. "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
  117777. "idxlist", "defer_subclause_opt", "orconf", "resolvetype",
  117778. "raisetype", "ifexists", "fullname", "selectnowith",
  117779. "oneselect", "with", "multiselect_op", "distinct",
  117780. "selcollist", "from", "where_opt", "groupby_opt",
  117781. "having_opt", "orderby_opt", "limit_opt", "values",
  117782. "nexprlist", "exprlist", "sclp", "as",
  117783. "seltablist", "stl_prefix", "joinop", "indexed_opt",
  117784. "on_opt", "using_opt", "joinop2", "idlist",
  117785. "sortlist", "setlist", "insert_cmd", "inscollist_opt",
  117786. "likeop", "between_op", "in_op", "case_operand",
  117787. "case_exprlist", "case_else", "uniqueflag", "collate",
  117788. "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
  117789. "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
  117790. "trnm", "tridxby", "database_kw_opt", "key_opt",
  117791. "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
  117792. "vtabarg", "vtabargtoken", "lp", "anylist",
  117793. "wqlist",
  117794. };
  117795. #endif /* NDEBUG */
  117796. #ifndef NDEBUG
  117797. /* For tracing reduce actions, the names of all rules are required.
  117798. */
  117799. static const char *const yyRuleName[] = {
  117800. /* 0 */ "input ::= cmdlist",
  117801. /* 1 */ "cmdlist ::= cmdlist ecmd",
  117802. /* 2 */ "cmdlist ::= ecmd",
  117803. /* 3 */ "ecmd ::= SEMI",
  117804. /* 4 */ "ecmd ::= explain cmdx SEMI",
  117805. /* 5 */ "explain ::=",
  117806. /* 6 */ "explain ::= EXPLAIN",
  117807. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  117808. /* 8 */ "cmdx ::= cmd",
  117809. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  117810. /* 10 */ "trans_opt ::=",
  117811. /* 11 */ "trans_opt ::= TRANSACTION",
  117812. /* 12 */ "trans_opt ::= TRANSACTION nm",
  117813. /* 13 */ "transtype ::=",
  117814. /* 14 */ "transtype ::= DEFERRED",
  117815. /* 15 */ "transtype ::= IMMEDIATE",
  117816. /* 16 */ "transtype ::= EXCLUSIVE",
  117817. /* 17 */ "cmd ::= COMMIT trans_opt",
  117818. /* 18 */ "cmd ::= END trans_opt",
  117819. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  117820. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  117821. /* 21 */ "savepoint_opt ::=",
  117822. /* 22 */ "cmd ::= SAVEPOINT nm",
  117823. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  117824. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  117825. /* 25 */ "cmd ::= create_table create_table_args",
  117826. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  117827. /* 27 */ "createkw ::= CREATE",
  117828. /* 28 */ "ifnotexists ::=",
  117829. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  117830. /* 30 */ "temp ::= TEMP",
  117831. /* 31 */ "temp ::=",
  117832. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  117833. /* 33 */ "create_table_args ::= AS select",
  117834. /* 34 */ "table_options ::=",
  117835. /* 35 */ "table_options ::= WITHOUT nm",
  117836. /* 36 */ "columnlist ::= columnlist COMMA column",
  117837. /* 37 */ "columnlist ::= column",
  117838. /* 38 */ "column ::= columnid type carglist",
  117839. /* 39 */ "columnid ::= nm",
  117840. /* 40 */ "nm ::= ID|INDEXED",
  117841. /* 41 */ "nm ::= STRING",
  117842. /* 42 */ "nm ::= JOIN_KW",
  117843. /* 43 */ "type ::=",
  117844. /* 44 */ "type ::= typetoken",
  117845. /* 45 */ "typetoken ::= typename",
  117846. /* 46 */ "typetoken ::= typename LP signed RP",
  117847. /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
  117848. /* 48 */ "typename ::= ID|STRING",
  117849. /* 49 */ "typename ::= typename ID|STRING",
  117850. /* 50 */ "signed ::= plus_num",
  117851. /* 51 */ "signed ::= minus_num",
  117852. /* 52 */ "carglist ::= carglist ccons",
  117853. /* 53 */ "carglist ::=",
  117854. /* 54 */ "ccons ::= CONSTRAINT nm",
  117855. /* 55 */ "ccons ::= DEFAULT term",
  117856. /* 56 */ "ccons ::= DEFAULT LP expr RP",
  117857. /* 57 */ "ccons ::= DEFAULT PLUS term",
  117858. /* 58 */ "ccons ::= DEFAULT MINUS term",
  117859. /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
  117860. /* 60 */ "ccons ::= NULL onconf",
  117861. /* 61 */ "ccons ::= NOT NULL onconf",
  117862. /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  117863. /* 63 */ "ccons ::= UNIQUE onconf",
  117864. /* 64 */ "ccons ::= CHECK LP expr RP",
  117865. /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  117866. /* 66 */ "ccons ::= defer_subclause",
  117867. /* 67 */ "ccons ::= COLLATE ID|STRING",
  117868. /* 68 */ "autoinc ::=",
  117869. /* 69 */ "autoinc ::= AUTOINCR",
  117870. /* 70 */ "refargs ::=",
  117871. /* 71 */ "refargs ::= refargs refarg",
  117872. /* 72 */ "refarg ::= MATCH nm",
  117873. /* 73 */ "refarg ::= ON INSERT refact",
  117874. /* 74 */ "refarg ::= ON DELETE refact",
  117875. /* 75 */ "refarg ::= ON UPDATE refact",
  117876. /* 76 */ "refact ::= SET NULL",
  117877. /* 77 */ "refact ::= SET DEFAULT",
  117878. /* 78 */ "refact ::= CASCADE",
  117879. /* 79 */ "refact ::= RESTRICT",
  117880. /* 80 */ "refact ::= NO ACTION",
  117881. /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  117882. /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  117883. /* 83 */ "init_deferred_pred_opt ::=",
  117884. /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  117885. /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  117886. /* 86 */ "conslist_opt ::=",
  117887. /* 87 */ "conslist_opt ::= COMMA conslist",
  117888. /* 88 */ "conslist ::= conslist tconscomma tcons",
  117889. /* 89 */ "conslist ::= tcons",
  117890. /* 90 */ "tconscomma ::= COMMA",
  117891. /* 91 */ "tconscomma ::=",
  117892. /* 92 */ "tcons ::= CONSTRAINT nm",
  117893. /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  117894. /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  117895. /* 95 */ "tcons ::= CHECK LP expr RP onconf",
  117896. /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  117897. /* 97 */ "defer_subclause_opt ::=",
  117898. /* 98 */ "defer_subclause_opt ::= defer_subclause",
  117899. /* 99 */ "onconf ::=",
  117900. /* 100 */ "onconf ::= ON CONFLICT resolvetype",
  117901. /* 101 */ "orconf ::=",
  117902. /* 102 */ "orconf ::= OR resolvetype",
  117903. /* 103 */ "resolvetype ::= raisetype",
  117904. /* 104 */ "resolvetype ::= IGNORE",
  117905. /* 105 */ "resolvetype ::= REPLACE",
  117906. /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
  117907. /* 107 */ "ifexists ::= IF EXISTS",
  117908. /* 108 */ "ifexists ::=",
  117909. /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  117910. /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
  117911. /* 111 */ "cmd ::= select",
  117912. /* 112 */ "select ::= with selectnowith",
  117913. /* 113 */ "selectnowith ::= oneselect",
  117914. /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  117915. /* 115 */ "multiselect_op ::= UNION",
  117916. /* 116 */ "multiselect_op ::= UNION ALL",
  117917. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  117918. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  117919. /* 119 */ "oneselect ::= values",
  117920. /* 120 */ "values ::= VALUES LP nexprlist RP",
  117921. /* 121 */ "values ::= values COMMA LP exprlist RP",
  117922. /* 122 */ "distinct ::= DISTINCT",
  117923. /* 123 */ "distinct ::= ALL",
  117924. /* 124 */ "distinct ::=",
  117925. /* 125 */ "sclp ::= selcollist COMMA",
  117926. /* 126 */ "sclp ::=",
  117927. /* 127 */ "selcollist ::= sclp expr as",
  117928. /* 128 */ "selcollist ::= sclp STAR",
  117929. /* 129 */ "selcollist ::= sclp nm DOT STAR",
  117930. /* 130 */ "as ::= AS nm",
  117931. /* 131 */ "as ::= ID|STRING",
  117932. /* 132 */ "as ::=",
  117933. /* 133 */ "from ::=",
  117934. /* 134 */ "from ::= FROM seltablist",
  117935. /* 135 */ "stl_prefix ::= seltablist joinop",
  117936. /* 136 */ "stl_prefix ::=",
  117937. /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  117938. /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  117939. /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  117940. /* 140 */ "dbnm ::=",
  117941. /* 141 */ "dbnm ::= DOT nm",
  117942. /* 142 */ "fullname ::= nm dbnm",
  117943. /* 143 */ "joinop ::= COMMA|JOIN",
  117944. /* 144 */ "joinop ::= JOIN_KW JOIN",
  117945. /* 145 */ "joinop ::= JOIN_KW nm JOIN",
  117946. /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
  117947. /* 147 */ "on_opt ::= ON expr",
  117948. /* 148 */ "on_opt ::=",
  117949. /* 149 */ "indexed_opt ::=",
  117950. /* 150 */ "indexed_opt ::= INDEXED BY nm",
  117951. /* 151 */ "indexed_opt ::= NOT INDEXED",
  117952. /* 152 */ "using_opt ::= USING LP idlist RP",
  117953. /* 153 */ "using_opt ::=",
  117954. /* 154 */ "orderby_opt ::=",
  117955. /* 155 */ "orderby_opt ::= ORDER BY sortlist",
  117956. /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
  117957. /* 157 */ "sortlist ::= expr sortorder",
  117958. /* 158 */ "sortorder ::= ASC",
  117959. /* 159 */ "sortorder ::= DESC",
  117960. /* 160 */ "sortorder ::=",
  117961. /* 161 */ "groupby_opt ::=",
  117962. /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
  117963. /* 163 */ "having_opt ::=",
  117964. /* 164 */ "having_opt ::= HAVING expr",
  117965. /* 165 */ "limit_opt ::=",
  117966. /* 166 */ "limit_opt ::= LIMIT expr",
  117967. /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
  117968. /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
  117969. /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  117970. /* 170 */ "where_opt ::=",
  117971. /* 171 */ "where_opt ::= WHERE expr",
  117972. /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  117973. /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
  117974. /* 174 */ "setlist ::= nm EQ expr",
  117975. /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
  117976. /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  117977. /* 177 */ "insert_cmd ::= INSERT orconf",
  117978. /* 178 */ "insert_cmd ::= REPLACE",
  117979. /* 179 */ "inscollist_opt ::=",
  117980. /* 180 */ "inscollist_opt ::= LP idlist RP",
  117981. /* 181 */ "idlist ::= idlist COMMA nm",
  117982. /* 182 */ "idlist ::= nm",
  117983. /* 183 */ "expr ::= term",
  117984. /* 184 */ "expr ::= LP expr RP",
  117985. /* 185 */ "term ::= NULL",
  117986. /* 186 */ "expr ::= ID|INDEXED",
  117987. /* 187 */ "expr ::= JOIN_KW",
  117988. /* 188 */ "expr ::= nm DOT nm",
  117989. /* 189 */ "expr ::= nm DOT nm DOT nm",
  117990. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  117991. /* 191 */ "term ::= STRING",
  117992. /* 192 */ "expr ::= VARIABLE",
  117993. /* 193 */ "expr ::= expr COLLATE ID|STRING",
  117994. /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
  117995. /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  117996. /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
  117997. /* 197 */ "term ::= CTIME_KW",
  117998. /* 198 */ "expr ::= expr AND expr",
  117999. /* 199 */ "expr ::= expr OR expr",
  118000. /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
  118001. /* 201 */ "expr ::= expr EQ|NE expr",
  118002. /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  118003. /* 203 */ "expr ::= expr PLUS|MINUS expr",
  118004. /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
  118005. /* 205 */ "expr ::= expr CONCAT expr",
  118006. /* 206 */ "likeop ::= LIKE_KW|MATCH",
  118007. /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
  118008. /* 208 */ "expr ::= expr likeop expr",
  118009. /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
  118010. /* 210 */ "expr ::= expr ISNULL|NOTNULL",
  118011. /* 211 */ "expr ::= expr NOT NULL",
  118012. /* 212 */ "expr ::= expr IS expr",
  118013. /* 213 */ "expr ::= expr IS NOT expr",
  118014. /* 214 */ "expr ::= NOT expr",
  118015. /* 215 */ "expr ::= BITNOT expr",
  118016. /* 216 */ "expr ::= MINUS expr",
  118017. /* 217 */ "expr ::= PLUS expr",
  118018. /* 218 */ "between_op ::= BETWEEN",
  118019. /* 219 */ "between_op ::= NOT BETWEEN",
  118020. /* 220 */ "expr ::= expr between_op expr AND expr",
  118021. /* 221 */ "in_op ::= IN",
  118022. /* 222 */ "in_op ::= NOT IN",
  118023. /* 223 */ "expr ::= expr in_op LP exprlist RP",
  118024. /* 224 */ "expr ::= LP select RP",
  118025. /* 225 */ "expr ::= expr in_op LP select RP",
  118026. /* 226 */ "expr ::= expr in_op nm dbnm",
  118027. /* 227 */ "expr ::= EXISTS LP select RP",
  118028. /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
  118029. /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  118030. /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
  118031. /* 231 */ "case_else ::= ELSE expr",
  118032. /* 232 */ "case_else ::=",
  118033. /* 233 */ "case_operand ::= expr",
  118034. /* 234 */ "case_operand ::=",
  118035. /* 235 */ "exprlist ::= nexprlist",
  118036. /* 236 */ "exprlist ::=",
  118037. /* 237 */ "nexprlist ::= nexprlist COMMA expr",
  118038. /* 238 */ "nexprlist ::= expr",
  118039. /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  118040. /* 240 */ "uniqueflag ::= UNIQUE",
  118041. /* 241 */ "uniqueflag ::=",
  118042. /* 242 */ "idxlist_opt ::=",
  118043. /* 243 */ "idxlist_opt ::= LP idxlist RP",
  118044. /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  118045. /* 245 */ "idxlist ::= nm collate sortorder",
  118046. /* 246 */ "collate ::=",
  118047. /* 247 */ "collate ::= COLLATE ID|STRING",
  118048. /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
  118049. /* 249 */ "cmd ::= VACUUM",
  118050. /* 250 */ "cmd ::= VACUUM nm",
  118051. /* 251 */ "cmd ::= PRAGMA nm dbnm",
  118052. /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  118053. /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  118054. /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  118055. /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  118056. /* 256 */ "nmnum ::= plus_num",
  118057. /* 257 */ "nmnum ::= nm",
  118058. /* 258 */ "nmnum ::= ON",
  118059. /* 259 */ "nmnum ::= DELETE",
  118060. /* 260 */ "nmnum ::= DEFAULT",
  118061. /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
  118062. /* 262 */ "plus_num ::= INTEGER|FLOAT",
  118063. /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
  118064. /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  118065. /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  118066. /* 266 */ "trigger_time ::= BEFORE",
  118067. /* 267 */ "trigger_time ::= AFTER",
  118068. /* 268 */ "trigger_time ::= INSTEAD OF",
  118069. /* 269 */ "trigger_time ::=",
  118070. /* 270 */ "trigger_event ::= DELETE|INSERT",
  118071. /* 271 */ "trigger_event ::= UPDATE",
  118072. /* 272 */ "trigger_event ::= UPDATE OF idlist",
  118073. /* 273 */ "foreach_clause ::=",
  118074. /* 274 */ "foreach_clause ::= FOR EACH ROW",
  118075. /* 275 */ "when_clause ::=",
  118076. /* 276 */ "when_clause ::= WHEN expr",
  118077. /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  118078. /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  118079. /* 279 */ "trnm ::= nm",
  118080. /* 280 */ "trnm ::= nm DOT nm",
  118081. /* 281 */ "tridxby ::=",
  118082. /* 282 */ "tridxby ::= INDEXED BY nm",
  118083. /* 283 */ "tridxby ::= NOT INDEXED",
  118084. /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  118085. /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  118086. /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  118087. /* 287 */ "trigger_cmd ::= select",
  118088. /* 288 */ "expr ::= RAISE LP IGNORE RP",
  118089. /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  118090. /* 290 */ "raisetype ::= ROLLBACK",
  118091. /* 291 */ "raisetype ::= ABORT",
  118092. /* 292 */ "raisetype ::= FAIL",
  118093. /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
  118094. /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  118095. /* 295 */ "cmd ::= DETACH database_kw_opt expr",
  118096. /* 296 */ "key_opt ::=",
  118097. /* 297 */ "key_opt ::= KEY expr",
  118098. /* 298 */ "database_kw_opt ::= DATABASE",
  118099. /* 299 */ "database_kw_opt ::=",
  118100. /* 300 */ "cmd ::= REINDEX",
  118101. /* 301 */ "cmd ::= REINDEX nm dbnm",
  118102. /* 302 */ "cmd ::= ANALYZE",
  118103. /* 303 */ "cmd ::= ANALYZE nm dbnm",
  118104. /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  118105. /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  118106. /* 306 */ "add_column_fullname ::= fullname",
  118107. /* 307 */ "kwcolumn_opt ::=",
  118108. /* 308 */ "kwcolumn_opt ::= COLUMNKW",
  118109. /* 309 */ "cmd ::= create_vtab",
  118110. /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
  118111. /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  118112. /* 312 */ "vtabarglist ::= vtabarg",
  118113. /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  118114. /* 314 */ "vtabarg ::=",
  118115. /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
  118116. /* 316 */ "vtabargtoken ::= ANY",
  118117. /* 317 */ "vtabargtoken ::= lp anylist RP",
  118118. /* 318 */ "lp ::= LP",
  118119. /* 319 */ "anylist ::=",
  118120. /* 320 */ "anylist ::= anylist LP anylist RP",
  118121. /* 321 */ "anylist ::= anylist ANY",
  118122. /* 322 */ "with ::=",
  118123. /* 323 */ "with ::= WITH wqlist",
  118124. /* 324 */ "with ::= WITH RECURSIVE wqlist",
  118125. /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
  118126. /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
  118127. };
  118128. #endif /* NDEBUG */
  118129. #if YYSTACKDEPTH<=0
  118130. /*
  118131. ** Try to increase the size of the parser stack.
  118132. */
  118133. static void yyGrowStack(yyParser *p){
  118134. int newSize;
  118135. yyStackEntry *pNew;
  118136. newSize = p->yystksz*2 + 100;
  118137. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  118138. if( pNew ){
  118139. p->yystack = pNew;
  118140. p->yystksz = newSize;
  118141. #ifndef NDEBUG
  118142. if( yyTraceFILE ){
  118143. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  118144. yyTracePrompt, p->yystksz);
  118145. }
  118146. #endif
  118147. }
  118148. }
  118149. #endif
  118150. /*
  118151. ** This function allocates a new parser.
  118152. ** The only argument is a pointer to a function which works like
  118153. ** malloc.
  118154. **
  118155. ** Inputs:
  118156. ** A pointer to the function used to allocate memory.
  118157. **
  118158. ** Outputs:
  118159. ** A pointer to a parser. This pointer is used in subsequent calls
  118160. ** to sqlite3Parser and sqlite3ParserFree.
  118161. */
  118162. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
  118163. yyParser *pParser;
  118164. pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
  118165. if( pParser ){
  118166. pParser->yyidx = -1;
  118167. #ifdef YYTRACKMAXSTACKDEPTH
  118168. pParser->yyidxMax = 0;
  118169. #endif
  118170. #if YYSTACKDEPTH<=0
  118171. pParser->yystack = NULL;
  118172. pParser->yystksz = 0;
  118173. yyGrowStack(pParser);
  118174. #endif
  118175. }
  118176. return pParser;
  118177. }
  118178. /* The following function deletes the value associated with a
  118179. ** symbol. The symbol can be either a terminal or nonterminal.
  118180. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  118181. ** the value.
  118182. */
  118183. static void yy_destructor(
  118184. yyParser *yypParser, /* The parser */
  118185. YYCODETYPE yymajor, /* Type code for object to destroy */
  118186. YYMINORTYPE *yypminor /* The object to be destroyed */
  118187. ){
  118188. sqlite3ParserARG_FETCH;
  118189. switch( yymajor ){
  118190. /* Here is inserted the actions which take place when a
  118191. ** terminal or non-terminal is destroyed. This can happen
  118192. ** when the symbol is popped from the stack during a
  118193. ** reduce or during error processing or when a parser is
  118194. ** being destroyed before it is finished parsing.
  118195. **
  118196. ** Note: during a reduce, the only symbols destroyed are those
  118197. ** which appear on the RHS of the rule, but which are not used
  118198. ** inside the C code.
  118199. */
  118200. case 163: /* select */
  118201. case 195: /* selectnowith */
  118202. case 196: /* oneselect */
  118203. case 207: /* values */
  118204. {
  118205. sqlite3SelectDelete(pParse->db, (yypminor->yy3));
  118206. }
  118207. break;
  118208. case 174: /* term */
  118209. case 175: /* expr */
  118210. {
  118211. sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
  118212. }
  118213. break;
  118214. case 179: /* idxlist_opt */
  118215. case 188: /* idxlist */
  118216. case 200: /* selcollist */
  118217. case 203: /* groupby_opt */
  118218. case 205: /* orderby_opt */
  118219. case 208: /* nexprlist */
  118220. case 209: /* exprlist */
  118221. case 210: /* sclp */
  118222. case 220: /* sortlist */
  118223. case 221: /* setlist */
  118224. case 228: /* case_exprlist */
  118225. {
  118226. sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
  118227. }
  118228. break;
  118229. case 194: /* fullname */
  118230. case 201: /* from */
  118231. case 212: /* seltablist */
  118232. case 213: /* stl_prefix */
  118233. {
  118234. sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
  118235. }
  118236. break;
  118237. case 197: /* with */
  118238. case 252: /* wqlist */
  118239. {
  118240. sqlite3WithDelete(pParse->db, (yypminor->yy59));
  118241. }
  118242. break;
  118243. case 202: /* where_opt */
  118244. case 204: /* having_opt */
  118245. case 216: /* on_opt */
  118246. case 227: /* case_operand */
  118247. case 229: /* case_else */
  118248. case 238: /* when_clause */
  118249. case 243: /* key_opt */
  118250. {
  118251. sqlite3ExprDelete(pParse->db, (yypminor->yy132));
  118252. }
  118253. break;
  118254. case 217: /* using_opt */
  118255. case 219: /* idlist */
  118256. case 223: /* inscollist_opt */
  118257. {
  118258. sqlite3IdListDelete(pParse->db, (yypminor->yy408));
  118259. }
  118260. break;
  118261. case 234: /* trigger_cmd_list */
  118262. case 239: /* trigger_cmd */
  118263. {
  118264. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
  118265. }
  118266. break;
  118267. case 236: /* trigger_event */
  118268. {
  118269. sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
  118270. }
  118271. break;
  118272. default: break; /* If no destructor action specified: do nothing */
  118273. }
  118274. }
  118275. /*
  118276. ** Pop the parser's stack once.
  118277. **
  118278. ** If there is a destructor routine associated with the token which
  118279. ** is popped from the stack, then call it.
  118280. **
  118281. ** Return the major token number for the symbol popped.
  118282. */
  118283. static int yy_pop_parser_stack(yyParser *pParser){
  118284. YYCODETYPE yymajor;
  118285. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  118286. /* There is no mechanism by which the parser stack can be popped below
  118287. ** empty in SQLite. */
  118288. assert( pParser->yyidx>=0 );
  118289. #ifndef NDEBUG
  118290. if( yyTraceFILE && pParser->yyidx>=0 ){
  118291. fprintf(yyTraceFILE,"%sPopping %s\n",
  118292. yyTracePrompt,
  118293. yyTokenName[yytos->major]);
  118294. }
  118295. #endif
  118296. yymajor = yytos->major;
  118297. yy_destructor(pParser, yymajor, &yytos->minor);
  118298. pParser->yyidx--;
  118299. return yymajor;
  118300. }
  118301. /*
  118302. ** Deallocate and destroy a parser. Destructors are all called for
  118303. ** all stack elements before shutting the parser down.
  118304. **
  118305. ** Inputs:
  118306. ** <ul>
  118307. ** <li> A pointer to the parser. This should be a pointer
  118308. ** obtained from sqlite3ParserAlloc.
  118309. ** <li> A pointer to a function used to reclaim memory obtained
  118310. ** from malloc.
  118311. ** </ul>
  118312. */
  118313. SQLITE_PRIVATE void sqlite3ParserFree(
  118314. void *p, /* The parser to be deleted */
  118315. void (*freeProc)(void*) /* Function used to reclaim memory */
  118316. ){
  118317. yyParser *pParser = (yyParser*)p;
  118318. /* In SQLite, we never try to destroy a parser that was not successfully
  118319. ** created in the first place. */
  118320. if( NEVER(pParser==0) ) return;
  118321. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  118322. #if YYSTACKDEPTH<=0
  118323. free(pParser->yystack);
  118324. #endif
  118325. (*freeProc)((void*)pParser);
  118326. }
  118327. /*
  118328. ** Return the peak depth of the stack for a parser.
  118329. */
  118330. #ifdef YYTRACKMAXSTACKDEPTH
  118331. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  118332. yyParser *pParser = (yyParser*)p;
  118333. return pParser->yyidxMax;
  118334. }
  118335. #endif
  118336. /*
  118337. ** Find the appropriate action for a parser given the terminal
  118338. ** look-ahead token iLookAhead.
  118339. **
  118340. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  118341. ** independent of the look-ahead. If it is, return the action, otherwise
  118342. ** return YY_NO_ACTION.
  118343. */
  118344. static int yy_find_shift_action(
  118345. yyParser *pParser, /* The parser */
  118346. YYCODETYPE iLookAhead /* The look-ahead token */
  118347. ){
  118348. int i;
  118349. int stateno = pParser->yystack[pParser->yyidx].stateno;
  118350. if( stateno>YY_SHIFT_COUNT
  118351. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  118352. return yy_default[stateno];
  118353. }
  118354. assert( iLookAhead!=YYNOCODE );
  118355. i += iLookAhead;
  118356. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  118357. if( iLookAhead>0 ){
  118358. #ifdef YYFALLBACK
  118359. YYCODETYPE iFallback; /* Fallback token */
  118360. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  118361. && (iFallback = yyFallback[iLookAhead])!=0 ){
  118362. #ifndef NDEBUG
  118363. if( yyTraceFILE ){
  118364. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  118365. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  118366. }
  118367. #endif
  118368. return yy_find_shift_action(pParser, iFallback);
  118369. }
  118370. #endif
  118371. #ifdef YYWILDCARD
  118372. {
  118373. int j = i - iLookAhead + YYWILDCARD;
  118374. if(
  118375. #if YY_SHIFT_MIN+YYWILDCARD<0
  118376. j>=0 &&
  118377. #endif
  118378. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  118379. j<YY_ACTTAB_COUNT &&
  118380. #endif
  118381. yy_lookahead[j]==YYWILDCARD
  118382. ){
  118383. #ifndef NDEBUG
  118384. if( yyTraceFILE ){
  118385. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  118386. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  118387. }
  118388. #endif /* NDEBUG */
  118389. return yy_action[j];
  118390. }
  118391. }
  118392. #endif /* YYWILDCARD */
  118393. }
  118394. return yy_default[stateno];
  118395. }else{
  118396. return yy_action[i];
  118397. }
  118398. }
  118399. /*
  118400. ** Find the appropriate action for a parser given the non-terminal
  118401. ** look-ahead token iLookAhead.
  118402. **
  118403. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  118404. ** independent of the look-ahead. If it is, return the action, otherwise
  118405. ** return YY_NO_ACTION.
  118406. */
  118407. static int yy_find_reduce_action(
  118408. int stateno, /* Current state number */
  118409. YYCODETYPE iLookAhead /* The look-ahead token */
  118410. ){
  118411. int i;
  118412. #ifdef YYERRORSYMBOL
  118413. if( stateno>YY_REDUCE_COUNT ){
  118414. return yy_default[stateno];
  118415. }
  118416. #else
  118417. assert( stateno<=YY_REDUCE_COUNT );
  118418. #endif
  118419. i = yy_reduce_ofst[stateno];
  118420. assert( i!=YY_REDUCE_USE_DFLT );
  118421. assert( iLookAhead!=YYNOCODE );
  118422. i += iLookAhead;
  118423. #ifdef YYERRORSYMBOL
  118424. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  118425. return yy_default[stateno];
  118426. }
  118427. #else
  118428. assert( i>=0 && i<YY_ACTTAB_COUNT );
  118429. assert( yy_lookahead[i]==iLookAhead );
  118430. #endif
  118431. return yy_action[i];
  118432. }
  118433. /*
  118434. ** The following routine is called if the stack overflows.
  118435. */
  118436. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  118437. sqlite3ParserARG_FETCH;
  118438. yypParser->yyidx--;
  118439. #ifndef NDEBUG
  118440. if( yyTraceFILE ){
  118441. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  118442. }
  118443. #endif
  118444. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  118445. /* Here code is inserted which will execute if the parser
  118446. ** stack every overflows */
  118447. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  118448. sqlite3ErrorMsg(pParse, "parser stack overflow");
  118449. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  118450. }
  118451. /*
  118452. ** Perform a shift action.
  118453. */
  118454. static void yy_shift(
  118455. yyParser *yypParser, /* The parser to be shifted */
  118456. int yyNewState, /* The new state to shift in */
  118457. int yyMajor, /* The major token to shift in */
  118458. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  118459. ){
  118460. yyStackEntry *yytos;
  118461. yypParser->yyidx++;
  118462. #ifdef YYTRACKMAXSTACKDEPTH
  118463. if( yypParser->yyidx>yypParser->yyidxMax ){
  118464. yypParser->yyidxMax = yypParser->yyidx;
  118465. }
  118466. #endif
  118467. #if YYSTACKDEPTH>0
  118468. if( yypParser->yyidx>=YYSTACKDEPTH ){
  118469. yyStackOverflow(yypParser, yypMinor);
  118470. return;
  118471. }
  118472. #else
  118473. if( yypParser->yyidx>=yypParser->yystksz ){
  118474. yyGrowStack(yypParser);
  118475. if( yypParser->yyidx>=yypParser->yystksz ){
  118476. yyStackOverflow(yypParser, yypMinor);
  118477. return;
  118478. }
  118479. }
  118480. #endif
  118481. yytos = &yypParser->yystack[yypParser->yyidx];
  118482. yytos->stateno = (YYACTIONTYPE)yyNewState;
  118483. yytos->major = (YYCODETYPE)yyMajor;
  118484. yytos->minor = *yypMinor;
  118485. #ifndef NDEBUG
  118486. if( yyTraceFILE && yypParser->yyidx>0 ){
  118487. int i;
  118488. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  118489. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  118490. for(i=1; i<=yypParser->yyidx; i++)
  118491. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  118492. fprintf(yyTraceFILE,"\n");
  118493. }
  118494. #endif
  118495. }
  118496. /* The following table contains information about every rule that
  118497. ** is used during the reduce.
  118498. */
  118499. static const struct {
  118500. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  118501. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  118502. } yyRuleInfo[] = {
  118503. { 144, 1 },
  118504. { 145, 2 },
  118505. { 145, 1 },
  118506. { 146, 1 },
  118507. { 146, 3 },
  118508. { 147, 0 },
  118509. { 147, 1 },
  118510. { 147, 3 },
  118511. { 148, 1 },
  118512. { 149, 3 },
  118513. { 151, 0 },
  118514. { 151, 1 },
  118515. { 151, 2 },
  118516. { 150, 0 },
  118517. { 150, 1 },
  118518. { 150, 1 },
  118519. { 150, 1 },
  118520. { 149, 2 },
  118521. { 149, 2 },
  118522. { 149, 2 },
  118523. { 153, 1 },
  118524. { 153, 0 },
  118525. { 149, 2 },
  118526. { 149, 3 },
  118527. { 149, 5 },
  118528. { 149, 2 },
  118529. { 154, 6 },
  118530. { 156, 1 },
  118531. { 158, 0 },
  118532. { 158, 3 },
  118533. { 157, 1 },
  118534. { 157, 0 },
  118535. { 155, 5 },
  118536. { 155, 2 },
  118537. { 162, 0 },
  118538. { 162, 2 },
  118539. { 160, 3 },
  118540. { 160, 1 },
  118541. { 164, 3 },
  118542. { 165, 1 },
  118543. { 152, 1 },
  118544. { 152, 1 },
  118545. { 152, 1 },
  118546. { 166, 0 },
  118547. { 166, 1 },
  118548. { 168, 1 },
  118549. { 168, 4 },
  118550. { 168, 6 },
  118551. { 169, 1 },
  118552. { 169, 2 },
  118553. { 170, 1 },
  118554. { 170, 1 },
  118555. { 167, 2 },
  118556. { 167, 0 },
  118557. { 173, 2 },
  118558. { 173, 2 },
  118559. { 173, 4 },
  118560. { 173, 3 },
  118561. { 173, 3 },
  118562. { 173, 2 },
  118563. { 173, 2 },
  118564. { 173, 3 },
  118565. { 173, 5 },
  118566. { 173, 2 },
  118567. { 173, 4 },
  118568. { 173, 4 },
  118569. { 173, 1 },
  118570. { 173, 2 },
  118571. { 178, 0 },
  118572. { 178, 1 },
  118573. { 180, 0 },
  118574. { 180, 2 },
  118575. { 182, 2 },
  118576. { 182, 3 },
  118577. { 182, 3 },
  118578. { 182, 3 },
  118579. { 183, 2 },
  118580. { 183, 2 },
  118581. { 183, 1 },
  118582. { 183, 1 },
  118583. { 183, 2 },
  118584. { 181, 3 },
  118585. { 181, 2 },
  118586. { 184, 0 },
  118587. { 184, 2 },
  118588. { 184, 2 },
  118589. { 161, 0 },
  118590. { 161, 2 },
  118591. { 185, 3 },
  118592. { 185, 1 },
  118593. { 186, 1 },
  118594. { 186, 0 },
  118595. { 187, 2 },
  118596. { 187, 7 },
  118597. { 187, 5 },
  118598. { 187, 5 },
  118599. { 187, 10 },
  118600. { 189, 0 },
  118601. { 189, 1 },
  118602. { 176, 0 },
  118603. { 176, 3 },
  118604. { 190, 0 },
  118605. { 190, 2 },
  118606. { 191, 1 },
  118607. { 191, 1 },
  118608. { 191, 1 },
  118609. { 149, 4 },
  118610. { 193, 2 },
  118611. { 193, 0 },
  118612. { 149, 8 },
  118613. { 149, 4 },
  118614. { 149, 1 },
  118615. { 163, 2 },
  118616. { 195, 1 },
  118617. { 195, 3 },
  118618. { 198, 1 },
  118619. { 198, 2 },
  118620. { 198, 1 },
  118621. { 196, 9 },
  118622. { 196, 1 },
  118623. { 207, 4 },
  118624. { 207, 5 },
  118625. { 199, 1 },
  118626. { 199, 1 },
  118627. { 199, 0 },
  118628. { 210, 2 },
  118629. { 210, 0 },
  118630. { 200, 3 },
  118631. { 200, 2 },
  118632. { 200, 4 },
  118633. { 211, 2 },
  118634. { 211, 1 },
  118635. { 211, 0 },
  118636. { 201, 0 },
  118637. { 201, 2 },
  118638. { 213, 2 },
  118639. { 213, 0 },
  118640. { 212, 7 },
  118641. { 212, 7 },
  118642. { 212, 7 },
  118643. { 159, 0 },
  118644. { 159, 2 },
  118645. { 194, 2 },
  118646. { 214, 1 },
  118647. { 214, 2 },
  118648. { 214, 3 },
  118649. { 214, 4 },
  118650. { 216, 2 },
  118651. { 216, 0 },
  118652. { 215, 0 },
  118653. { 215, 3 },
  118654. { 215, 2 },
  118655. { 217, 4 },
  118656. { 217, 0 },
  118657. { 205, 0 },
  118658. { 205, 3 },
  118659. { 220, 4 },
  118660. { 220, 2 },
  118661. { 177, 1 },
  118662. { 177, 1 },
  118663. { 177, 0 },
  118664. { 203, 0 },
  118665. { 203, 3 },
  118666. { 204, 0 },
  118667. { 204, 2 },
  118668. { 206, 0 },
  118669. { 206, 2 },
  118670. { 206, 4 },
  118671. { 206, 4 },
  118672. { 149, 6 },
  118673. { 202, 0 },
  118674. { 202, 2 },
  118675. { 149, 8 },
  118676. { 221, 5 },
  118677. { 221, 3 },
  118678. { 149, 6 },
  118679. { 149, 7 },
  118680. { 222, 2 },
  118681. { 222, 1 },
  118682. { 223, 0 },
  118683. { 223, 3 },
  118684. { 219, 3 },
  118685. { 219, 1 },
  118686. { 175, 1 },
  118687. { 175, 3 },
  118688. { 174, 1 },
  118689. { 175, 1 },
  118690. { 175, 1 },
  118691. { 175, 3 },
  118692. { 175, 5 },
  118693. { 174, 1 },
  118694. { 174, 1 },
  118695. { 175, 1 },
  118696. { 175, 3 },
  118697. { 175, 6 },
  118698. { 175, 5 },
  118699. { 175, 4 },
  118700. { 174, 1 },
  118701. { 175, 3 },
  118702. { 175, 3 },
  118703. { 175, 3 },
  118704. { 175, 3 },
  118705. { 175, 3 },
  118706. { 175, 3 },
  118707. { 175, 3 },
  118708. { 175, 3 },
  118709. { 224, 1 },
  118710. { 224, 2 },
  118711. { 175, 3 },
  118712. { 175, 5 },
  118713. { 175, 2 },
  118714. { 175, 3 },
  118715. { 175, 3 },
  118716. { 175, 4 },
  118717. { 175, 2 },
  118718. { 175, 2 },
  118719. { 175, 2 },
  118720. { 175, 2 },
  118721. { 225, 1 },
  118722. { 225, 2 },
  118723. { 175, 5 },
  118724. { 226, 1 },
  118725. { 226, 2 },
  118726. { 175, 5 },
  118727. { 175, 3 },
  118728. { 175, 5 },
  118729. { 175, 4 },
  118730. { 175, 4 },
  118731. { 175, 5 },
  118732. { 228, 5 },
  118733. { 228, 4 },
  118734. { 229, 2 },
  118735. { 229, 0 },
  118736. { 227, 1 },
  118737. { 227, 0 },
  118738. { 209, 1 },
  118739. { 209, 0 },
  118740. { 208, 3 },
  118741. { 208, 1 },
  118742. { 149, 12 },
  118743. { 230, 1 },
  118744. { 230, 0 },
  118745. { 179, 0 },
  118746. { 179, 3 },
  118747. { 188, 5 },
  118748. { 188, 3 },
  118749. { 231, 0 },
  118750. { 231, 2 },
  118751. { 149, 4 },
  118752. { 149, 1 },
  118753. { 149, 2 },
  118754. { 149, 3 },
  118755. { 149, 5 },
  118756. { 149, 6 },
  118757. { 149, 5 },
  118758. { 149, 6 },
  118759. { 232, 1 },
  118760. { 232, 1 },
  118761. { 232, 1 },
  118762. { 232, 1 },
  118763. { 232, 1 },
  118764. { 171, 2 },
  118765. { 171, 1 },
  118766. { 172, 2 },
  118767. { 149, 5 },
  118768. { 233, 11 },
  118769. { 235, 1 },
  118770. { 235, 1 },
  118771. { 235, 2 },
  118772. { 235, 0 },
  118773. { 236, 1 },
  118774. { 236, 1 },
  118775. { 236, 3 },
  118776. { 237, 0 },
  118777. { 237, 3 },
  118778. { 238, 0 },
  118779. { 238, 2 },
  118780. { 234, 3 },
  118781. { 234, 2 },
  118782. { 240, 1 },
  118783. { 240, 3 },
  118784. { 241, 0 },
  118785. { 241, 3 },
  118786. { 241, 2 },
  118787. { 239, 7 },
  118788. { 239, 5 },
  118789. { 239, 5 },
  118790. { 239, 1 },
  118791. { 175, 4 },
  118792. { 175, 6 },
  118793. { 192, 1 },
  118794. { 192, 1 },
  118795. { 192, 1 },
  118796. { 149, 4 },
  118797. { 149, 6 },
  118798. { 149, 3 },
  118799. { 243, 0 },
  118800. { 243, 2 },
  118801. { 242, 1 },
  118802. { 242, 0 },
  118803. { 149, 1 },
  118804. { 149, 3 },
  118805. { 149, 1 },
  118806. { 149, 3 },
  118807. { 149, 6 },
  118808. { 149, 6 },
  118809. { 244, 1 },
  118810. { 245, 0 },
  118811. { 245, 1 },
  118812. { 149, 1 },
  118813. { 149, 4 },
  118814. { 246, 8 },
  118815. { 247, 1 },
  118816. { 247, 3 },
  118817. { 248, 0 },
  118818. { 248, 2 },
  118819. { 249, 1 },
  118820. { 249, 3 },
  118821. { 250, 1 },
  118822. { 251, 0 },
  118823. { 251, 4 },
  118824. { 251, 2 },
  118825. { 197, 0 },
  118826. { 197, 2 },
  118827. { 197, 3 },
  118828. { 252, 6 },
  118829. { 252, 8 },
  118830. };
  118831. static void yy_accept(yyParser*); /* Forward Declaration */
  118832. /*
  118833. ** Perform a reduce action and the shift that must immediately
  118834. ** follow the reduce.
  118835. */
  118836. static void yy_reduce(
  118837. yyParser *yypParser, /* The parser */
  118838. int yyruleno /* Number of the rule by which to reduce */
  118839. ){
  118840. int yygoto; /* The next state */
  118841. int yyact; /* The next action */
  118842. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  118843. yyStackEntry *yymsp; /* The top of the parser's stack */
  118844. int yysize; /* Amount to pop the stack */
  118845. sqlite3ParserARG_FETCH;
  118846. yymsp = &yypParser->yystack[yypParser->yyidx];
  118847. #ifndef NDEBUG
  118848. if( yyTraceFILE && yyruleno>=0
  118849. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  118850. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  118851. yyRuleName[yyruleno]);
  118852. }
  118853. #endif /* NDEBUG */
  118854. /* Silence complaints from purify about yygotominor being uninitialized
  118855. ** in some cases when it is copied into the stack after the following
  118856. ** switch. yygotominor is uninitialized when a rule reduces that does
  118857. ** not set the value of its left-hand side nonterminal. Leaving the
  118858. ** value of the nonterminal uninitialized is utterly harmless as long
  118859. ** as the value is never used. So really the only thing this code
  118860. ** accomplishes is to quieten purify.
  118861. **
  118862. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  118863. ** without this code, their parser segfaults. I'm not sure what there
  118864. ** parser is doing to make this happen. This is the second bug report
  118865. ** from wireshark this week. Clearly they are stressing Lemon in ways
  118866. ** that it has not been previously stressed... (SQLite ticket #2172)
  118867. */
  118868. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  118869. yygotominor = yyzerominor;
  118870. switch( yyruleno ){
  118871. /* Beginning here are the reduction cases. A typical example
  118872. ** follows:
  118873. ** case 0:
  118874. ** #line <lineno> <grammarfile>
  118875. ** { ... } // User supplied code
  118876. ** #line <lineno> <thisfile>
  118877. ** break;
  118878. */
  118879. case 5: /* explain ::= */
  118880. { sqlite3BeginParse(pParse, 0); }
  118881. break;
  118882. case 6: /* explain ::= EXPLAIN */
  118883. { sqlite3BeginParse(pParse, 1); }
  118884. break;
  118885. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  118886. { sqlite3BeginParse(pParse, 2); }
  118887. break;
  118888. case 8: /* cmdx ::= cmd */
  118889. { sqlite3FinishCoding(pParse); }
  118890. break;
  118891. case 9: /* cmd ::= BEGIN transtype trans_opt */
  118892. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
  118893. break;
  118894. case 13: /* transtype ::= */
  118895. {yygotominor.yy328 = TK_DEFERRED;}
  118896. break;
  118897. case 14: /* transtype ::= DEFERRED */
  118898. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  118899. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  118900. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  118901. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  118902. {yygotominor.yy328 = yymsp[0].major;}
  118903. break;
  118904. case 17: /* cmd ::= COMMIT trans_opt */
  118905. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  118906. {sqlite3CommitTransaction(pParse);}
  118907. break;
  118908. case 19: /* cmd ::= ROLLBACK trans_opt */
  118909. {sqlite3RollbackTransaction(pParse);}
  118910. break;
  118911. case 22: /* cmd ::= SAVEPOINT nm */
  118912. {
  118913. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  118914. }
  118915. break;
  118916. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  118917. {
  118918. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  118919. }
  118920. break;
  118921. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  118922. {
  118923. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  118924. }
  118925. break;
  118926. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  118927. {
  118928. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
  118929. }
  118930. break;
  118931. case 27: /* createkw ::= CREATE */
  118932. {
  118933. pParse->db->lookaside.bEnabled = 0;
  118934. yygotominor.yy0 = yymsp[0].minor.yy0;
  118935. }
  118936. break;
  118937. case 28: /* ifnotexists ::= */
  118938. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  118939. case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
  118940. case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
  118941. case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
  118942. case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
  118943. case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
  118944. case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
  118945. case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
  118946. case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
  118947. {yygotominor.yy328 = 0;}
  118948. break;
  118949. case 29: /* ifnotexists ::= IF NOT EXISTS */
  118950. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  118951. case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
  118952. case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
  118953. case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
  118954. case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
  118955. case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
  118956. {yygotominor.yy328 = 1;}
  118957. break;
  118958. case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  118959. {
  118960. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
  118961. }
  118962. break;
  118963. case 33: /* create_table_args ::= AS select */
  118964. {
  118965. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
  118966. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  118967. }
  118968. break;
  118969. case 34: /* table_options ::= */
  118970. {yygotominor.yy186 = 0;}
  118971. break;
  118972. case 35: /* table_options ::= WITHOUT nm */
  118973. {
  118974. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  118975. yygotominor.yy186 = TF_WithoutRowid | TF_NoVisibleRowid;
  118976. }else{
  118977. yygotominor.yy186 = 0;
  118978. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  118979. }
  118980. }
  118981. break;
  118982. case 38: /* column ::= columnid type carglist */
  118983. {
  118984. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  118985. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  118986. }
  118987. break;
  118988. case 39: /* columnid ::= nm */
  118989. {
  118990. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  118991. yygotominor.yy0 = yymsp[0].minor.yy0;
  118992. pParse->constraintName.n = 0;
  118993. }
  118994. break;
  118995. case 40: /* nm ::= ID|INDEXED */
  118996. case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
  118997. case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
  118998. case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
  118999. case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
  119000. case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
  119001. case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
  119002. case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
  119003. case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
  119004. case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
  119005. case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
  119006. case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
  119007. case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
  119008. case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
  119009. case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
  119010. case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
  119011. case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
  119012. case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
  119013. case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
  119014. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  119015. break;
  119016. case 44: /* type ::= typetoken */
  119017. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  119018. break;
  119019. case 46: /* typetoken ::= typename LP signed RP */
  119020. {
  119021. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  119022. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  119023. }
  119024. break;
  119025. case 47: /* typetoken ::= typename LP signed COMMA signed RP */
  119026. {
  119027. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  119028. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  119029. }
  119030. break;
  119031. case 49: /* typename ::= typename ID|STRING */
  119032. {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);}
  119033. break;
  119034. case 54: /* ccons ::= CONSTRAINT nm */
  119035. case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
  119036. {pParse->constraintName = yymsp[0].minor.yy0;}
  119037. break;
  119038. case 55: /* ccons ::= DEFAULT term */
  119039. case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
  119040. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
  119041. break;
  119042. case 56: /* ccons ::= DEFAULT LP expr RP */
  119043. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
  119044. break;
  119045. case 58: /* ccons ::= DEFAULT MINUS term */
  119046. {
  119047. ExprSpan v;
  119048. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
  119049. v.zStart = yymsp[-1].minor.yy0.z;
  119050. v.zEnd = yymsp[0].minor.yy346.zEnd;
  119051. sqlite3AddDefaultValue(pParse,&v);
  119052. }
  119053. break;
  119054. case 59: /* ccons ::= DEFAULT ID|INDEXED */
  119055. {
  119056. ExprSpan v;
  119057. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  119058. sqlite3AddDefaultValue(pParse,&v);
  119059. }
  119060. break;
  119061. case 61: /* ccons ::= NOT NULL onconf */
  119062. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
  119063. break;
  119064. case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  119065. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
  119066. break;
  119067. case 63: /* ccons ::= UNIQUE onconf */
  119068. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
  119069. break;
  119070. case 64: /* ccons ::= CHECK LP expr RP */
  119071. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
  119072. break;
  119073. case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  119074. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
  119075. break;
  119076. case 66: /* ccons ::= defer_subclause */
  119077. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
  119078. break;
  119079. case 67: /* ccons ::= COLLATE ID|STRING */
  119080. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  119081. break;
  119082. case 70: /* refargs ::= */
  119083. { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
  119084. break;
  119085. case 71: /* refargs ::= refargs refarg */
  119086. { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
  119087. break;
  119088. case 72: /* refarg ::= MATCH nm */
  119089. case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
  119090. { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
  119091. break;
  119092. case 74: /* refarg ::= ON DELETE refact */
  119093. { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
  119094. break;
  119095. case 75: /* refarg ::= ON UPDATE refact */
  119096. { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
  119097. break;
  119098. case 76: /* refact ::= SET NULL */
  119099. { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
  119100. break;
  119101. case 77: /* refact ::= SET DEFAULT */
  119102. { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
  119103. break;
  119104. case 78: /* refact ::= CASCADE */
  119105. { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
  119106. break;
  119107. case 79: /* refact ::= RESTRICT */
  119108. { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
  119109. break;
  119110. case 80: /* refact ::= NO ACTION */
  119111. { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
  119112. break;
  119113. case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  119114. case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
  119115. case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
  119116. case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
  119117. {yygotominor.yy328 = yymsp[0].minor.yy328;}
  119118. break;
  119119. case 86: /* conslist_opt ::= */
  119120. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  119121. break;
  119122. case 87: /* conslist_opt ::= COMMA conslist */
  119123. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  119124. break;
  119125. case 90: /* tconscomma ::= COMMA */
  119126. {pParse->constraintName.n = 0;}
  119127. break;
  119128. case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  119129. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
  119130. break;
  119131. case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
  119132. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
  119133. break;
  119134. case 95: /* tcons ::= CHECK LP expr RP onconf */
  119135. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
  119136. break;
  119137. case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  119138. {
  119139. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
  119140. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
  119141. }
  119142. break;
  119143. case 99: /* onconf ::= */
  119144. {yygotominor.yy328 = OE_Default;}
  119145. break;
  119146. case 101: /* orconf ::= */
  119147. {yygotominor.yy186 = OE_Default;}
  119148. break;
  119149. case 102: /* orconf ::= OR resolvetype */
  119150. {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
  119151. break;
  119152. case 104: /* resolvetype ::= IGNORE */
  119153. {yygotominor.yy328 = OE_Ignore;}
  119154. break;
  119155. case 105: /* resolvetype ::= REPLACE */
  119156. {yygotominor.yy328 = OE_Replace;}
  119157. break;
  119158. case 106: /* cmd ::= DROP TABLE ifexists fullname */
  119159. {
  119160. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
  119161. }
  119162. break;
  119163. case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  119164. {
  119165. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
  119166. }
  119167. break;
  119168. case 110: /* cmd ::= DROP VIEW ifexists fullname */
  119169. {
  119170. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
  119171. }
  119172. break;
  119173. case 111: /* cmd ::= select */
  119174. {
  119175. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  119176. sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
  119177. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  119178. }
  119179. break;
  119180. case 112: /* select ::= with selectnowith */
  119181. {
  119182. Select *p = yymsp[0].minor.yy3;
  119183. if( p ){
  119184. p->pWith = yymsp[-1].minor.yy59;
  119185. parserDoubleLinkSelect(pParse, p);
  119186. }else{
  119187. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
  119188. }
  119189. yygotominor.yy3 = p;
  119190. }
  119191. break;
  119192. case 113: /* selectnowith ::= oneselect */
  119193. case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
  119194. {yygotominor.yy3 = yymsp[0].minor.yy3;}
  119195. break;
  119196. case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
  119197. {
  119198. Select *pRhs = yymsp[0].minor.yy3;
  119199. Select *pLhs = yymsp[-2].minor.yy3;
  119200. if( pRhs && pRhs->pPrior ){
  119201. SrcList *pFrom;
  119202. Token x;
  119203. x.n = 0;
  119204. parserDoubleLinkSelect(pParse, pRhs);
  119205. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  119206. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  119207. }
  119208. if( pRhs ){
  119209. pRhs->op = (u8)yymsp[-1].minor.yy328;
  119210. pRhs->pPrior = pLhs;
  119211. if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
  119212. pRhs->selFlags &= ~SF_MultiValue;
  119213. if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
  119214. }else{
  119215. sqlite3SelectDelete(pParse->db, pLhs);
  119216. }
  119217. yygotominor.yy3 = pRhs;
  119218. }
  119219. break;
  119220. case 116: /* multiselect_op ::= UNION ALL */
  119221. {yygotominor.yy328 = TK_ALL;}
  119222. break;
  119223. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  119224. {
  119225. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
  119226. #if SELECTTRACE_ENABLED
  119227. /* Populate the Select.zSelName[] string that is used to help with
  119228. ** query planner debugging, to differentiate between multiple Select
  119229. ** objects in a complex query.
  119230. **
  119231. ** If the SELECT keyword is immediately followed by a C-style comment
  119232. ** then extract the first few alphanumeric characters from within that
  119233. ** comment to be the zSelName value. Otherwise, the label is #N where
  119234. ** is an integer that is incremented with each SELECT statement seen.
  119235. */
  119236. if( yygotominor.yy3!=0 ){
  119237. const char *z = yymsp[-8].minor.yy0.z+6;
  119238. int i;
  119239. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
  119240. ++pParse->nSelect);
  119241. while( z[0]==' ' ) z++;
  119242. if( z[0]=='/' && z[1]=='*' ){
  119243. z += 2;
  119244. while( z[0]==' ' ) z++;
  119245. for(i=0; sqlite3Isalnum(z[i]); i++){}
  119246. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
  119247. }
  119248. }
  119249. #endif /* SELECTRACE_ENABLED */
  119250. }
  119251. break;
  119252. case 120: /* values ::= VALUES LP nexprlist RP */
  119253. {
  119254. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
  119255. }
  119256. break;
  119257. case 121: /* values ::= values COMMA LP exprlist RP */
  119258. {
  119259. Select *pRight, *pLeft = yymsp[-4].minor.yy3;
  119260. pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
  119261. if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
  119262. if( pRight ){
  119263. pRight->op = TK_ALL;
  119264. pLeft = yymsp[-4].minor.yy3;
  119265. pRight->pPrior = pLeft;
  119266. yygotominor.yy3 = pRight;
  119267. }else{
  119268. yygotominor.yy3 = pLeft;
  119269. }
  119270. }
  119271. break;
  119272. case 122: /* distinct ::= DISTINCT */
  119273. {yygotominor.yy381 = SF_Distinct;}
  119274. break;
  119275. case 123: /* distinct ::= ALL */
  119276. {yygotominor.yy381 = SF_All;}
  119277. break;
  119278. case 124: /* distinct ::= */
  119279. {yygotominor.yy381 = 0;}
  119280. break;
  119281. case 125: /* sclp ::= selcollist COMMA */
  119282. case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
  119283. {yygotominor.yy14 = yymsp[-1].minor.yy14;}
  119284. break;
  119285. case 126: /* sclp ::= */
  119286. case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
  119287. case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
  119288. case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
  119289. case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
  119290. {yygotominor.yy14 = 0;}
  119291. break;
  119292. case 127: /* selcollist ::= sclp expr as */
  119293. {
  119294. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
  119295. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
  119296. sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
  119297. }
  119298. break;
  119299. case 128: /* selcollist ::= sclp STAR */
  119300. {
  119301. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  119302. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
  119303. }
  119304. break;
  119305. case 129: /* selcollist ::= sclp nm DOT STAR */
  119306. {
  119307. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  119308. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  119309. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  119310. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
  119311. }
  119312. break;
  119313. case 132: /* as ::= */
  119314. {yygotominor.yy0.n = 0;}
  119315. break;
  119316. case 133: /* from ::= */
  119317. {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
  119318. break;
  119319. case 134: /* from ::= FROM seltablist */
  119320. {
  119321. yygotominor.yy65 = yymsp[0].minor.yy65;
  119322. sqlite3SrcListShiftJoinType(yygotominor.yy65);
  119323. }
  119324. break;
  119325. case 135: /* stl_prefix ::= seltablist joinop */
  119326. {
  119327. yygotominor.yy65 = yymsp[-1].minor.yy65;
  119328. if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
  119329. }
  119330. break;
  119331. case 136: /* stl_prefix ::= */
  119332. {yygotominor.yy65 = 0;}
  119333. break;
  119334. case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  119335. {
  119336. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  119337. sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
  119338. }
  119339. break;
  119340. case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  119341. {
  119342. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  119343. }
  119344. break;
  119345. case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  119346. {
  119347. if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
  119348. yygotominor.yy65 = yymsp[-4].minor.yy65;
  119349. }else if( yymsp[-4].minor.yy65->nSrc==1 ){
  119350. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  119351. if( yygotominor.yy65 ){
  119352. struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
  119353. struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
  119354. pNew->zName = pOld->zName;
  119355. pNew->zDatabase = pOld->zDatabase;
  119356. pNew->pSelect = pOld->pSelect;
  119357. pOld->zName = pOld->zDatabase = 0;
  119358. pOld->pSelect = 0;
  119359. }
  119360. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
  119361. }else{
  119362. Select *pSubquery;
  119363. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
  119364. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
  119365. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  119366. }
  119367. }
  119368. break;
  119369. case 140: /* dbnm ::= */
  119370. case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
  119371. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  119372. break;
  119373. case 142: /* fullname ::= nm dbnm */
  119374. {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  119375. break;
  119376. case 143: /* joinop ::= COMMA|JOIN */
  119377. { yygotominor.yy328 = JT_INNER; }
  119378. break;
  119379. case 144: /* joinop ::= JOIN_KW JOIN */
  119380. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  119381. break;
  119382. case 145: /* joinop ::= JOIN_KW nm JOIN */
  119383. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  119384. break;
  119385. case 146: /* joinop ::= JOIN_KW nm nm JOIN */
  119386. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  119387. break;
  119388. case 147: /* on_opt ::= ON expr */
  119389. case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
  119390. case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
  119391. case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
  119392. case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
  119393. {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
  119394. break;
  119395. case 148: /* on_opt ::= */
  119396. case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
  119397. case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
  119398. case 232: /* case_else ::= */ yytestcase(yyruleno==232);
  119399. case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
  119400. {yygotominor.yy132 = 0;}
  119401. break;
  119402. case 151: /* indexed_opt ::= NOT INDEXED */
  119403. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  119404. break;
  119405. case 152: /* using_opt ::= USING LP idlist RP */
  119406. case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
  119407. {yygotominor.yy408 = yymsp[-1].minor.yy408;}
  119408. break;
  119409. case 153: /* using_opt ::= */
  119410. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  119411. {yygotominor.yy408 = 0;}
  119412. break;
  119413. case 155: /* orderby_opt ::= ORDER BY sortlist */
  119414. case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
  119415. case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
  119416. {yygotominor.yy14 = yymsp[0].minor.yy14;}
  119417. break;
  119418. case 156: /* sortlist ::= sortlist COMMA expr sortorder */
  119419. {
  119420. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
  119421. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  119422. }
  119423. break;
  119424. case 157: /* sortlist ::= expr sortorder */
  119425. {
  119426. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
  119427. if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
  119428. }
  119429. break;
  119430. case 158: /* sortorder ::= ASC */
  119431. case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
  119432. {yygotominor.yy328 = SQLITE_SO_ASC;}
  119433. break;
  119434. case 159: /* sortorder ::= DESC */
  119435. {yygotominor.yy328 = SQLITE_SO_DESC;}
  119436. break;
  119437. case 165: /* limit_opt ::= */
  119438. {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
  119439. break;
  119440. case 166: /* limit_opt ::= LIMIT expr */
  119441. {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
  119442. break;
  119443. case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
  119444. {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
  119445. break;
  119446. case 168: /* limit_opt ::= LIMIT expr COMMA expr */
  119447. {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
  119448. break;
  119449. case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  119450. {
  119451. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  119452. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
  119453. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
  119454. }
  119455. break;
  119456. case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  119457. {
  119458. sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
  119459. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
  119460. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
  119461. sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
  119462. }
  119463. break;
  119464. case 173: /* setlist ::= setlist COMMA nm EQ expr */
  119465. {
  119466. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
  119467. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  119468. }
  119469. break;
  119470. case 174: /* setlist ::= nm EQ expr */
  119471. {
  119472. yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
  119473. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  119474. }
  119475. break;
  119476. case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
  119477. {
  119478. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  119479. sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
  119480. }
  119481. break;
  119482. case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  119483. {
  119484. sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
  119485. sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
  119486. }
  119487. break;
  119488. case 177: /* insert_cmd ::= INSERT orconf */
  119489. {yygotominor.yy186 = yymsp[0].minor.yy186;}
  119490. break;
  119491. case 178: /* insert_cmd ::= REPLACE */
  119492. {yygotominor.yy186 = OE_Replace;}
  119493. break;
  119494. case 181: /* idlist ::= idlist COMMA nm */
  119495. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
  119496. break;
  119497. case 182: /* idlist ::= nm */
  119498. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  119499. break;
  119500. case 183: /* expr ::= term */
  119501. {yygotominor.yy346 = yymsp[0].minor.yy346;}
  119502. break;
  119503. case 184: /* expr ::= LP expr RP */
  119504. {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  119505. break;
  119506. case 185: /* term ::= NULL */
  119507. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  119508. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  119509. {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  119510. break;
  119511. case 186: /* expr ::= ID|INDEXED */
  119512. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  119513. {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
  119514. break;
  119515. case 188: /* expr ::= nm DOT nm */
  119516. {
  119517. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  119518. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  119519. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  119520. spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  119521. }
  119522. break;
  119523. case 189: /* expr ::= nm DOT nm DOT nm */
  119524. {
  119525. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  119526. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  119527. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  119528. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  119529. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  119530. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  119531. }
  119532. break;
  119533. case 192: /* expr ::= VARIABLE */
  119534. {
  119535. if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
  119536. /* When doing a nested parse, one can include terms in an expression
  119537. ** that look like this: #1 #2 ... These terms refer to registers
  119538. ** in the virtual machine. #N is the N-th register. */
  119539. if( pParse->nested==0 ){
  119540. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  119541. yygotominor.yy346.pExpr = 0;
  119542. }else{
  119543. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  119544. if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
  119545. }
  119546. }else{
  119547. spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  119548. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
  119549. }
  119550. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  119551. }
  119552. break;
  119553. case 193: /* expr ::= expr COLLATE ID|STRING */
  119554. {
  119555. yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
  119556. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  119557. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119558. }
  119559. break;
  119560. case 194: /* expr ::= CAST LP expr AS typetoken RP */
  119561. {
  119562. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
  119563. spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  119564. }
  119565. break;
  119566. case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  119567. {
  119568. if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  119569. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  119570. }
  119571. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
  119572. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  119573. if( yymsp[-2].minor.yy381==SF_Distinct && yygotominor.yy346.pExpr ){
  119574. yygotominor.yy346.pExpr->flags |= EP_Distinct;
  119575. }
  119576. }
  119577. break;
  119578. case 196: /* expr ::= ID|INDEXED LP STAR RP */
  119579. {
  119580. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  119581. spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  119582. }
  119583. break;
  119584. case 197: /* term ::= CTIME_KW */
  119585. {
  119586. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  119587. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  119588. }
  119589. break;
  119590. case 198: /* expr ::= expr AND expr */
  119591. case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
  119592. case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
  119593. case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
  119594. case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
  119595. case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
  119596. case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
  119597. case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
  119598. {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
  119599. break;
  119600. case 206: /* likeop ::= LIKE_KW|MATCH */
  119601. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
  119602. break;
  119603. case 207: /* likeop ::= NOT LIKE_KW|MATCH */
  119604. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
  119605. break;
  119606. case 208: /* expr ::= expr likeop expr */
  119607. {
  119608. ExprList *pList;
  119609. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
  119610. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
  119611. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
  119612. if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  119613. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  119614. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  119615. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  119616. }
  119617. break;
  119618. case 209: /* expr ::= expr likeop expr ESCAPE expr */
  119619. {
  119620. ExprList *pList;
  119621. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  119622. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
  119623. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  119624. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
  119625. if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  119626. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  119627. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  119628. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  119629. }
  119630. break;
  119631. case 210: /* expr ::= expr ISNULL|NOTNULL */
  119632. {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
  119633. break;
  119634. case 211: /* expr ::= expr NOT NULL */
  119635. {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
  119636. break;
  119637. case 212: /* expr ::= expr IS expr */
  119638. {
  119639. spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
  119640. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
  119641. }
  119642. break;
  119643. case 213: /* expr ::= expr IS NOT expr */
  119644. {
  119645. spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
  119646. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
  119647. }
  119648. break;
  119649. case 214: /* expr ::= NOT expr */
  119650. case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
  119651. {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  119652. break;
  119653. case 216: /* expr ::= MINUS expr */
  119654. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  119655. break;
  119656. case 217: /* expr ::= PLUS expr */
  119657. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  119658. break;
  119659. case 220: /* expr ::= expr between_op expr AND expr */
  119660. {
  119661. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  119662. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  119663. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  119664. if( yygotominor.yy346.pExpr ){
  119665. yygotominor.yy346.pExpr->x.pList = pList;
  119666. }else{
  119667. sqlite3ExprListDelete(pParse->db, pList);
  119668. }
  119669. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  119670. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  119671. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  119672. }
  119673. break;
  119674. case 223: /* expr ::= expr in_op LP exprlist RP */
  119675. {
  119676. if( yymsp[-1].minor.yy14==0 ){
  119677. /* Expressions of the form
  119678. **
  119679. ** expr1 IN ()
  119680. ** expr1 NOT IN ()
  119681. **
  119682. ** simplify to constants 0 (false) and 1 (true), respectively,
  119683. ** regardless of the value of expr1.
  119684. */
  119685. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
  119686. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
  119687. }else if( yymsp[-1].minor.yy14->nExpr==1 ){
  119688. /* Expressions of the form:
  119689. **
  119690. ** expr1 IN (?1)
  119691. ** expr1 NOT IN (?2)
  119692. **
  119693. ** with exactly one value on the RHS can be simplified to something
  119694. ** like this:
  119695. **
  119696. ** expr1 == ?1
  119697. ** expr1 <> ?2
  119698. **
  119699. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  119700. ** so that it may not contribute to the computation of comparison
  119701. ** affinity or the collating sequence to use for comparison. Otherwise,
  119702. ** the semantics would be subtly different from IN or NOT IN.
  119703. */
  119704. Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
  119705. yymsp[-1].minor.yy14->a[0].pExpr = 0;
  119706. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  119707. /* pRHS cannot be NULL because a malloc error would have been detected
  119708. ** before now and control would have never reached this point */
  119709. if( ALWAYS(pRHS) ){
  119710. pRHS->flags &= ~EP_Collate;
  119711. pRHS->flags |= EP_Generic;
  119712. }
  119713. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
  119714. }else{
  119715. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  119716. if( yygotominor.yy346.pExpr ){
  119717. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
  119718. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  119719. }else{
  119720. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  119721. }
  119722. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  119723. }
  119724. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  119725. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119726. }
  119727. break;
  119728. case 224: /* expr ::= LP select RP */
  119729. {
  119730. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  119731. if( yygotominor.yy346.pExpr ){
  119732. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  119733. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  119734. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  119735. }else{
  119736. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  119737. }
  119738. yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
  119739. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119740. }
  119741. break;
  119742. case 225: /* expr ::= expr in_op LP select RP */
  119743. {
  119744. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  119745. if( yygotominor.yy346.pExpr ){
  119746. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  119747. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  119748. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  119749. }else{
  119750. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  119751. }
  119752. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  119753. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  119754. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119755. }
  119756. break;
  119757. case 226: /* expr ::= expr in_op nm dbnm */
  119758. {
  119759. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  119760. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
  119761. if( yygotominor.yy346.pExpr ){
  119762. yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  119763. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
  119764. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  119765. }else{
  119766. sqlite3SrcListDelete(pParse->db, pSrc);
  119767. }
  119768. if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  119769. yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
  119770. yygotominor.yy346.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
  119771. }
  119772. break;
  119773. case 227: /* expr ::= EXISTS LP select RP */
  119774. {
  119775. Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  119776. if( p ){
  119777. p->x.pSelect = yymsp[-1].minor.yy3;
  119778. ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
  119779. sqlite3ExprSetHeightAndFlags(pParse, p);
  119780. }else{
  119781. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  119782. }
  119783. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  119784. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119785. }
  119786. break;
  119787. case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
  119788. {
  119789. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
  119790. if( yygotominor.yy346.pExpr ){
  119791. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
  119792. sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
  119793. }else{
  119794. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
  119795. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
  119796. }
  119797. yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
  119798. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119799. }
  119800. break;
  119801. case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  119802. {
  119803. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
  119804. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  119805. }
  119806. break;
  119807. case 230: /* case_exprlist ::= WHEN expr THEN expr */
  119808. {
  119809. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  119810. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  119811. }
  119812. break;
  119813. case 237: /* nexprlist ::= nexprlist COMMA expr */
  119814. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
  119815. break;
  119816. case 238: /* nexprlist ::= expr */
  119817. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
  119818. break;
  119819. case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  119820. {
  119821. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  119822. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
  119823. &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
  119824. }
  119825. break;
  119826. case 240: /* uniqueflag ::= UNIQUE */
  119827. case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
  119828. {yygotominor.yy328 = OE_Abort;}
  119829. break;
  119830. case 241: /* uniqueflag ::= */
  119831. {yygotominor.yy328 = OE_None;}
  119832. break;
  119833. case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
  119834. {
  119835. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
  119836. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
  119837. sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
  119838. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  119839. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  119840. }
  119841. break;
  119842. case 245: /* idxlist ::= nm collate sortorder */
  119843. {
  119844. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
  119845. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
  119846. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  119847. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  119848. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  119849. }
  119850. break;
  119851. case 246: /* collate ::= */
  119852. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  119853. break;
  119854. case 248: /* cmd ::= DROP INDEX ifexists fullname */
  119855. {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
  119856. break;
  119857. case 249: /* cmd ::= VACUUM */
  119858. case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
  119859. {sqlite3Vacuum(pParse);}
  119860. break;
  119861. case 251: /* cmd ::= PRAGMA nm dbnm */
  119862. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  119863. break;
  119864. case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  119865. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  119866. break;
  119867. case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  119868. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  119869. break;
  119870. case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  119871. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  119872. break;
  119873. case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  119874. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  119875. break;
  119876. case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  119877. {
  119878. Token all;
  119879. all.z = yymsp[-3].minor.yy0.z;
  119880. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  119881. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
  119882. }
  119883. break;
  119884. case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  119885. {
  119886. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
  119887. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  119888. }
  119889. break;
  119890. case 266: /* trigger_time ::= BEFORE */
  119891. case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
  119892. { yygotominor.yy328 = TK_BEFORE; }
  119893. break;
  119894. case 267: /* trigger_time ::= AFTER */
  119895. { yygotominor.yy328 = TK_AFTER; }
  119896. break;
  119897. case 268: /* trigger_time ::= INSTEAD OF */
  119898. { yygotominor.yy328 = TK_INSTEAD;}
  119899. break;
  119900. case 270: /* trigger_event ::= DELETE|INSERT */
  119901. case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
  119902. {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
  119903. break;
  119904. case 272: /* trigger_event ::= UPDATE OF idlist */
  119905. {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
  119906. break;
  119907. case 275: /* when_clause ::= */
  119908. case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
  119909. { yygotominor.yy132 = 0; }
  119910. break;
  119911. case 276: /* when_clause ::= WHEN expr */
  119912. case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
  119913. { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
  119914. break;
  119915. case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  119916. {
  119917. assert( yymsp[-2].minor.yy473!=0 );
  119918. yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
  119919. yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
  119920. yygotominor.yy473 = yymsp[-2].minor.yy473;
  119921. }
  119922. break;
  119923. case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
  119924. {
  119925. assert( yymsp[-1].minor.yy473!=0 );
  119926. yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
  119927. yygotominor.yy473 = yymsp[-1].minor.yy473;
  119928. }
  119929. break;
  119930. case 280: /* trnm ::= nm DOT nm */
  119931. {
  119932. yygotominor.yy0 = yymsp[0].minor.yy0;
  119933. sqlite3ErrorMsg(pParse,
  119934. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  119935. "statements within triggers");
  119936. }
  119937. break;
  119938. case 282: /* tridxby ::= INDEXED BY nm */
  119939. {
  119940. sqlite3ErrorMsg(pParse,
  119941. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  119942. "within triggers");
  119943. }
  119944. break;
  119945. case 283: /* tridxby ::= NOT INDEXED */
  119946. {
  119947. sqlite3ErrorMsg(pParse,
  119948. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  119949. "within triggers");
  119950. }
  119951. break;
  119952. case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  119953. { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
  119954. break;
  119955. case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  119956. {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
  119957. break;
  119958. case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  119959. {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
  119960. break;
  119961. case 287: /* trigger_cmd ::= select */
  119962. {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
  119963. break;
  119964. case 288: /* expr ::= RAISE LP IGNORE RP */
  119965. {
  119966. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  119967. if( yygotominor.yy346.pExpr ){
  119968. yygotominor.yy346.pExpr->affinity = OE_Ignore;
  119969. }
  119970. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  119971. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119972. }
  119973. break;
  119974. case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
  119975. {
  119976. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  119977. if( yygotominor.yy346.pExpr ) {
  119978. yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
  119979. }
  119980. yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
  119981. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  119982. }
  119983. break;
  119984. case 290: /* raisetype ::= ROLLBACK */
  119985. {yygotominor.yy328 = OE_Rollback;}
  119986. break;
  119987. case 292: /* raisetype ::= FAIL */
  119988. {yygotominor.yy328 = OE_Fail;}
  119989. break;
  119990. case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
  119991. {
  119992. sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
  119993. }
  119994. break;
  119995. case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  119996. {
  119997. sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
  119998. }
  119999. break;
  120000. case 295: /* cmd ::= DETACH database_kw_opt expr */
  120001. {
  120002. sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
  120003. }
  120004. break;
  120005. case 300: /* cmd ::= REINDEX */
  120006. {sqlite3Reindex(pParse, 0, 0);}
  120007. break;
  120008. case 301: /* cmd ::= REINDEX nm dbnm */
  120009. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  120010. break;
  120011. case 302: /* cmd ::= ANALYZE */
  120012. {sqlite3Analyze(pParse, 0, 0);}
  120013. break;
  120014. case 303: /* cmd ::= ANALYZE nm dbnm */
  120015. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  120016. break;
  120017. case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  120018. {
  120019. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
  120020. }
  120021. break;
  120022. case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  120023. {
  120024. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  120025. }
  120026. break;
  120027. case 306: /* add_column_fullname ::= fullname */
  120028. {
  120029. pParse->db->lookaside.bEnabled = 0;
  120030. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
  120031. }
  120032. break;
  120033. case 309: /* cmd ::= create_vtab */
  120034. {sqlite3VtabFinishParse(pParse,0);}
  120035. break;
  120036. case 310: /* cmd ::= create_vtab LP vtabarglist RP */
  120037. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  120038. break;
  120039. case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  120040. {
  120041. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
  120042. }
  120043. break;
  120044. case 314: /* vtabarg ::= */
  120045. {sqlite3VtabArgInit(pParse);}
  120046. break;
  120047. case 316: /* vtabargtoken ::= ANY */
  120048. case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
  120049. case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
  120050. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  120051. break;
  120052. case 322: /* with ::= */
  120053. {yygotominor.yy59 = 0;}
  120054. break;
  120055. case 323: /* with ::= WITH wqlist */
  120056. case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
  120057. { yygotominor.yy59 = yymsp[0].minor.yy59; }
  120058. break;
  120059. case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
  120060. {
  120061. yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  120062. }
  120063. break;
  120064. case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
  120065. {
  120066. yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  120067. }
  120068. break;
  120069. default:
  120070. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  120071. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  120072. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  120073. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  120074. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  120075. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  120076. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  120077. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  120078. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  120079. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  120080. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  120081. /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
  120082. /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
  120083. /* (43) type ::= */ yytestcase(yyruleno==43);
  120084. /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
  120085. /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
  120086. /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
  120087. /* (53) carglist ::= */ yytestcase(yyruleno==53);
  120088. /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
  120089. /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
  120090. /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
  120091. /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
  120092. /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
  120093. /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
  120094. /* (281) tridxby ::= */ yytestcase(yyruleno==281);
  120095. /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
  120096. /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
  120097. /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
  120098. /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
  120099. /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
  120100. /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
  120101. /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
  120102. /* (319) anylist ::= */ yytestcase(yyruleno==319);
  120103. /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
  120104. /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
  120105. break;
  120106. };
  120107. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  120108. yygoto = yyRuleInfo[yyruleno].lhs;
  120109. yysize = yyRuleInfo[yyruleno].nrhs;
  120110. yypParser->yyidx -= yysize;
  120111. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  120112. if( yyact < YYNSTATE ){
  120113. #ifdef NDEBUG
  120114. /* If we are not debugging and the reduce action popped at least
  120115. ** one element off the stack, then we can push the new element back
  120116. ** onto the stack here, and skip the stack overflow test in yy_shift().
  120117. ** That gives a significant speed improvement. */
  120118. if( yysize ){
  120119. yypParser->yyidx++;
  120120. yymsp -= yysize-1;
  120121. yymsp->stateno = (YYACTIONTYPE)yyact;
  120122. yymsp->major = (YYCODETYPE)yygoto;
  120123. yymsp->minor = yygotominor;
  120124. }else
  120125. #endif
  120126. {
  120127. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  120128. }
  120129. }else{
  120130. assert( yyact == YYNSTATE + YYNRULE + 1 );
  120131. yy_accept(yypParser);
  120132. }
  120133. }
  120134. /*
  120135. ** The following code executes when the parse fails
  120136. */
  120137. #ifndef YYNOERRORRECOVERY
  120138. static void yy_parse_failed(
  120139. yyParser *yypParser /* The parser */
  120140. ){
  120141. sqlite3ParserARG_FETCH;
  120142. #ifndef NDEBUG
  120143. if( yyTraceFILE ){
  120144. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  120145. }
  120146. #endif
  120147. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  120148. /* Here code is inserted which will be executed whenever the
  120149. ** parser fails */
  120150. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  120151. }
  120152. #endif /* YYNOERRORRECOVERY */
  120153. /*
  120154. ** The following code executes when a syntax error first occurs.
  120155. */
  120156. static void yy_syntax_error(
  120157. yyParser *yypParser, /* The parser */
  120158. int yymajor, /* The major type of the error token */
  120159. YYMINORTYPE yyminor /* The minor type of the error token */
  120160. ){
  120161. sqlite3ParserARG_FETCH;
  120162. #define TOKEN (yyminor.yy0)
  120163. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  120164. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  120165. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  120166. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  120167. }
  120168. /*
  120169. ** The following is executed when the parser accepts
  120170. */
  120171. static void yy_accept(
  120172. yyParser *yypParser /* The parser */
  120173. ){
  120174. sqlite3ParserARG_FETCH;
  120175. #ifndef NDEBUG
  120176. if( yyTraceFILE ){
  120177. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  120178. }
  120179. #endif
  120180. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  120181. /* Here code is inserted which will be executed whenever the
  120182. ** parser accepts */
  120183. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  120184. }
  120185. /* The main parser program.
  120186. ** The first argument is a pointer to a structure obtained from
  120187. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  120188. ** The second argument is the major token number. The third is
  120189. ** the minor token. The fourth optional argument is whatever the
  120190. ** user wants (and specified in the grammar) and is available for
  120191. ** use by the action routines.
  120192. **
  120193. ** Inputs:
  120194. ** <ul>
  120195. ** <li> A pointer to the parser (an opaque structure.)
  120196. ** <li> The major token number.
  120197. ** <li> The minor token number.
  120198. ** <li> An option argument of a grammar-specified type.
  120199. ** </ul>
  120200. **
  120201. ** Outputs:
  120202. ** None.
  120203. */
  120204. SQLITE_PRIVATE void sqlite3Parser(
  120205. void *yyp, /* The parser */
  120206. int yymajor, /* The major token code number */
  120207. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  120208. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  120209. ){
  120210. YYMINORTYPE yyminorunion;
  120211. int yyact; /* The parser action. */
  120212. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  120213. int yyendofinput; /* True if we are at the end of input */
  120214. #endif
  120215. #ifdef YYERRORSYMBOL
  120216. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  120217. #endif
  120218. yyParser *yypParser; /* The parser */
  120219. /* (re)initialize the parser, if necessary */
  120220. yypParser = (yyParser*)yyp;
  120221. if( yypParser->yyidx<0 ){
  120222. #if YYSTACKDEPTH<=0
  120223. if( yypParser->yystksz <=0 ){
  120224. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  120225. yyminorunion = yyzerominor;
  120226. yyStackOverflow(yypParser, &yyminorunion);
  120227. return;
  120228. }
  120229. #endif
  120230. yypParser->yyidx = 0;
  120231. yypParser->yyerrcnt = -1;
  120232. yypParser->yystack[0].stateno = 0;
  120233. yypParser->yystack[0].major = 0;
  120234. }
  120235. yyminorunion.yy0 = yyminor;
  120236. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  120237. yyendofinput = (yymajor==0);
  120238. #endif
  120239. sqlite3ParserARG_STORE;
  120240. #ifndef NDEBUG
  120241. if( yyTraceFILE ){
  120242. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  120243. }
  120244. #endif
  120245. do{
  120246. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  120247. if( yyact<YYNSTATE ){
  120248. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  120249. yypParser->yyerrcnt--;
  120250. yymajor = YYNOCODE;
  120251. }else if( yyact < YYNSTATE + YYNRULE ){
  120252. yy_reduce(yypParser,yyact-YYNSTATE);
  120253. }else{
  120254. assert( yyact == YY_ERROR_ACTION );
  120255. #ifdef YYERRORSYMBOL
  120256. int yymx;
  120257. #endif
  120258. #ifndef NDEBUG
  120259. if( yyTraceFILE ){
  120260. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  120261. }
  120262. #endif
  120263. #ifdef YYERRORSYMBOL
  120264. /* A syntax error has occurred.
  120265. ** The response to an error depends upon whether or not the
  120266. ** grammar defines an error token "ERROR".
  120267. **
  120268. ** This is what we do if the grammar does define ERROR:
  120269. **
  120270. ** * Call the %syntax_error function.
  120271. **
  120272. ** * Begin popping the stack until we enter a state where
  120273. ** it is legal to shift the error symbol, then shift
  120274. ** the error symbol.
  120275. **
  120276. ** * Set the error count to three.
  120277. **
  120278. ** * Begin accepting and shifting new tokens. No new error
  120279. ** processing will occur until three tokens have been
  120280. ** shifted successfully.
  120281. **
  120282. */
  120283. if( yypParser->yyerrcnt<0 ){
  120284. yy_syntax_error(yypParser,yymajor,yyminorunion);
  120285. }
  120286. yymx = yypParser->yystack[yypParser->yyidx].major;
  120287. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  120288. #ifndef NDEBUG
  120289. if( yyTraceFILE ){
  120290. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  120291. yyTracePrompt,yyTokenName[yymajor]);
  120292. }
  120293. #endif
  120294. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  120295. yymajor = YYNOCODE;
  120296. }else{
  120297. while(
  120298. yypParser->yyidx >= 0 &&
  120299. yymx != YYERRORSYMBOL &&
  120300. (yyact = yy_find_reduce_action(
  120301. yypParser->yystack[yypParser->yyidx].stateno,
  120302. YYERRORSYMBOL)) >= YYNSTATE
  120303. ){
  120304. yy_pop_parser_stack(yypParser);
  120305. }
  120306. if( yypParser->yyidx < 0 || yymajor==0 ){
  120307. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  120308. yy_parse_failed(yypParser);
  120309. yymajor = YYNOCODE;
  120310. }else if( yymx!=YYERRORSYMBOL ){
  120311. YYMINORTYPE u2;
  120312. u2.YYERRSYMDT = 0;
  120313. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  120314. }
  120315. }
  120316. yypParser->yyerrcnt = 3;
  120317. yyerrorhit = 1;
  120318. #elif defined(YYNOERRORRECOVERY)
  120319. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  120320. ** do any kind of error recovery. Instead, simply invoke the syntax
  120321. ** error routine and continue going as if nothing had happened.
  120322. **
  120323. ** Applications can set this macro (for example inside %include) if
  120324. ** they intend to abandon the parse upon the first syntax error seen.
  120325. */
  120326. yy_syntax_error(yypParser,yymajor,yyminorunion);
  120327. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  120328. yymajor = YYNOCODE;
  120329. #else /* YYERRORSYMBOL is not defined */
  120330. /* This is what we do if the grammar does not define ERROR:
  120331. **
  120332. ** * Report an error message, and throw away the input token.
  120333. **
  120334. ** * If the input token is $, then fail the parse.
  120335. **
  120336. ** As before, subsequent error messages are suppressed until
  120337. ** three input tokens have been successfully shifted.
  120338. */
  120339. if( yypParser->yyerrcnt<=0 ){
  120340. yy_syntax_error(yypParser,yymajor,yyminorunion);
  120341. }
  120342. yypParser->yyerrcnt = 3;
  120343. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  120344. if( yyendofinput ){
  120345. yy_parse_failed(yypParser);
  120346. }
  120347. yymajor = YYNOCODE;
  120348. #endif
  120349. }
  120350. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  120351. return;
  120352. }
  120353. /************** End of parse.c ***********************************************/
  120354. /************** Begin file tokenize.c ****************************************/
  120355. /*
  120356. ** 2001 September 15
  120357. **
  120358. ** The author disclaims copyright to this source code. In place of
  120359. ** a legal notice, here is a blessing:
  120360. **
  120361. ** May you do good and not evil.
  120362. ** May you find forgiveness for yourself and forgive others.
  120363. ** May you share freely, never taking more than you give.
  120364. **
  120365. *************************************************************************
  120366. ** An tokenizer for SQL
  120367. **
  120368. ** This file contains C code that splits an SQL input string up into
  120369. ** individual tokens and sends those tokens one-by-one over to the
  120370. ** parser for analysis.
  120371. */
  120372. /* #include "sqliteInt.h" */
  120373. /* #include <stdlib.h> */
  120374. /*
  120375. ** The charMap() macro maps alphabetic characters into their
  120376. ** lower-case ASCII equivalent. On ASCII machines, this is just
  120377. ** an upper-to-lower case map. On EBCDIC machines we also need
  120378. ** to adjust the encoding. Only alphabetic characters and underscores
  120379. ** need to be translated.
  120380. */
  120381. #ifdef SQLITE_ASCII
  120382. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  120383. #endif
  120384. #ifdef SQLITE_EBCDIC
  120385. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  120386. const unsigned char ebcdicToAscii[] = {
  120387. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  120388. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  120389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  120390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  120391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  120392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  120393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  120394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  120395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  120396. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  120397. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  120398. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  120399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  120400. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  120401. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  120402. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  120403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  120404. };
  120405. #endif
  120406. /*
  120407. ** The sqlite3KeywordCode function looks up an identifier to determine if
  120408. ** it is a keyword. If it is a keyword, the token code of that keyword is
  120409. ** returned. If the input is not a keyword, TK_ID is returned.
  120410. **
  120411. ** The implementation of this routine was generated by a program,
  120412. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  120413. ** The output of the mkkeywordhash.c program is written into a file
  120414. ** named keywordhash.h and then included into this source file by
  120415. ** the #include below.
  120416. */
  120417. /************** Include keywordhash.h in the middle of tokenize.c ************/
  120418. /************** Begin file keywordhash.h *************************************/
  120419. /***** This file contains automatically generated code ******
  120420. **
  120421. ** The code in this file has been automatically generated by
  120422. **
  120423. ** sqlite/tool/mkkeywordhash.c
  120424. **
  120425. ** The code in this file implements a function that determines whether
  120426. ** or not a given identifier is really an SQL keyword. The same thing
  120427. ** might be implemented more directly using a hand-written hash table.
  120428. ** But by using this automatically generated code, the size of the code
  120429. ** is substantially reduced. This is important for embedded applications
  120430. ** on platforms with limited memory.
  120431. */
  120432. /* Hash score: 182 */
  120433. static int keywordCode(const char *z, int n){
  120434. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  120435. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  120436. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  120437. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  120438. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  120439. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  120440. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  120441. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  120442. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  120443. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  120444. /* VACUUMVIEWINITIALLY */
  120445. static const char zText[553] = {
  120446. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  120447. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  120448. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  120449. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  120450. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  120451. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  120452. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  120453. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  120454. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  120455. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  120456. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  120457. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  120458. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  120459. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  120460. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  120461. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  120462. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  120463. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  120464. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  120465. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  120466. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  120467. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  120468. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  120469. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  120470. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  120471. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  120472. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  120473. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  120474. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  120475. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  120476. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  120477. };
  120478. static const unsigned char aHash[127] = {
  120479. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  120480. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  120481. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  120482. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  120483. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  120484. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  120485. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  120486. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  120487. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  120488. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  120489. };
  120490. static const unsigned char aNext[124] = {
  120491. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  120492. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  120493. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  120494. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  120495. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  120496. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  120497. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  120498. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  120499. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  120500. 73, 83, 0, 35, 68, 0, 0,
  120501. };
  120502. static const unsigned char aLen[124] = {
  120503. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  120504. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  120505. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  120506. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  120507. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  120508. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  120509. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  120510. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  120511. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  120512. 3, 5, 5, 6, 4, 9, 3,
  120513. };
  120514. static const unsigned short int aOffset[124] = {
  120515. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  120516. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  120517. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  120518. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  120519. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  120520. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  120521. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  120522. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  120523. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  120524. 521, 524, 529, 534, 540, 544, 549,
  120525. };
  120526. static const unsigned char aCode[124] = {
  120527. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  120528. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  120529. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  120530. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  120531. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  120532. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  120533. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  120534. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  120535. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  120536. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  120537. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  120538. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  120539. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  120540. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  120541. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  120542. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  120543. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  120544. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  120545. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  120546. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  120547. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  120548. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  120549. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  120550. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  120551. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  120552. };
  120553. int h, i;
  120554. if( n<2 ) return TK_ID;
  120555. h = ((charMap(z[0])*4) ^
  120556. (charMap(z[n-1])*3) ^
  120557. n) % 127;
  120558. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  120559. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  120560. testcase( i==0 ); /* REINDEX */
  120561. testcase( i==1 ); /* INDEXED */
  120562. testcase( i==2 ); /* INDEX */
  120563. testcase( i==3 ); /* DESC */
  120564. testcase( i==4 ); /* ESCAPE */
  120565. testcase( i==5 ); /* EACH */
  120566. testcase( i==6 ); /* CHECK */
  120567. testcase( i==7 ); /* KEY */
  120568. testcase( i==8 ); /* BEFORE */
  120569. testcase( i==9 ); /* FOREIGN */
  120570. testcase( i==10 ); /* FOR */
  120571. testcase( i==11 ); /* IGNORE */
  120572. testcase( i==12 ); /* REGEXP */
  120573. testcase( i==13 ); /* EXPLAIN */
  120574. testcase( i==14 ); /* INSTEAD */
  120575. testcase( i==15 ); /* ADD */
  120576. testcase( i==16 ); /* DATABASE */
  120577. testcase( i==17 ); /* AS */
  120578. testcase( i==18 ); /* SELECT */
  120579. testcase( i==19 ); /* TABLE */
  120580. testcase( i==20 ); /* LEFT */
  120581. testcase( i==21 ); /* THEN */
  120582. testcase( i==22 ); /* END */
  120583. testcase( i==23 ); /* DEFERRABLE */
  120584. testcase( i==24 ); /* ELSE */
  120585. testcase( i==25 ); /* EXCEPT */
  120586. testcase( i==26 ); /* TRANSACTION */
  120587. testcase( i==27 ); /* ACTION */
  120588. testcase( i==28 ); /* ON */
  120589. testcase( i==29 ); /* NATURAL */
  120590. testcase( i==30 ); /* ALTER */
  120591. testcase( i==31 ); /* RAISE */
  120592. testcase( i==32 ); /* EXCLUSIVE */
  120593. testcase( i==33 ); /* EXISTS */
  120594. testcase( i==34 ); /* SAVEPOINT */
  120595. testcase( i==35 ); /* INTERSECT */
  120596. testcase( i==36 ); /* TRIGGER */
  120597. testcase( i==37 ); /* REFERENCES */
  120598. testcase( i==38 ); /* CONSTRAINT */
  120599. testcase( i==39 ); /* INTO */
  120600. testcase( i==40 ); /* OFFSET */
  120601. testcase( i==41 ); /* OF */
  120602. testcase( i==42 ); /* SET */
  120603. testcase( i==43 ); /* TEMPORARY */
  120604. testcase( i==44 ); /* TEMP */
  120605. testcase( i==45 ); /* OR */
  120606. testcase( i==46 ); /* UNIQUE */
  120607. testcase( i==47 ); /* QUERY */
  120608. testcase( i==48 ); /* WITHOUT */
  120609. testcase( i==49 ); /* WITH */
  120610. testcase( i==50 ); /* OUTER */
  120611. testcase( i==51 ); /* RELEASE */
  120612. testcase( i==52 ); /* ATTACH */
  120613. testcase( i==53 ); /* HAVING */
  120614. testcase( i==54 ); /* GROUP */
  120615. testcase( i==55 ); /* UPDATE */
  120616. testcase( i==56 ); /* BEGIN */
  120617. testcase( i==57 ); /* INNER */
  120618. testcase( i==58 ); /* RECURSIVE */
  120619. testcase( i==59 ); /* BETWEEN */
  120620. testcase( i==60 ); /* NOTNULL */
  120621. testcase( i==61 ); /* NOT */
  120622. testcase( i==62 ); /* NO */
  120623. testcase( i==63 ); /* NULL */
  120624. testcase( i==64 ); /* LIKE */
  120625. testcase( i==65 ); /* CASCADE */
  120626. testcase( i==66 ); /* ASC */
  120627. testcase( i==67 ); /* DELETE */
  120628. testcase( i==68 ); /* CASE */
  120629. testcase( i==69 ); /* COLLATE */
  120630. testcase( i==70 ); /* CREATE */
  120631. testcase( i==71 ); /* CURRENT_DATE */
  120632. testcase( i==72 ); /* DETACH */
  120633. testcase( i==73 ); /* IMMEDIATE */
  120634. testcase( i==74 ); /* JOIN */
  120635. testcase( i==75 ); /* INSERT */
  120636. testcase( i==76 ); /* MATCH */
  120637. testcase( i==77 ); /* PLAN */
  120638. testcase( i==78 ); /* ANALYZE */
  120639. testcase( i==79 ); /* PRAGMA */
  120640. testcase( i==80 ); /* ABORT */
  120641. testcase( i==81 ); /* VALUES */
  120642. testcase( i==82 ); /* VIRTUAL */
  120643. testcase( i==83 ); /* LIMIT */
  120644. testcase( i==84 ); /* WHEN */
  120645. testcase( i==85 ); /* WHERE */
  120646. testcase( i==86 ); /* RENAME */
  120647. testcase( i==87 ); /* AFTER */
  120648. testcase( i==88 ); /* REPLACE */
  120649. testcase( i==89 ); /* AND */
  120650. testcase( i==90 ); /* DEFAULT */
  120651. testcase( i==91 ); /* AUTOINCREMENT */
  120652. testcase( i==92 ); /* TO */
  120653. testcase( i==93 ); /* IN */
  120654. testcase( i==94 ); /* CAST */
  120655. testcase( i==95 ); /* COLUMN */
  120656. testcase( i==96 ); /* COMMIT */
  120657. testcase( i==97 ); /* CONFLICT */
  120658. testcase( i==98 ); /* CROSS */
  120659. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  120660. testcase( i==100 ); /* CURRENT_TIME */
  120661. testcase( i==101 ); /* PRIMARY */
  120662. testcase( i==102 ); /* DEFERRED */
  120663. testcase( i==103 ); /* DISTINCT */
  120664. testcase( i==104 ); /* IS */
  120665. testcase( i==105 ); /* DROP */
  120666. testcase( i==106 ); /* FAIL */
  120667. testcase( i==107 ); /* FROM */
  120668. testcase( i==108 ); /* FULL */
  120669. testcase( i==109 ); /* GLOB */
  120670. testcase( i==110 ); /* BY */
  120671. testcase( i==111 ); /* IF */
  120672. testcase( i==112 ); /* ISNULL */
  120673. testcase( i==113 ); /* ORDER */
  120674. testcase( i==114 ); /* RESTRICT */
  120675. testcase( i==115 ); /* RIGHT */
  120676. testcase( i==116 ); /* ROLLBACK */
  120677. testcase( i==117 ); /* ROW */
  120678. testcase( i==118 ); /* UNION */
  120679. testcase( i==119 ); /* USING */
  120680. testcase( i==120 ); /* VACUUM */
  120681. testcase( i==121 ); /* VIEW */
  120682. testcase( i==122 ); /* INITIALLY */
  120683. testcase( i==123 ); /* ALL */
  120684. return aCode[i];
  120685. }
  120686. }
  120687. return TK_ID;
  120688. }
  120689. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  120690. return keywordCode((char*)z, n);
  120691. }
  120692. #define SQLITE_N_KEYWORD 124
  120693. /************** End of keywordhash.h *****************************************/
  120694. /************** Continuing where we left off in tokenize.c *******************/
  120695. /*
  120696. ** If X is a character that can be used in an identifier then
  120697. ** IdChar(X) will be true. Otherwise it is false.
  120698. **
  120699. ** For ASCII, any character with the high-order bit set is
  120700. ** allowed in an identifier. For 7-bit characters,
  120701. ** sqlite3IsIdChar[X] must be 1.
  120702. **
  120703. ** For EBCDIC, the rules are more complex but have the same
  120704. ** end result.
  120705. **
  120706. ** Ticket #1066. the SQL standard does not allow '$' in the
  120707. ** middle of identifiers. But many SQL implementations do.
  120708. ** SQLite will allow '$' in identifiers for compatibility.
  120709. ** But the feature is undocumented.
  120710. */
  120711. #ifdef SQLITE_ASCII
  120712. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  120713. #endif
  120714. #ifdef SQLITE_EBCDIC
  120715. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  120716. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  120717. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  120718. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  120719. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  120720. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  120721. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  120722. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  120723. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  120724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  120725. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  120726. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  120727. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  120728. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  120729. };
  120730. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  120731. #endif
  120732. /* Make the IdChar function accessible from ctime.c */
  120733. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  120734. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  120735. #endif
  120736. /*
  120737. ** Return the length of the token that begins at z[0].
  120738. ** Store the token type in *tokenType before returning.
  120739. */
  120740. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  120741. int i, c;
  120742. switch( *z ){
  120743. case ' ': case '\t': case '\n': case '\f': case '\r': {
  120744. testcase( z[0]==' ' );
  120745. testcase( z[0]=='\t' );
  120746. testcase( z[0]=='\n' );
  120747. testcase( z[0]=='\f' );
  120748. testcase( z[0]=='\r' );
  120749. for(i=1; sqlite3Isspace(z[i]); i++){}
  120750. *tokenType = TK_SPACE;
  120751. return i;
  120752. }
  120753. case '-': {
  120754. if( z[1]=='-' ){
  120755. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  120756. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  120757. return i;
  120758. }
  120759. *tokenType = TK_MINUS;
  120760. return 1;
  120761. }
  120762. case '(': {
  120763. *tokenType = TK_LP;
  120764. return 1;
  120765. }
  120766. case ')': {
  120767. *tokenType = TK_RP;
  120768. return 1;
  120769. }
  120770. case ';': {
  120771. *tokenType = TK_SEMI;
  120772. return 1;
  120773. }
  120774. case '+': {
  120775. *tokenType = TK_PLUS;
  120776. return 1;
  120777. }
  120778. case '*': {
  120779. *tokenType = TK_STAR;
  120780. return 1;
  120781. }
  120782. case '/': {
  120783. if( z[1]!='*' || z[2]==0 ){
  120784. *tokenType = TK_SLASH;
  120785. return 1;
  120786. }
  120787. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  120788. if( c ) i++;
  120789. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  120790. return i;
  120791. }
  120792. case '%': {
  120793. *tokenType = TK_REM;
  120794. return 1;
  120795. }
  120796. case '=': {
  120797. *tokenType = TK_EQ;
  120798. return 1 + (z[1]=='=');
  120799. }
  120800. case '<': {
  120801. if( (c=z[1])=='=' ){
  120802. *tokenType = TK_LE;
  120803. return 2;
  120804. }else if( c=='>' ){
  120805. *tokenType = TK_NE;
  120806. return 2;
  120807. }else if( c=='<' ){
  120808. *tokenType = TK_LSHIFT;
  120809. return 2;
  120810. }else{
  120811. *tokenType = TK_LT;
  120812. return 1;
  120813. }
  120814. }
  120815. case '>': {
  120816. if( (c=z[1])=='=' ){
  120817. *tokenType = TK_GE;
  120818. return 2;
  120819. }else if( c=='>' ){
  120820. *tokenType = TK_RSHIFT;
  120821. return 2;
  120822. }else{
  120823. *tokenType = TK_GT;
  120824. return 1;
  120825. }
  120826. }
  120827. case '!': {
  120828. if( z[1]!='=' ){
  120829. *tokenType = TK_ILLEGAL;
  120830. return 2;
  120831. }else{
  120832. *tokenType = TK_NE;
  120833. return 2;
  120834. }
  120835. }
  120836. case '|': {
  120837. if( z[1]!='|' ){
  120838. *tokenType = TK_BITOR;
  120839. return 1;
  120840. }else{
  120841. *tokenType = TK_CONCAT;
  120842. return 2;
  120843. }
  120844. }
  120845. case ',': {
  120846. *tokenType = TK_COMMA;
  120847. return 1;
  120848. }
  120849. case '&': {
  120850. *tokenType = TK_BITAND;
  120851. return 1;
  120852. }
  120853. case '~': {
  120854. *tokenType = TK_BITNOT;
  120855. return 1;
  120856. }
  120857. case '`':
  120858. case '\'':
  120859. case '"': {
  120860. int delim = z[0];
  120861. testcase( delim=='`' );
  120862. testcase( delim=='\'' );
  120863. testcase( delim=='"' );
  120864. for(i=1; (c=z[i])!=0; i++){
  120865. if( c==delim ){
  120866. if( z[i+1]==delim ){
  120867. i++;
  120868. }else{
  120869. break;
  120870. }
  120871. }
  120872. }
  120873. if( c=='\'' ){
  120874. *tokenType = TK_STRING;
  120875. return i+1;
  120876. }else if( c!=0 ){
  120877. *tokenType = TK_ID;
  120878. return i+1;
  120879. }else{
  120880. *tokenType = TK_ILLEGAL;
  120881. return i;
  120882. }
  120883. }
  120884. case '.': {
  120885. #ifndef SQLITE_OMIT_FLOATING_POINT
  120886. if( !sqlite3Isdigit(z[1]) )
  120887. #endif
  120888. {
  120889. *tokenType = TK_DOT;
  120890. return 1;
  120891. }
  120892. /* If the next character is a digit, this is a floating point
  120893. ** number that begins with ".". Fall thru into the next case */
  120894. }
  120895. case '0': case '1': case '2': case '3': case '4':
  120896. case '5': case '6': case '7': case '8': case '9': {
  120897. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  120898. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  120899. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  120900. testcase( z[0]=='9' );
  120901. *tokenType = TK_INTEGER;
  120902. #ifndef SQLITE_OMIT_HEX_INTEGER
  120903. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  120904. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  120905. return i;
  120906. }
  120907. #endif
  120908. for(i=0; sqlite3Isdigit(z[i]); i++){}
  120909. #ifndef SQLITE_OMIT_FLOATING_POINT
  120910. if( z[i]=='.' ){
  120911. i++;
  120912. while( sqlite3Isdigit(z[i]) ){ i++; }
  120913. *tokenType = TK_FLOAT;
  120914. }
  120915. if( (z[i]=='e' || z[i]=='E') &&
  120916. ( sqlite3Isdigit(z[i+1])
  120917. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  120918. )
  120919. ){
  120920. i += 2;
  120921. while( sqlite3Isdigit(z[i]) ){ i++; }
  120922. *tokenType = TK_FLOAT;
  120923. }
  120924. #endif
  120925. while( IdChar(z[i]) ){
  120926. *tokenType = TK_ILLEGAL;
  120927. i++;
  120928. }
  120929. return i;
  120930. }
  120931. case '[': {
  120932. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  120933. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  120934. return i;
  120935. }
  120936. case '?': {
  120937. *tokenType = TK_VARIABLE;
  120938. for(i=1; sqlite3Isdigit(z[i]); i++){}
  120939. return i;
  120940. }
  120941. #ifndef SQLITE_OMIT_TCL_VARIABLE
  120942. case '$':
  120943. #endif
  120944. case '@': /* For compatibility with MS SQL Server */
  120945. case '#':
  120946. case ':': {
  120947. int n = 0;
  120948. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  120949. testcase( z[0]==':' ); testcase( z[0]=='#' );
  120950. *tokenType = TK_VARIABLE;
  120951. for(i=1; (c=z[i])!=0; i++){
  120952. if( IdChar(c) ){
  120953. n++;
  120954. #ifndef SQLITE_OMIT_TCL_VARIABLE
  120955. }else if( c=='(' && n>0 ){
  120956. do{
  120957. i++;
  120958. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  120959. if( c==')' ){
  120960. i++;
  120961. }else{
  120962. *tokenType = TK_ILLEGAL;
  120963. }
  120964. break;
  120965. }else if( c==':' && z[i+1]==':' ){
  120966. i++;
  120967. #endif
  120968. }else{
  120969. break;
  120970. }
  120971. }
  120972. if( n==0 ) *tokenType = TK_ILLEGAL;
  120973. return i;
  120974. }
  120975. #ifndef SQLITE_OMIT_BLOB_LITERAL
  120976. case 'x': case 'X': {
  120977. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  120978. if( z[1]=='\'' ){
  120979. *tokenType = TK_BLOB;
  120980. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  120981. if( z[i]!='\'' || i%2 ){
  120982. *tokenType = TK_ILLEGAL;
  120983. while( z[i] && z[i]!='\'' ){ i++; }
  120984. }
  120985. if( z[i] ) i++;
  120986. return i;
  120987. }
  120988. /* Otherwise fall through to the next case */
  120989. }
  120990. #endif
  120991. default: {
  120992. if( !IdChar(*z) ){
  120993. break;
  120994. }
  120995. for(i=1; IdChar(z[i]); i++){}
  120996. *tokenType = keywordCode((char*)z, i);
  120997. return i;
  120998. }
  120999. }
  121000. *tokenType = TK_ILLEGAL;
  121001. return 1;
  121002. }
  121003. /*
  121004. ** Run the parser on the given SQL string. The parser structure is
  121005. ** passed in. An SQLITE_ status code is returned. If an error occurs
  121006. ** then an and attempt is made to write an error message into
  121007. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  121008. ** error message.
  121009. */
  121010. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  121011. int nErr = 0; /* Number of errors encountered */
  121012. int i; /* Loop counter */
  121013. void *pEngine; /* The LEMON-generated LALR(1) parser */
  121014. int tokenType; /* type of the next token */
  121015. int lastTokenParsed = -1; /* type of the previous token */
  121016. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  121017. sqlite3 *db = pParse->db; /* The database connection */
  121018. int mxSqlLen; /* Max length of an SQL string */
  121019. assert( zSql!=0 );
  121020. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  121021. if( db->nVdbeActive==0 ){
  121022. db->u1.isInterrupted = 0;
  121023. }
  121024. pParse->rc = SQLITE_OK;
  121025. pParse->zTail = zSql;
  121026. i = 0;
  121027. assert( pzErrMsg!=0 );
  121028. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  121029. if( pEngine==0 ){
  121030. db->mallocFailed = 1;
  121031. return SQLITE_NOMEM;
  121032. }
  121033. assert( pParse->pNewTable==0 );
  121034. assert( pParse->pNewTrigger==0 );
  121035. assert( pParse->nVar==0 );
  121036. assert( pParse->nzVar==0 );
  121037. assert( pParse->azVar==0 );
  121038. enableLookaside = db->lookaside.bEnabled;
  121039. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  121040. while( !db->mallocFailed && zSql[i]!=0 ){
  121041. assert( i>=0 );
  121042. pParse->sLastToken.z = &zSql[i];
  121043. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  121044. i += pParse->sLastToken.n;
  121045. if( i>mxSqlLen ){
  121046. pParse->rc = SQLITE_TOOBIG;
  121047. break;
  121048. }
  121049. switch( tokenType ){
  121050. case TK_SPACE: {
  121051. if( db->u1.isInterrupted ){
  121052. sqlite3ErrorMsg(pParse, "interrupt");
  121053. pParse->rc = SQLITE_INTERRUPT;
  121054. goto abort_parse;
  121055. }
  121056. break;
  121057. }
  121058. case TK_ILLEGAL: {
  121059. sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
  121060. &pParse->sLastToken);
  121061. goto abort_parse;
  121062. }
  121063. case TK_SEMI: {
  121064. pParse->zTail = &zSql[i];
  121065. /* Fall thru into the default case */
  121066. }
  121067. default: {
  121068. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  121069. lastTokenParsed = tokenType;
  121070. if( pParse->rc!=SQLITE_OK ){
  121071. goto abort_parse;
  121072. }
  121073. break;
  121074. }
  121075. }
  121076. }
  121077. abort_parse:
  121078. assert( nErr==0 );
  121079. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  121080. assert( zSql[i]==0 );
  121081. if( lastTokenParsed!=TK_SEMI ){
  121082. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  121083. pParse->zTail = &zSql[i];
  121084. }
  121085. if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
  121086. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  121087. }
  121088. }
  121089. #ifdef YYTRACKMAXSTACKDEPTH
  121090. sqlite3_mutex_enter(sqlite3MallocMutex());
  121091. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  121092. sqlite3ParserStackPeak(pEngine)
  121093. );
  121094. sqlite3_mutex_leave(sqlite3MallocMutex());
  121095. #endif /* YYDEBUG */
  121096. sqlite3ParserFree(pEngine, sqlite3_free);
  121097. db->lookaside.bEnabled = enableLookaside;
  121098. if( db->mallocFailed ){
  121099. pParse->rc = SQLITE_NOMEM;
  121100. }
  121101. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  121102. pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
  121103. }
  121104. assert( pzErrMsg!=0 );
  121105. if( pParse->zErrMsg ){
  121106. *pzErrMsg = pParse->zErrMsg;
  121107. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  121108. pParse->zErrMsg = 0;
  121109. nErr++;
  121110. }
  121111. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  121112. sqlite3VdbeDelete(pParse->pVdbe);
  121113. pParse->pVdbe = 0;
  121114. }
  121115. #ifndef SQLITE_OMIT_SHARED_CACHE
  121116. if( pParse->nested==0 ){
  121117. sqlite3DbFree(db, pParse->aTableLock);
  121118. pParse->aTableLock = 0;
  121119. pParse->nTableLock = 0;
  121120. }
  121121. #endif
  121122. #ifndef SQLITE_OMIT_VIRTUALTABLE
  121123. sqlite3_free(pParse->apVtabLock);
  121124. #endif
  121125. if( !IN_DECLARE_VTAB ){
  121126. /* If the pParse->declareVtab flag is set, do not delete any table
  121127. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  121128. ** will take responsibility for freeing the Table structure.
  121129. */
  121130. sqlite3DeleteTable(db, pParse->pNewTable);
  121131. }
  121132. if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
  121133. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  121134. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  121135. sqlite3DbFree(db, pParse->azVar);
  121136. while( pParse->pAinc ){
  121137. AutoincInfo *p = pParse->pAinc;
  121138. pParse->pAinc = p->pNext;
  121139. sqlite3DbFree(db, p);
  121140. }
  121141. while( pParse->pZombieTab ){
  121142. Table *p = pParse->pZombieTab;
  121143. pParse->pZombieTab = p->pNextZombie;
  121144. sqlite3DeleteTable(db, p);
  121145. }
  121146. assert( nErr==0 || pParse->rc!=SQLITE_OK );
  121147. return nErr;
  121148. }
  121149. /************** End of tokenize.c ********************************************/
  121150. /************** Begin file complete.c ****************************************/
  121151. /*
  121152. ** 2001 September 15
  121153. **
  121154. ** The author disclaims copyright to this source code. In place of
  121155. ** a legal notice, here is a blessing:
  121156. **
  121157. ** May you do good and not evil.
  121158. ** May you find forgiveness for yourself and forgive others.
  121159. ** May you share freely, never taking more than you give.
  121160. **
  121161. *************************************************************************
  121162. ** An tokenizer for SQL
  121163. **
  121164. ** This file contains C code that implements the sqlite3_complete() API.
  121165. ** This code used to be part of the tokenizer.c source file. But by
  121166. ** separating it out, the code will be automatically omitted from
  121167. ** static links that do not use it.
  121168. */
  121169. /* #include "sqliteInt.h" */
  121170. #ifndef SQLITE_OMIT_COMPLETE
  121171. /*
  121172. ** This is defined in tokenize.c. We just have to import the definition.
  121173. */
  121174. #ifndef SQLITE_AMALGAMATION
  121175. #ifdef SQLITE_ASCII
  121176. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  121177. #endif
  121178. #ifdef SQLITE_EBCDIC
  121179. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  121180. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  121181. #endif
  121182. #endif /* SQLITE_AMALGAMATION */
  121183. /*
  121184. ** Token types used by the sqlite3_complete() routine. See the header
  121185. ** comments on that procedure for additional information.
  121186. */
  121187. #define tkSEMI 0
  121188. #define tkWS 1
  121189. #define tkOTHER 2
  121190. #ifndef SQLITE_OMIT_TRIGGER
  121191. #define tkEXPLAIN 3
  121192. #define tkCREATE 4
  121193. #define tkTEMP 5
  121194. #define tkTRIGGER 6
  121195. #define tkEND 7
  121196. #endif
  121197. /*
  121198. ** Return TRUE if the given SQL string ends in a semicolon.
  121199. **
  121200. ** Special handling is require for CREATE TRIGGER statements.
  121201. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  121202. ** must end with ";END;".
  121203. **
  121204. ** This implementation uses a state machine with 8 states:
  121205. **
  121206. ** (0) INVALID We have not yet seen a non-whitespace character.
  121207. **
  121208. ** (1) START At the beginning or end of an SQL statement. This routine
  121209. ** returns 1 if it ends in the START state and 0 if it ends
  121210. ** in any other state.
  121211. **
  121212. ** (2) NORMAL We are in the middle of statement which ends with a single
  121213. ** semicolon.
  121214. **
  121215. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  121216. ** a statement.
  121217. **
  121218. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  121219. ** statement, possibly preceded by EXPLAIN and/or followed by
  121220. ** TEMP or TEMPORARY
  121221. **
  121222. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  121223. ** ended by a semicolon, the keyword END, and another semicolon.
  121224. **
  121225. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  121226. ** the end of a trigger definition.
  121227. **
  121228. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  121229. ** of a trigger definition.
  121230. **
  121231. ** Transitions between states above are determined by tokens extracted
  121232. ** from the input. The following tokens are significant:
  121233. **
  121234. ** (0) tkSEMI A semicolon.
  121235. ** (1) tkWS Whitespace.
  121236. ** (2) tkOTHER Any other SQL token.
  121237. ** (3) tkEXPLAIN The "explain" keyword.
  121238. ** (4) tkCREATE The "create" keyword.
  121239. ** (5) tkTEMP The "temp" or "temporary" keyword.
  121240. ** (6) tkTRIGGER The "trigger" keyword.
  121241. ** (7) tkEND The "end" keyword.
  121242. **
  121243. ** Whitespace never causes a state transition and is always ignored.
  121244. ** This means that a SQL string of all whitespace is invalid.
  121245. **
  121246. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  121247. ** to recognize the end of a trigger can be omitted. All we have to do
  121248. ** is look for a semicolon that is not part of an string or comment.
  121249. */
  121250. SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
  121251. u8 state = 0; /* Current state, using numbers defined in header comment */
  121252. u8 token; /* Value of the next token */
  121253. #ifndef SQLITE_OMIT_TRIGGER
  121254. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  121255. ** statement. This is the normal case.
  121256. */
  121257. static const u8 trans[8][8] = {
  121258. /* Token: */
  121259. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  121260. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  121261. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  121262. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  121263. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  121264. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  121265. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  121266. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  121267. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  121268. };
  121269. #else
  121270. /* If triggers are not supported by this compile then the statement machine
  121271. ** used to detect the end of a statement is much simpler
  121272. */
  121273. static const u8 trans[3][3] = {
  121274. /* Token: */
  121275. /* State: ** SEMI WS OTHER */
  121276. /* 0 INVALID: */ { 1, 0, 2, },
  121277. /* 1 START: */ { 1, 1, 2, },
  121278. /* 2 NORMAL: */ { 1, 2, 2, },
  121279. };
  121280. #endif /* SQLITE_OMIT_TRIGGER */
  121281. #ifdef SQLITE_ENABLE_API_ARMOR
  121282. if( zSql==0 ){
  121283. (void)SQLITE_MISUSE_BKPT;
  121284. return 0;
  121285. }
  121286. #endif
  121287. while( *zSql ){
  121288. switch( *zSql ){
  121289. case ';': { /* A semicolon */
  121290. token = tkSEMI;
  121291. break;
  121292. }
  121293. case ' ':
  121294. case '\r':
  121295. case '\t':
  121296. case '\n':
  121297. case '\f': { /* White space is ignored */
  121298. token = tkWS;
  121299. break;
  121300. }
  121301. case '/': { /* C-style comments */
  121302. if( zSql[1]!='*' ){
  121303. token = tkOTHER;
  121304. break;
  121305. }
  121306. zSql += 2;
  121307. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  121308. if( zSql[0]==0 ) return 0;
  121309. zSql++;
  121310. token = tkWS;
  121311. break;
  121312. }
  121313. case '-': { /* SQL-style comments from "--" to end of line */
  121314. if( zSql[1]!='-' ){
  121315. token = tkOTHER;
  121316. break;
  121317. }
  121318. while( *zSql && *zSql!='\n' ){ zSql++; }
  121319. if( *zSql==0 ) return state==1;
  121320. token = tkWS;
  121321. break;
  121322. }
  121323. case '[': { /* Microsoft-style identifiers in [...] */
  121324. zSql++;
  121325. while( *zSql && *zSql!=']' ){ zSql++; }
  121326. if( *zSql==0 ) return 0;
  121327. token = tkOTHER;
  121328. break;
  121329. }
  121330. case '`': /* Grave-accent quoted symbols used by MySQL */
  121331. case '"': /* single- and double-quoted strings */
  121332. case '\'': {
  121333. int c = *zSql;
  121334. zSql++;
  121335. while( *zSql && *zSql!=c ){ zSql++; }
  121336. if( *zSql==0 ) return 0;
  121337. token = tkOTHER;
  121338. break;
  121339. }
  121340. default: {
  121341. #ifdef SQLITE_EBCDIC
  121342. unsigned char c;
  121343. #endif
  121344. if( IdChar((u8)*zSql) ){
  121345. /* Keywords and unquoted identifiers */
  121346. int nId;
  121347. for(nId=1; IdChar(zSql[nId]); nId++){}
  121348. #ifdef SQLITE_OMIT_TRIGGER
  121349. token = tkOTHER;
  121350. #else
  121351. switch( *zSql ){
  121352. case 'c': case 'C': {
  121353. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  121354. token = tkCREATE;
  121355. }else{
  121356. token = tkOTHER;
  121357. }
  121358. break;
  121359. }
  121360. case 't': case 'T': {
  121361. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  121362. token = tkTRIGGER;
  121363. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  121364. token = tkTEMP;
  121365. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  121366. token = tkTEMP;
  121367. }else{
  121368. token = tkOTHER;
  121369. }
  121370. break;
  121371. }
  121372. case 'e': case 'E': {
  121373. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  121374. token = tkEND;
  121375. }else
  121376. #ifndef SQLITE_OMIT_EXPLAIN
  121377. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  121378. token = tkEXPLAIN;
  121379. }else
  121380. #endif
  121381. {
  121382. token = tkOTHER;
  121383. }
  121384. break;
  121385. }
  121386. default: {
  121387. token = tkOTHER;
  121388. break;
  121389. }
  121390. }
  121391. #endif /* SQLITE_OMIT_TRIGGER */
  121392. zSql += nId-1;
  121393. }else{
  121394. /* Operators and special symbols */
  121395. token = tkOTHER;
  121396. }
  121397. break;
  121398. }
  121399. }
  121400. state = trans[state][token];
  121401. zSql++;
  121402. }
  121403. return state==1;
  121404. }
  121405. #ifndef SQLITE_OMIT_UTF16
  121406. /*
  121407. ** This routine is the same as the sqlite3_complete() routine described
  121408. ** above, except that the parameter is required to be UTF-16 encoded, not
  121409. ** UTF-8.
  121410. */
  121411. SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
  121412. sqlite3_value *pVal;
  121413. char const *zSql8;
  121414. int rc;
  121415. #ifndef SQLITE_OMIT_AUTOINIT
  121416. rc = sqlite3_initialize();
  121417. if( rc ) return rc;
  121418. #endif
  121419. pVal = sqlite3ValueNew(0);
  121420. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  121421. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  121422. if( zSql8 ){
  121423. rc = sqlite3_complete(zSql8);
  121424. }else{
  121425. rc = SQLITE_NOMEM;
  121426. }
  121427. sqlite3ValueFree(pVal);
  121428. return rc & 0xff;
  121429. }
  121430. #endif /* SQLITE_OMIT_UTF16 */
  121431. #endif /* SQLITE_OMIT_COMPLETE */
  121432. /************** End of complete.c ********************************************/
  121433. /************** Begin file main.c ********************************************/
  121434. /*
  121435. ** 2001 September 15
  121436. **
  121437. ** The author disclaims copyright to this source code. In place of
  121438. ** a legal notice, here is a blessing:
  121439. **
  121440. ** May you do good and not evil.
  121441. ** May you find forgiveness for yourself and forgive others.
  121442. ** May you share freely, never taking more than you give.
  121443. **
  121444. *************************************************************************
  121445. ** Main file for the SQLite library. The routines in this file
  121446. ** implement the programmer interface to the library. Routines in
  121447. ** other files are for internal use by SQLite and should not be
  121448. ** accessed by users of the library.
  121449. */
  121450. /* #include "sqliteInt.h" */
  121451. #ifdef SQLITE_ENABLE_FTS3
  121452. /************** Include fts3.h in the middle of main.c ***********************/
  121453. /************** Begin file fts3.h ********************************************/
  121454. /*
  121455. ** 2006 Oct 10
  121456. **
  121457. ** The author disclaims copyright to this source code. In place of
  121458. ** a legal notice, here is a blessing:
  121459. **
  121460. ** May you do good and not evil.
  121461. ** May you find forgiveness for yourself and forgive others.
  121462. ** May you share freely, never taking more than you give.
  121463. **
  121464. ******************************************************************************
  121465. **
  121466. ** This header file is used by programs that want to link against the
  121467. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  121468. */
  121469. /* #include "sqlite3.h" */
  121470. #if 0
  121471. extern "C" {
  121472. #endif /* __cplusplus */
  121473. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  121474. #if 0
  121475. } /* extern "C" */
  121476. #endif /* __cplusplus */
  121477. /************** End of fts3.h ************************************************/
  121478. /************** Continuing where we left off in main.c ***********************/
  121479. #endif
  121480. #ifdef SQLITE_ENABLE_RTREE
  121481. /************** Include rtree.h in the middle of main.c **********************/
  121482. /************** Begin file rtree.h *******************************************/
  121483. /*
  121484. ** 2008 May 26
  121485. **
  121486. ** The author disclaims copyright to this source code. In place of
  121487. ** a legal notice, here is a blessing:
  121488. **
  121489. ** May you do good and not evil.
  121490. ** May you find forgiveness for yourself and forgive others.
  121491. ** May you share freely, never taking more than you give.
  121492. **
  121493. ******************************************************************************
  121494. **
  121495. ** This header file is used by programs that want to link against the
  121496. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  121497. */
  121498. /* #include "sqlite3.h" */
  121499. #if 0
  121500. extern "C" {
  121501. #endif /* __cplusplus */
  121502. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  121503. #if 0
  121504. } /* extern "C" */
  121505. #endif /* __cplusplus */
  121506. /************** End of rtree.h ***********************************************/
  121507. /************** Continuing where we left off in main.c ***********************/
  121508. #endif
  121509. #ifdef SQLITE_ENABLE_ICU
  121510. /************** Include sqliteicu.h in the middle of main.c ******************/
  121511. /************** Begin file sqliteicu.h ***************************************/
  121512. /*
  121513. ** 2008 May 26
  121514. **
  121515. ** The author disclaims copyright to this source code. In place of
  121516. ** a legal notice, here is a blessing:
  121517. **
  121518. ** May you do good and not evil.
  121519. ** May you find forgiveness for yourself and forgive others.
  121520. ** May you share freely, never taking more than you give.
  121521. **
  121522. ******************************************************************************
  121523. **
  121524. ** This header file is used by programs that want to link against the
  121525. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  121526. */
  121527. /* #include "sqlite3.h" */
  121528. #if 0
  121529. extern "C" {
  121530. #endif /* __cplusplus */
  121531. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  121532. #if 0
  121533. } /* extern "C" */
  121534. #endif /* __cplusplus */
  121535. /************** End of sqliteicu.h *******************************************/
  121536. /************** Continuing where we left off in main.c ***********************/
  121537. #endif
  121538. #ifndef SQLITE_AMALGAMATION
  121539. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  121540. ** contains the text of SQLITE_VERSION macro.
  121541. */
  121542. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  121543. #endif
  121544. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  121545. ** a pointer to the to the sqlite3_version[] string constant.
  121546. */
  121547. SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
  121548. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  121549. ** pointer to a string constant whose value is the same as the
  121550. ** SQLITE_SOURCE_ID C preprocessor macro.
  121551. */
  121552. SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  121553. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  121554. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  121555. */
  121556. SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  121557. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  121558. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  121559. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  121560. */
  121561. SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  121562. /*
  121563. ** When compiling the test fixture or with debugging enabled (on Win32),
  121564. ** this variable being set to non-zero will cause OSTRACE macros to emit
  121565. ** extra diagnostic information.
  121566. */
  121567. #ifdef SQLITE_HAVE_OS_TRACE
  121568. # ifndef SQLITE_DEBUG_OS_TRACE
  121569. # define SQLITE_DEBUG_OS_TRACE 0
  121570. # endif
  121571. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  121572. #endif
  121573. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  121574. /*
  121575. ** If the following function pointer is not NULL and if
  121576. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  121577. ** I/O active are written using this function. These messages
  121578. ** are intended for debugging activity only.
  121579. */
  121580. SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
  121581. #endif
  121582. /*
  121583. ** If the following global variable points to a string which is the
  121584. ** name of a directory, then that directory will be used to store
  121585. ** temporary files.
  121586. **
  121587. ** See also the "PRAGMA temp_store_directory" SQL command.
  121588. */
  121589. SQLITE_API char *sqlite3_temp_directory = 0;
  121590. /*
  121591. ** If the following global variable points to a string which is the
  121592. ** name of a directory, then that directory will be used to store
  121593. ** all database files specified with a relative pathname.
  121594. **
  121595. ** See also the "PRAGMA data_store_directory" SQL command.
  121596. */
  121597. SQLITE_API char *sqlite3_data_directory = 0;
  121598. /*
  121599. ** Initialize SQLite.
  121600. **
  121601. ** This routine must be called to initialize the memory allocation,
  121602. ** VFS, and mutex subsystems prior to doing any serious work with
  121603. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  121604. ** this routine will be called automatically by key routines such as
  121605. ** sqlite3_open().
  121606. **
  121607. ** This routine is a no-op except on its very first call for the process,
  121608. ** or for the first call after a call to sqlite3_shutdown.
  121609. **
  121610. ** The first thread to call this routine runs the initialization to
  121611. ** completion. If subsequent threads call this routine before the first
  121612. ** thread has finished the initialization process, then the subsequent
  121613. ** threads must block until the first thread finishes with the initialization.
  121614. **
  121615. ** The first thread might call this routine recursively. Recursive
  121616. ** calls to this routine should not block, of course. Otherwise the
  121617. ** initialization process would never complete.
  121618. **
  121619. ** Let X be the first thread to enter this routine. Let Y be some other
  121620. ** thread. Then while the initial invocation of this routine by X is
  121621. ** incomplete, it is required that:
  121622. **
  121623. ** * Calls to this routine from Y must block until the outer-most
  121624. ** call by X completes.
  121625. **
  121626. ** * Recursive calls to this routine from thread X return immediately
  121627. ** without blocking.
  121628. */
  121629. SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
  121630. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  121631. int rc; /* Result code */
  121632. #ifdef SQLITE_EXTRA_INIT
  121633. int bRunExtraInit = 0; /* Extra initialization needed */
  121634. #endif
  121635. #ifdef SQLITE_OMIT_WSD
  121636. rc = sqlite3_wsd_init(4096, 24);
  121637. if( rc!=SQLITE_OK ){
  121638. return rc;
  121639. }
  121640. #endif
  121641. /* If the following assert() fails on some obscure processor/compiler
  121642. ** combination, the work-around is to set the correct pointer
  121643. ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
  121644. assert( SQLITE_PTRSIZE==sizeof(char*) );
  121645. /* If SQLite is already completely initialized, then this call
  121646. ** to sqlite3_initialize() should be a no-op. But the initialization
  121647. ** must be complete. So isInit must not be set until the very end
  121648. ** of this routine.
  121649. */
  121650. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  121651. /* Make sure the mutex subsystem is initialized. If unable to
  121652. ** initialize the mutex subsystem, return early with the error.
  121653. ** If the system is so sick that we are unable to allocate a mutex,
  121654. ** there is not much SQLite is going to be able to do.
  121655. **
  121656. ** The mutex subsystem must take care of serializing its own
  121657. ** initialization.
  121658. */
  121659. rc = sqlite3MutexInit();
  121660. if( rc ) return rc;
  121661. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  121662. ** This operation is protected by the STATIC_MASTER mutex. Note that
  121663. ** MutexAlloc() is called for a static mutex prior to initializing the
  121664. ** malloc subsystem - this implies that the allocation of a static
  121665. ** mutex must not require support from the malloc subsystem.
  121666. */
  121667. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  121668. sqlite3_mutex_enter(pMaster);
  121669. sqlite3GlobalConfig.isMutexInit = 1;
  121670. if( !sqlite3GlobalConfig.isMallocInit ){
  121671. rc = sqlite3MallocInit();
  121672. }
  121673. if( rc==SQLITE_OK ){
  121674. sqlite3GlobalConfig.isMallocInit = 1;
  121675. if( !sqlite3GlobalConfig.pInitMutex ){
  121676. sqlite3GlobalConfig.pInitMutex =
  121677. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  121678. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  121679. rc = SQLITE_NOMEM;
  121680. }
  121681. }
  121682. }
  121683. if( rc==SQLITE_OK ){
  121684. sqlite3GlobalConfig.nRefInitMutex++;
  121685. }
  121686. sqlite3_mutex_leave(pMaster);
  121687. /* If rc is not SQLITE_OK at this point, then either the malloc
  121688. ** subsystem could not be initialized or the system failed to allocate
  121689. ** the pInitMutex mutex. Return an error in either case. */
  121690. if( rc!=SQLITE_OK ){
  121691. return rc;
  121692. }
  121693. /* Do the rest of the initialization under the recursive mutex so
  121694. ** that we will be able to handle recursive calls into
  121695. ** sqlite3_initialize(). The recursive calls normally come through
  121696. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  121697. ** recursive calls might also be possible.
  121698. **
  121699. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  121700. ** to the xInit method, so the xInit method need not be threadsafe.
  121701. **
  121702. ** The following mutex is what serializes access to the appdef pcache xInit
  121703. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  121704. ** call to sqlite3PcacheInitialize().
  121705. */
  121706. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  121707. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  121708. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  121709. sqlite3GlobalConfig.inProgress = 1;
  121710. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  121711. sqlite3RegisterGlobalFunctions();
  121712. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  121713. rc = sqlite3PcacheInitialize();
  121714. }
  121715. if( rc==SQLITE_OK ){
  121716. sqlite3GlobalConfig.isPCacheInit = 1;
  121717. rc = sqlite3OsInit();
  121718. }
  121719. if( rc==SQLITE_OK ){
  121720. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  121721. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  121722. sqlite3GlobalConfig.isInit = 1;
  121723. #ifdef SQLITE_EXTRA_INIT
  121724. bRunExtraInit = 1;
  121725. #endif
  121726. }
  121727. sqlite3GlobalConfig.inProgress = 0;
  121728. }
  121729. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  121730. /* Go back under the static mutex and clean up the recursive
  121731. ** mutex to prevent a resource leak.
  121732. */
  121733. sqlite3_mutex_enter(pMaster);
  121734. sqlite3GlobalConfig.nRefInitMutex--;
  121735. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  121736. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  121737. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  121738. sqlite3GlobalConfig.pInitMutex = 0;
  121739. }
  121740. sqlite3_mutex_leave(pMaster);
  121741. /* The following is just a sanity check to make sure SQLite has
  121742. ** been compiled correctly. It is important to run this code, but
  121743. ** we don't want to run it too often and soak up CPU cycles for no
  121744. ** reason. So we run it once during initialization.
  121745. */
  121746. #ifndef NDEBUG
  121747. #ifndef SQLITE_OMIT_FLOATING_POINT
  121748. /* This section of code's only "output" is via assert() statements. */
  121749. if ( rc==SQLITE_OK ){
  121750. u64 x = (((u64)1)<<63)-1;
  121751. double y;
  121752. assert(sizeof(x)==8);
  121753. assert(sizeof(x)==sizeof(y));
  121754. memcpy(&y, &x, 8);
  121755. assert( sqlite3IsNaN(y) );
  121756. }
  121757. #endif
  121758. #endif
  121759. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  121760. ** compile-time option.
  121761. */
  121762. #ifdef SQLITE_EXTRA_INIT
  121763. if( bRunExtraInit ){
  121764. int SQLITE_EXTRA_INIT(const char*);
  121765. rc = SQLITE_EXTRA_INIT(0);
  121766. }
  121767. #endif
  121768. return rc;
  121769. }
  121770. /*
  121771. ** Undo the effects of sqlite3_initialize(). Must not be called while
  121772. ** there are outstanding database connections or memory allocations or
  121773. ** while any part of SQLite is otherwise in use in any thread. This
  121774. ** routine is not threadsafe. But it is safe to invoke this routine
  121775. ** on when SQLite is already shut down. If SQLite is already shut down
  121776. ** when this routine is invoked, then this routine is a harmless no-op.
  121777. */
  121778. SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
  121779. #ifdef SQLITE_OMIT_WSD
  121780. int rc = sqlite3_wsd_init(4096, 24);
  121781. if( rc!=SQLITE_OK ){
  121782. return rc;
  121783. }
  121784. #endif
  121785. if( sqlite3GlobalConfig.isInit ){
  121786. #ifdef SQLITE_EXTRA_SHUTDOWN
  121787. void SQLITE_EXTRA_SHUTDOWN(void);
  121788. SQLITE_EXTRA_SHUTDOWN();
  121789. #endif
  121790. sqlite3_os_end();
  121791. sqlite3_reset_auto_extension();
  121792. sqlite3GlobalConfig.isInit = 0;
  121793. }
  121794. if( sqlite3GlobalConfig.isPCacheInit ){
  121795. sqlite3PcacheShutdown();
  121796. sqlite3GlobalConfig.isPCacheInit = 0;
  121797. }
  121798. if( sqlite3GlobalConfig.isMallocInit ){
  121799. sqlite3MallocEnd();
  121800. sqlite3GlobalConfig.isMallocInit = 0;
  121801. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  121802. /* The heap subsystem has now been shutdown and these values are supposed
  121803. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  121804. ** which would rely on that heap subsystem; therefore, make sure these
  121805. ** values cannot refer to heap memory that was just invalidated when the
  121806. ** heap subsystem was shutdown. This is only done if the current call to
  121807. ** this function resulted in the heap subsystem actually being shutdown.
  121808. */
  121809. sqlite3_data_directory = 0;
  121810. sqlite3_temp_directory = 0;
  121811. #endif
  121812. }
  121813. if( sqlite3GlobalConfig.isMutexInit ){
  121814. sqlite3MutexEnd();
  121815. sqlite3GlobalConfig.isMutexInit = 0;
  121816. }
  121817. return SQLITE_OK;
  121818. }
  121819. /*
  121820. ** This API allows applications to modify the global configuration of
  121821. ** the SQLite library at run-time.
  121822. **
  121823. ** This routine should only be called when there are no outstanding
  121824. ** database connections or memory allocations. This routine is not
  121825. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  121826. ** behavior.
  121827. */
  121828. SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
  121829. va_list ap;
  121830. int rc = SQLITE_OK;
  121831. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  121832. ** the SQLite library is in use. */
  121833. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  121834. va_start(ap, op);
  121835. switch( op ){
  121836. /* Mutex configuration options are only available in a threadsafe
  121837. ** compile.
  121838. */
  121839. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
  121840. case SQLITE_CONFIG_SINGLETHREAD: {
  121841. /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
  121842. ** Single-thread. */
  121843. sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
  121844. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  121845. break;
  121846. }
  121847. #endif
  121848. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
  121849. case SQLITE_CONFIG_MULTITHREAD: {
  121850. /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
  121851. ** Multi-thread. */
  121852. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  121853. sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
  121854. break;
  121855. }
  121856. #endif
  121857. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
  121858. case SQLITE_CONFIG_SERIALIZED: {
  121859. /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
  121860. ** Serialized. */
  121861. sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
  121862. sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
  121863. break;
  121864. }
  121865. #endif
  121866. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
  121867. case SQLITE_CONFIG_MUTEX: {
  121868. /* Specify an alternative mutex implementation */
  121869. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  121870. break;
  121871. }
  121872. #endif
  121873. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
  121874. case SQLITE_CONFIG_GETMUTEX: {
  121875. /* Retrieve the current mutex implementation */
  121876. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  121877. break;
  121878. }
  121879. #endif
  121880. case SQLITE_CONFIG_MALLOC: {
  121881. /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
  121882. ** single argument which is a pointer to an instance of the
  121883. ** sqlite3_mem_methods structure. The argument specifies alternative
  121884. ** low-level memory allocation routines to be used in place of the memory
  121885. ** allocation routines built into SQLite. */
  121886. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  121887. break;
  121888. }
  121889. case SQLITE_CONFIG_GETMALLOC: {
  121890. /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
  121891. ** single argument which is a pointer to an instance of the
  121892. ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
  121893. ** filled with the currently defined memory allocation routines. */
  121894. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  121895. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  121896. break;
  121897. }
  121898. case SQLITE_CONFIG_MEMSTATUS: {
  121899. /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
  121900. ** single argument of type int, interpreted as a boolean, which enables
  121901. ** or disables the collection of memory allocation statistics. */
  121902. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  121903. break;
  121904. }
  121905. case SQLITE_CONFIG_SCRATCH: {
  121906. /* EVIDENCE-OF: R-08404-60887 There are three arguments to
  121907. ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
  121908. ** which the scratch allocations will be drawn, the size of each scratch
  121909. ** allocation (sz), and the maximum number of scratch allocations (N). */
  121910. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  121911. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  121912. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  121913. break;
  121914. }
  121915. case SQLITE_CONFIG_PAGECACHE: {
  121916. /* EVIDENCE-OF: R-31408-40510 There are three arguments to
  121917. ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
  121918. ** of each page buffer (sz), and the number of pages (N). */
  121919. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  121920. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  121921. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  121922. break;
  121923. }
  121924. case SQLITE_CONFIG_PCACHE_HDRSZ: {
  121925. /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
  121926. ** a single parameter which is a pointer to an integer and writes into
  121927. ** that integer the number of extra bytes per page required for each page
  121928. ** in SQLITE_CONFIG_PAGECACHE. */
  121929. *va_arg(ap, int*) =
  121930. sqlite3HeaderSizeBtree() +
  121931. sqlite3HeaderSizePcache() +
  121932. sqlite3HeaderSizePcache1();
  121933. break;
  121934. }
  121935. case SQLITE_CONFIG_PCACHE: {
  121936. /* no-op */
  121937. break;
  121938. }
  121939. case SQLITE_CONFIG_GETPCACHE: {
  121940. /* now an error */
  121941. rc = SQLITE_ERROR;
  121942. break;
  121943. }
  121944. case SQLITE_CONFIG_PCACHE2: {
  121945. /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
  121946. ** single argument which is a pointer to an sqlite3_pcache_methods2
  121947. ** object. This object specifies the interface to a custom page cache
  121948. ** implementation. */
  121949. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  121950. break;
  121951. }
  121952. case SQLITE_CONFIG_GETPCACHE2: {
  121953. /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
  121954. ** single argument which is a pointer to an sqlite3_pcache_methods2
  121955. ** object. SQLite copies of the current page cache implementation into
  121956. ** that object. */
  121957. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  121958. sqlite3PCacheSetDefault();
  121959. }
  121960. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  121961. break;
  121962. }
  121963. /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
  121964. ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
  121965. ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
  121966. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  121967. case SQLITE_CONFIG_HEAP: {
  121968. /* EVIDENCE-OF: R-19854-42126 There are three arguments to
  121969. ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
  121970. ** number of bytes in the memory buffer, and the minimum allocation size.
  121971. */
  121972. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  121973. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  121974. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  121975. if( sqlite3GlobalConfig.mnReq<1 ){
  121976. sqlite3GlobalConfig.mnReq = 1;
  121977. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  121978. /* cap min request size at 2^12 */
  121979. sqlite3GlobalConfig.mnReq = (1<<12);
  121980. }
  121981. if( sqlite3GlobalConfig.pHeap==0 ){
  121982. /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
  121983. ** is NULL, then SQLite reverts to using its default memory allocator
  121984. ** (the system malloc() implementation), undoing any prior invocation of
  121985. ** SQLITE_CONFIG_MALLOC.
  121986. **
  121987. ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
  121988. ** revert to its default implementation when sqlite3_initialize() is run
  121989. */
  121990. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  121991. }else{
  121992. /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
  121993. ** alternative memory allocator is engaged to handle all of SQLites
  121994. ** memory allocation needs. */
  121995. #ifdef SQLITE_ENABLE_MEMSYS3
  121996. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  121997. #endif
  121998. #ifdef SQLITE_ENABLE_MEMSYS5
  121999. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  122000. #endif
  122001. }
  122002. break;
  122003. }
  122004. #endif
  122005. case SQLITE_CONFIG_LOOKASIDE: {
  122006. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  122007. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  122008. break;
  122009. }
  122010. /* Record a pointer to the logger function and its first argument.
  122011. ** The default is NULL. Logging is disabled if the function pointer is
  122012. ** NULL.
  122013. */
  122014. case SQLITE_CONFIG_LOG: {
  122015. /* MSVC is picky about pulling func ptrs from va lists.
  122016. ** http://support.microsoft.com/kb/47961
  122017. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  122018. */
  122019. typedef void(*LOGFUNC_t)(void*,int,const char*);
  122020. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  122021. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  122022. break;
  122023. }
  122024. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  122025. ** can be changed at start-time using the
  122026. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  122027. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  122028. */
  122029. case SQLITE_CONFIG_URI: {
  122030. /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
  122031. ** argument of type int. If non-zero, then URI handling is globally
  122032. ** enabled. If the parameter is zero, then URI handling is globally
  122033. ** disabled. */
  122034. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  122035. break;
  122036. }
  122037. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  122038. /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
  122039. ** option takes a single integer argument which is interpreted as a
  122040. ** boolean in order to enable or disable the use of covering indices for
  122041. ** full table scans in the query optimizer. */
  122042. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  122043. break;
  122044. }
  122045. #ifdef SQLITE_ENABLE_SQLLOG
  122046. case SQLITE_CONFIG_SQLLOG: {
  122047. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  122048. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  122049. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  122050. break;
  122051. }
  122052. #endif
  122053. case SQLITE_CONFIG_MMAP_SIZE: {
  122054. /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
  122055. ** integer (sqlite3_int64) values that are the default mmap size limit
  122056. ** (the default setting for PRAGMA mmap_size) and the maximum allowed
  122057. ** mmap size limit. */
  122058. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  122059. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  122060. /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
  122061. ** negative, then that argument is changed to its compile-time default.
  122062. **
  122063. ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
  122064. ** silently truncated if necessary so that it does not exceed the
  122065. ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
  122066. ** compile-time option.
  122067. */
  122068. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  122069. mxMmap = SQLITE_MAX_MMAP_SIZE;
  122070. }
  122071. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  122072. if( szMmap>mxMmap) szMmap = mxMmap;
  122073. sqlite3GlobalConfig.mxMmap = mxMmap;
  122074. sqlite3GlobalConfig.szMmap = szMmap;
  122075. break;
  122076. }
  122077. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
  122078. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  122079. /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
  122080. ** unsigned integer value that specifies the maximum size of the created
  122081. ** heap. */
  122082. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  122083. break;
  122084. }
  122085. #endif
  122086. case SQLITE_CONFIG_PMASZ: {
  122087. sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
  122088. break;
  122089. }
  122090. default: {
  122091. rc = SQLITE_ERROR;
  122092. break;
  122093. }
  122094. }
  122095. va_end(ap);
  122096. return rc;
  122097. }
  122098. /*
  122099. ** Set up the lookaside buffers for a database connection.
  122100. ** Return SQLITE_OK on success.
  122101. ** If lookaside is already active, return SQLITE_BUSY.
  122102. **
  122103. ** The sz parameter is the number of bytes in each lookaside slot.
  122104. ** The cnt parameter is the number of slots. If pStart is NULL the
  122105. ** space for the lookaside memory is obtained from sqlite3_malloc().
  122106. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  122107. ** the lookaside memory.
  122108. */
  122109. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  122110. #ifndef SQLITE_OMIT_LOOKASIDE
  122111. void *pStart;
  122112. if( db->lookaside.nOut ){
  122113. return SQLITE_BUSY;
  122114. }
  122115. /* Free any existing lookaside buffer for this handle before
  122116. ** allocating a new one so we don't have to have space for
  122117. ** both at the same time.
  122118. */
  122119. if( db->lookaside.bMalloced ){
  122120. sqlite3_free(db->lookaside.pStart);
  122121. }
  122122. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  122123. ** than a pointer to be useful.
  122124. */
  122125. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  122126. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  122127. if( cnt<0 ) cnt = 0;
  122128. if( sz==0 || cnt==0 ){
  122129. sz = 0;
  122130. pStart = 0;
  122131. }else if( pBuf==0 ){
  122132. sqlite3BeginBenignMalloc();
  122133. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  122134. sqlite3EndBenignMalloc();
  122135. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  122136. }else{
  122137. pStart = pBuf;
  122138. }
  122139. db->lookaside.pStart = pStart;
  122140. db->lookaside.pFree = 0;
  122141. db->lookaside.sz = (u16)sz;
  122142. if( pStart ){
  122143. int i;
  122144. LookasideSlot *p;
  122145. assert( sz > (int)sizeof(LookasideSlot*) );
  122146. p = (LookasideSlot*)pStart;
  122147. for(i=cnt-1; i>=0; i--){
  122148. p->pNext = db->lookaside.pFree;
  122149. db->lookaside.pFree = p;
  122150. p = (LookasideSlot*)&((u8*)p)[sz];
  122151. }
  122152. db->lookaside.pEnd = p;
  122153. db->lookaside.bEnabled = 1;
  122154. db->lookaside.bMalloced = pBuf==0 ?1:0;
  122155. }else{
  122156. db->lookaside.pStart = db;
  122157. db->lookaside.pEnd = db;
  122158. db->lookaside.bEnabled = 0;
  122159. db->lookaside.bMalloced = 0;
  122160. }
  122161. #endif /* SQLITE_OMIT_LOOKASIDE */
  122162. return SQLITE_OK;
  122163. }
  122164. /*
  122165. ** Return the mutex associated with a database connection.
  122166. */
  122167. SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
  122168. #ifdef SQLITE_ENABLE_API_ARMOR
  122169. if( !sqlite3SafetyCheckOk(db) ){
  122170. (void)SQLITE_MISUSE_BKPT;
  122171. return 0;
  122172. }
  122173. #endif
  122174. return db->mutex;
  122175. }
  122176. /*
  122177. ** Free up as much memory as we can from the given database
  122178. ** connection.
  122179. */
  122180. SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
  122181. int i;
  122182. #ifdef SQLITE_ENABLE_API_ARMOR
  122183. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  122184. #endif
  122185. sqlite3_mutex_enter(db->mutex);
  122186. sqlite3BtreeEnterAll(db);
  122187. for(i=0; i<db->nDb; i++){
  122188. Btree *pBt = db->aDb[i].pBt;
  122189. if( pBt ){
  122190. Pager *pPager = sqlite3BtreePager(pBt);
  122191. sqlite3PagerShrink(pPager);
  122192. }
  122193. }
  122194. sqlite3BtreeLeaveAll(db);
  122195. sqlite3_mutex_leave(db->mutex);
  122196. return SQLITE_OK;
  122197. }
  122198. /*
  122199. ** Configuration settings for an individual database connection
  122200. */
  122201. SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
  122202. va_list ap;
  122203. int rc;
  122204. va_start(ap, op);
  122205. switch( op ){
  122206. case SQLITE_DBCONFIG_LOOKASIDE: {
  122207. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  122208. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  122209. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  122210. rc = setupLookaside(db, pBuf, sz, cnt);
  122211. break;
  122212. }
  122213. default: {
  122214. static const struct {
  122215. int op; /* The opcode */
  122216. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  122217. } aFlagOp[] = {
  122218. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  122219. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  122220. };
  122221. unsigned int i;
  122222. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  122223. for(i=0; i<ArraySize(aFlagOp); i++){
  122224. if( aFlagOp[i].op==op ){
  122225. int onoff = va_arg(ap, int);
  122226. int *pRes = va_arg(ap, int*);
  122227. int oldFlags = db->flags;
  122228. if( onoff>0 ){
  122229. db->flags |= aFlagOp[i].mask;
  122230. }else if( onoff==0 ){
  122231. db->flags &= ~aFlagOp[i].mask;
  122232. }
  122233. if( oldFlags!=db->flags ){
  122234. sqlite3ExpirePreparedStatements(db);
  122235. }
  122236. if( pRes ){
  122237. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  122238. }
  122239. rc = SQLITE_OK;
  122240. break;
  122241. }
  122242. }
  122243. break;
  122244. }
  122245. }
  122246. va_end(ap);
  122247. return rc;
  122248. }
  122249. /*
  122250. ** Return true if the buffer z[0..n-1] contains all spaces.
  122251. */
  122252. static int allSpaces(const char *z, int n){
  122253. while( n>0 && z[n-1]==' ' ){ n--; }
  122254. return n==0;
  122255. }
  122256. /*
  122257. ** This is the default collating function named "BINARY" which is always
  122258. ** available.
  122259. **
  122260. ** If the padFlag argument is not NULL then space padding at the end
  122261. ** of strings is ignored. This implements the RTRIM collation.
  122262. */
  122263. static int binCollFunc(
  122264. void *padFlag,
  122265. int nKey1, const void *pKey1,
  122266. int nKey2, const void *pKey2
  122267. ){
  122268. int rc, n;
  122269. n = nKey1<nKey2 ? nKey1 : nKey2;
  122270. /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
  122271. ** strings byte by byte using the memcmp() function from the standard C
  122272. ** library. */
  122273. rc = memcmp(pKey1, pKey2, n);
  122274. if( rc==0 ){
  122275. if( padFlag
  122276. && allSpaces(((char*)pKey1)+n, nKey1-n)
  122277. && allSpaces(((char*)pKey2)+n, nKey2-n)
  122278. ){
  122279. /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
  122280. ** spaces at the end of either string do not change the result. In other
  122281. ** words, strings will compare equal to one another as long as they
  122282. ** differ only in the number of spaces at the end.
  122283. */
  122284. }else{
  122285. rc = nKey1 - nKey2;
  122286. }
  122287. }
  122288. return rc;
  122289. }
  122290. /*
  122291. ** Another built-in collating sequence: NOCASE.
  122292. **
  122293. ** This collating sequence is intended to be used for "case independent
  122294. ** comparison". SQLite's knowledge of upper and lower case equivalents
  122295. ** extends only to the 26 characters used in the English language.
  122296. **
  122297. ** At the moment there is only a UTF-8 implementation.
  122298. */
  122299. static int nocaseCollatingFunc(
  122300. void *NotUsed,
  122301. int nKey1, const void *pKey1,
  122302. int nKey2, const void *pKey2
  122303. ){
  122304. int r = sqlite3StrNICmp(
  122305. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  122306. UNUSED_PARAMETER(NotUsed);
  122307. if( 0==r ){
  122308. r = nKey1-nKey2;
  122309. }
  122310. return r;
  122311. }
  122312. /*
  122313. ** Return the ROWID of the most recent insert
  122314. */
  122315. SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
  122316. #ifdef SQLITE_ENABLE_API_ARMOR
  122317. if( !sqlite3SafetyCheckOk(db) ){
  122318. (void)SQLITE_MISUSE_BKPT;
  122319. return 0;
  122320. }
  122321. #endif
  122322. return db->lastRowid;
  122323. }
  122324. /*
  122325. ** Return the number of changes in the most recent call to sqlite3_exec().
  122326. */
  122327. SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
  122328. #ifdef SQLITE_ENABLE_API_ARMOR
  122329. if( !sqlite3SafetyCheckOk(db) ){
  122330. (void)SQLITE_MISUSE_BKPT;
  122331. return 0;
  122332. }
  122333. #endif
  122334. return db->nChange;
  122335. }
  122336. /*
  122337. ** Return the number of changes since the database handle was opened.
  122338. */
  122339. SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
  122340. #ifdef SQLITE_ENABLE_API_ARMOR
  122341. if( !sqlite3SafetyCheckOk(db) ){
  122342. (void)SQLITE_MISUSE_BKPT;
  122343. return 0;
  122344. }
  122345. #endif
  122346. return db->nTotalChange;
  122347. }
  122348. /*
  122349. ** Close all open savepoints. This function only manipulates fields of the
  122350. ** database handle object, it does not close any savepoints that may be open
  122351. ** at the b-tree/pager level.
  122352. */
  122353. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  122354. while( db->pSavepoint ){
  122355. Savepoint *pTmp = db->pSavepoint;
  122356. db->pSavepoint = pTmp->pNext;
  122357. sqlite3DbFree(db, pTmp);
  122358. }
  122359. db->nSavepoint = 0;
  122360. db->nStatement = 0;
  122361. db->isTransactionSavepoint = 0;
  122362. }
  122363. /*
  122364. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  122365. ** if this is not the last copy of the function, do not invoke it. Multiple
  122366. ** copies of a single function are created when create_function() is called
  122367. ** with SQLITE_ANY as the encoding.
  122368. */
  122369. static void functionDestroy(sqlite3 *db, FuncDef *p){
  122370. FuncDestructor *pDestructor = p->pDestructor;
  122371. if( pDestructor ){
  122372. pDestructor->nRef--;
  122373. if( pDestructor->nRef==0 ){
  122374. pDestructor->xDestroy(pDestructor->pUserData);
  122375. sqlite3DbFree(db, pDestructor);
  122376. }
  122377. }
  122378. }
  122379. /*
  122380. ** Disconnect all sqlite3_vtab objects that belong to database connection
  122381. ** db. This is called when db is being closed.
  122382. */
  122383. static void disconnectAllVtab(sqlite3 *db){
  122384. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122385. int i;
  122386. sqlite3BtreeEnterAll(db);
  122387. for(i=0; i<db->nDb; i++){
  122388. Schema *pSchema = db->aDb[i].pSchema;
  122389. if( db->aDb[i].pSchema ){
  122390. HashElem *p;
  122391. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  122392. Table *pTab = (Table *)sqliteHashData(p);
  122393. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  122394. }
  122395. }
  122396. }
  122397. sqlite3VtabUnlockList(db);
  122398. sqlite3BtreeLeaveAll(db);
  122399. #else
  122400. UNUSED_PARAMETER(db);
  122401. #endif
  122402. }
  122403. /*
  122404. ** Return TRUE if database connection db has unfinalized prepared
  122405. ** statements or unfinished sqlite3_backup objects.
  122406. */
  122407. static int connectionIsBusy(sqlite3 *db){
  122408. int j;
  122409. assert( sqlite3_mutex_held(db->mutex) );
  122410. if( db->pVdbe ) return 1;
  122411. for(j=0; j<db->nDb; j++){
  122412. Btree *pBt = db->aDb[j].pBt;
  122413. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  122414. }
  122415. return 0;
  122416. }
  122417. /*
  122418. ** Close an existing SQLite database
  122419. */
  122420. static int sqlite3Close(sqlite3 *db, int forceZombie){
  122421. if( !db ){
  122422. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  122423. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  122424. return SQLITE_OK;
  122425. }
  122426. if( !sqlite3SafetyCheckSickOrOk(db) ){
  122427. return SQLITE_MISUSE_BKPT;
  122428. }
  122429. sqlite3_mutex_enter(db->mutex);
  122430. /* Force xDisconnect calls on all virtual tables */
  122431. disconnectAllVtab(db);
  122432. /* If a transaction is open, the disconnectAllVtab() call above
  122433. ** will not have called the xDisconnect() method on any virtual
  122434. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  122435. ** call will do so. We need to do this before the check for active
  122436. ** SQL statements below, as the v-table implementation may be storing
  122437. ** some prepared statements internally.
  122438. */
  122439. sqlite3VtabRollback(db);
  122440. /* Legacy behavior (sqlite3_close() behavior) is to return
  122441. ** SQLITE_BUSY if the connection can not be closed immediately.
  122442. */
  122443. if( !forceZombie && connectionIsBusy(db) ){
  122444. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  122445. "statements or unfinished backups");
  122446. sqlite3_mutex_leave(db->mutex);
  122447. return SQLITE_BUSY;
  122448. }
  122449. #ifdef SQLITE_ENABLE_SQLLOG
  122450. if( sqlite3GlobalConfig.xSqllog ){
  122451. /* Closing the handle. Fourth parameter is passed the value 2. */
  122452. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  122453. }
  122454. #endif
  122455. /* Convert the connection into a zombie and then close it.
  122456. */
  122457. db->magic = SQLITE_MAGIC_ZOMBIE;
  122458. sqlite3LeaveMutexAndCloseZombie(db);
  122459. return SQLITE_OK;
  122460. }
  122461. /*
  122462. ** Two variations on the public interface for closing a database
  122463. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  122464. ** leaves the connection option if there are unfinalized prepared
  122465. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  122466. ** version forces the connection to become a zombie if there are
  122467. ** unclosed resources, and arranges for deallocation when the last
  122468. ** prepare statement or sqlite3_backup closes.
  122469. */
  122470. SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  122471. SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  122472. /*
  122473. ** Close the mutex on database connection db.
  122474. **
  122475. ** Furthermore, if database connection db is a zombie (meaning that there
  122476. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  122477. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  122478. ** finished, then free all resources.
  122479. */
  122480. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  122481. HashElem *i; /* Hash table iterator */
  122482. int j;
  122483. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  122484. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  122485. ** then just leave the mutex and return.
  122486. */
  122487. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  122488. sqlite3_mutex_leave(db->mutex);
  122489. return;
  122490. }
  122491. /* If we reach this point, it means that the database connection has
  122492. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  122493. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  122494. ** go ahead and free all resources.
  122495. */
  122496. /* If a transaction is open, roll it back. This also ensures that if
  122497. ** any database schemas have been modified by an uncommitted transaction
  122498. ** they are reset. And that the required b-tree mutex is held to make
  122499. ** the pager rollback and schema reset an atomic operation. */
  122500. sqlite3RollbackAll(db, SQLITE_OK);
  122501. /* Free any outstanding Savepoint structures. */
  122502. sqlite3CloseSavepoints(db);
  122503. /* Close all database connections */
  122504. for(j=0; j<db->nDb; j++){
  122505. struct Db *pDb = &db->aDb[j];
  122506. if( pDb->pBt ){
  122507. sqlite3BtreeClose(pDb->pBt);
  122508. pDb->pBt = 0;
  122509. if( j!=1 ){
  122510. pDb->pSchema = 0;
  122511. }
  122512. }
  122513. }
  122514. /* Clear the TEMP schema separately and last */
  122515. if( db->aDb[1].pSchema ){
  122516. sqlite3SchemaClear(db->aDb[1].pSchema);
  122517. }
  122518. sqlite3VtabUnlockList(db);
  122519. /* Free up the array of auxiliary databases */
  122520. sqlite3CollapseDatabaseArray(db);
  122521. assert( db->nDb<=2 );
  122522. assert( db->aDb==db->aDbStatic );
  122523. /* Tell the code in notify.c that the connection no longer holds any
  122524. ** locks and does not require any further unlock-notify callbacks.
  122525. */
  122526. sqlite3ConnectionClosed(db);
  122527. for(j=0; j<ArraySize(db->aFunc.a); j++){
  122528. FuncDef *pNext, *pHash, *p;
  122529. for(p=db->aFunc.a[j]; p; p=pHash){
  122530. pHash = p->pHash;
  122531. while( p ){
  122532. functionDestroy(db, p);
  122533. pNext = p->pNext;
  122534. sqlite3DbFree(db, p);
  122535. p = pNext;
  122536. }
  122537. }
  122538. }
  122539. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  122540. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  122541. /* Invoke any destructors registered for collation sequence user data. */
  122542. for(j=0; j<3; j++){
  122543. if( pColl[j].xDel ){
  122544. pColl[j].xDel(pColl[j].pUser);
  122545. }
  122546. }
  122547. sqlite3DbFree(db, pColl);
  122548. }
  122549. sqlite3HashClear(&db->aCollSeq);
  122550. #ifndef SQLITE_OMIT_VIRTUALTABLE
  122551. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  122552. Module *pMod = (Module *)sqliteHashData(i);
  122553. if( pMod->xDestroy ){
  122554. pMod->xDestroy(pMod->pAux);
  122555. }
  122556. sqlite3DbFree(db, pMod);
  122557. }
  122558. sqlite3HashClear(&db->aModule);
  122559. #endif
  122560. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  122561. sqlite3ValueFree(db->pErr);
  122562. sqlite3CloseExtensions(db);
  122563. #if SQLITE_USER_AUTHENTICATION
  122564. sqlite3_free(db->auth.zAuthUser);
  122565. sqlite3_free(db->auth.zAuthPW);
  122566. #endif
  122567. db->magic = SQLITE_MAGIC_ERROR;
  122568. /* The temp-database schema is allocated differently from the other schema
  122569. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  122570. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  122571. ** the same sqliteMalloc() as the one that allocates the database
  122572. ** structure?
  122573. */
  122574. sqlite3DbFree(db, db->aDb[1].pSchema);
  122575. sqlite3_mutex_leave(db->mutex);
  122576. db->magic = SQLITE_MAGIC_CLOSED;
  122577. sqlite3_mutex_free(db->mutex);
  122578. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  122579. if( db->lookaside.bMalloced ){
  122580. sqlite3_free(db->lookaside.pStart);
  122581. }
  122582. sqlite3_free(db);
  122583. }
  122584. /*
  122585. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  122586. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  122587. ** breaker") and made to return tripCode if there are any further
  122588. ** attempts to use that cursor. Read cursors remain open and valid
  122589. ** but are "saved" in case the table pages are moved around.
  122590. */
  122591. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  122592. int i;
  122593. int inTrans = 0;
  122594. int schemaChange;
  122595. assert( sqlite3_mutex_held(db->mutex) );
  122596. sqlite3BeginBenignMalloc();
  122597. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  122598. ** This is important in case the transaction being rolled back has
  122599. ** modified the database schema. If the b-tree mutexes are not taken
  122600. ** here, then another shared-cache connection might sneak in between
  122601. ** the database rollback and schema reset, which can cause false
  122602. ** corruption reports in some cases. */
  122603. sqlite3BtreeEnterAll(db);
  122604. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  122605. for(i=0; i<db->nDb; i++){
  122606. Btree *p = db->aDb[i].pBt;
  122607. if( p ){
  122608. if( sqlite3BtreeIsInTrans(p) ){
  122609. inTrans = 1;
  122610. }
  122611. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  122612. }
  122613. }
  122614. sqlite3VtabRollback(db);
  122615. sqlite3EndBenignMalloc();
  122616. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  122617. sqlite3ExpirePreparedStatements(db);
  122618. sqlite3ResetAllSchemasOfConnection(db);
  122619. }
  122620. sqlite3BtreeLeaveAll(db);
  122621. /* Any deferred constraint violations have now been resolved. */
  122622. db->nDeferredCons = 0;
  122623. db->nDeferredImmCons = 0;
  122624. db->flags &= ~SQLITE_DeferFKs;
  122625. /* If one has been configured, invoke the rollback-hook callback */
  122626. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  122627. db->xRollbackCallback(db->pRollbackArg);
  122628. }
  122629. }
  122630. /*
  122631. ** Return a static string containing the name corresponding to the error code
  122632. ** specified in the argument.
  122633. */
  122634. #if defined(SQLITE_NEED_ERR_NAME)
  122635. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  122636. const char *zName = 0;
  122637. int i, origRc = rc;
  122638. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  122639. switch( rc ){
  122640. case SQLITE_OK: zName = "SQLITE_OK"; break;
  122641. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  122642. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  122643. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  122644. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  122645. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  122646. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  122647. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  122648. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  122649. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  122650. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  122651. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  122652. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  122653. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  122654. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  122655. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  122656. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  122657. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  122658. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  122659. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  122660. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  122661. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  122662. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  122663. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  122664. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  122665. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  122666. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  122667. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  122668. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  122669. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  122670. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  122671. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  122672. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  122673. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  122674. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  122675. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  122676. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  122677. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  122678. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  122679. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  122680. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  122681. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  122682. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  122683. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  122684. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  122685. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  122686. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  122687. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  122688. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  122689. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  122690. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  122691. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  122692. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  122693. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  122694. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  122695. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  122696. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  122697. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  122698. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  122699. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  122700. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  122701. case SQLITE_CONSTRAINT_FOREIGNKEY:
  122702. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  122703. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  122704. case SQLITE_CONSTRAINT_PRIMARYKEY:
  122705. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  122706. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  122707. case SQLITE_CONSTRAINT_COMMITHOOK:
  122708. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  122709. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  122710. case SQLITE_CONSTRAINT_FUNCTION:
  122711. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  122712. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  122713. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  122714. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  122715. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  122716. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  122717. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  122718. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  122719. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  122720. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  122721. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  122722. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  122723. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  122724. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  122725. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  122726. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  122727. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  122728. }
  122729. }
  122730. if( zName==0 ){
  122731. static char zBuf[50];
  122732. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  122733. zName = zBuf;
  122734. }
  122735. return zName;
  122736. }
  122737. #endif
  122738. /*
  122739. ** Return a static string that describes the kind of error specified in the
  122740. ** argument.
  122741. */
  122742. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  122743. static const char* const aMsg[] = {
  122744. /* SQLITE_OK */ "not an error",
  122745. /* SQLITE_ERROR */ "SQL logic error or missing database",
  122746. /* SQLITE_INTERNAL */ 0,
  122747. /* SQLITE_PERM */ "access permission denied",
  122748. /* SQLITE_ABORT */ "callback requested query abort",
  122749. /* SQLITE_BUSY */ "database is locked",
  122750. /* SQLITE_LOCKED */ "database table is locked",
  122751. /* SQLITE_NOMEM */ "out of memory",
  122752. /* SQLITE_READONLY */ "attempt to write a readonly database",
  122753. /* SQLITE_INTERRUPT */ "interrupted",
  122754. /* SQLITE_IOERR */ "disk I/O error",
  122755. /* SQLITE_CORRUPT */ "database disk image is malformed",
  122756. /* SQLITE_NOTFOUND */ "unknown operation",
  122757. /* SQLITE_FULL */ "database or disk is full",
  122758. /* SQLITE_CANTOPEN */ "unable to open database file",
  122759. /* SQLITE_PROTOCOL */ "locking protocol",
  122760. /* SQLITE_EMPTY */ "table contains no data",
  122761. /* SQLITE_SCHEMA */ "database schema has changed",
  122762. /* SQLITE_TOOBIG */ "string or blob too big",
  122763. /* SQLITE_CONSTRAINT */ "constraint failed",
  122764. /* SQLITE_MISMATCH */ "datatype mismatch",
  122765. /* SQLITE_MISUSE */ "library routine called out of sequence",
  122766. /* SQLITE_NOLFS */ "large file support is disabled",
  122767. /* SQLITE_AUTH */ "authorization denied",
  122768. /* SQLITE_FORMAT */ "auxiliary database format error",
  122769. /* SQLITE_RANGE */ "bind or column index out of range",
  122770. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  122771. };
  122772. const char *zErr = "unknown error";
  122773. switch( rc ){
  122774. case SQLITE_ABORT_ROLLBACK: {
  122775. zErr = "abort due to ROLLBACK";
  122776. break;
  122777. }
  122778. default: {
  122779. rc &= 0xff;
  122780. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  122781. zErr = aMsg[rc];
  122782. }
  122783. break;
  122784. }
  122785. }
  122786. return zErr;
  122787. }
  122788. /*
  122789. ** This routine implements a busy callback that sleeps and tries
  122790. ** again until a timeout value is reached. The timeout value is
  122791. ** an integer number of milliseconds passed in as the first
  122792. ** argument.
  122793. */
  122794. static int sqliteDefaultBusyCallback(
  122795. void *ptr, /* Database connection */
  122796. int count /* Number of times table has been busy */
  122797. ){
  122798. #if SQLITE_OS_WIN || HAVE_USLEEP
  122799. static const u8 delays[] =
  122800. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  122801. static const u8 totals[] =
  122802. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  122803. # define NDELAY ArraySize(delays)
  122804. sqlite3 *db = (sqlite3 *)ptr;
  122805. int timeout = db->busyTimeout;
  122806. int delay, prior;
  122807. assert( count>=0 );
  122808. if( count < NDELAY ){
  122809. delay = delays[count];
  122810. prior = totals[count];
  122811. }else{
  122812. delay = delays[NDELAY-1];
  122813. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  122814. }
  122815. if( prior + delay > timeout ){
  122816. delay = timeout - prior;
  122817. if( delay<=0 ) return 0;
  122818. }
  122819. sqlite3OsSleep(db->pVfs, delay*1000);
  122820. return 1;
  122821. #else
  122822. sqlite3 *db = (sqlite3 *)ptr;
  122823. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  122824. if( (count+1)*1000 > timeout ){
  122825. return 0;
  122826. }
  122827. sqlite3OsSleep(db->pVfs, 1000000);
  122828. return 1;
  122829. #endif
  122830. }
  122831. /*
  122832. ** Invoke the given busy handler.
  122833. **
  122834. ** This routine is called when an operation failed with a lock.
  122835. ** If this routine returns non-zero, the lock is retried. If it
  122836. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  122837. */
  122838. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  122839. int rc;
  122840. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  122841. rc = p->xFunc(p->pArg, p->nBusy);
  122842. if( rc==0 ){
  122843. p->nBusy = -1;
  122844. }else{
  122845. p->nBusy++;
  122846. }
  122847. return rc;
  122848. }
  122849. /*
  122850. ** This routine sets the busy callback for an Sqlite database to the
  122851. ** given callback function with the given argument.
  122852. */
  122853. SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
  122854. sqlite3 *db,
  122855. int (*xBusy)(void*,int),
  122856. void *pArg
  122857. ){
  122858. #ifdef SQLITE_ENABLE_API_ARMOR
  122859. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  122860. #endif
  122861. sqlite3_mutex_enter(db->mutex);
  122862. db->busyHandler.xFunc = xBusy;
  122863. db->busyHandler.pArg = pArg;
  122864. db->busyHandler.nBusy = 0;
  122865. db->busyTimeout = 0;
  122866. sqlite3_mutex_leave(db->mutex);
  122867. return SQLITE_OK;
  122868. }
  122869. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  122870. /*
  122871. ** This routine sets the progress callback for an Sqlite database to the
  122872. ** given callback function with the given argument. The progress callback will
  122873. ** be invoked every nOps opcodes.
  122874. */
  122875. SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
  122876. sqlite3 *db,
  122877. int nOps,
  122878. int (*xProgress)(void*),
  122879. void *pArg
  122880. ){
  122881. #ifdef SQLITE_ENABLE_API_ARMOR
  122882. if( !sqlite3SafetyCheckOk(db) ){
  122883. (void)SQLITE_MISUSE_BKPT;
  122884. return;
  122885. }
  122886. #endif
  122887. sqlite3_mutex_enter(db->mutex);
  122888. if( nOps>0 ){
  122889. db->xProgress = xProgress;
  122890. db->nProgressOps = (unsigned)nOps;
  122891. db->pProgressArg = pArg;
  122892. }else{
  122893. db->xProgress = 0;
  122894. db->nProgressOps = 0;
  122895. db->pProgressArg = 0;
  122896. }
  122897. sqlite3_mutex_leave(db->mutex);
  122898. }
  122899. #endif
  122900. /*
  122901. ** This routine installs a default busy handler that waits for the
  122902. ** specified number of milliseconds before returning 0.
  122903. */
  122904. SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
  122905. #ifdef SQLITE_ENABLE_API_ARMOR
  122906. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  122907. #endif
  122908. if( ms>0 ){
  122909. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  122910. db->busyTimeout = ms;
  122911. }else{
  122912. sqlite3_busy_handler(db, 0, 0);
  122913. }
  122914. return SQLITE_OK;
  122915. }
  122916. /*
  122917. ** Cause any pending operation to stop at its earliest opportunity.
  122918. */
  122919. SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
  122920. #ifdef SQLITE_ENABLE_API_ARMOR
  122921. if( !sqlite3SafetyCheckOk(db) ){
  122922. (void)SQLITE_MISUSE_BKPT;
  122923. return;
  122924. }
  122925. #endif
  122926. db->u1.isInterrupted = 1;
  122927. }
  122928. /*
  122929. ** This function is exactly the same as sqlite3_create_function(), except
  122930. ** that it is designed to be called by internal code. The difference is
  122931. ** that if a malloc() fails in sqlite3_create_function(), an error code
  122932. ** is returned and the mallocFailed flag cleared.
  122933. */
  122934. SQLITE_PRIVATE int sqlite3CreateFunc(
  122935. sqlite3 *db,
  122936. const char *zFunctionName,
  122937. int nArg,
  122938. int enc,
  122939. void *pUserData,
  122940. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  122941. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  122942. void (*xFinal)(sqlite3_context*),
  122943. FuncDestructor *pDestructor
  122944. ){
  122945. FuncDef *p;
  122946. int nName;
  122947. int extraFlags;
  122948. assert( sqlite3_mutex_held(db->mutex) );
  122949. if( zFunctionName==0 ||
  122950. (xFunc && (xFinal || xStep)) ||
  122951. (!xFunc && (xFinal && !xStep)) ||
  122952. (!xFunc && (!xFinal && xStep)) ||
  122953. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  122954. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  122955. return SQLITE_MISUSE_BKPT;
  122956. }
  122957. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  122958. extraFlags = enc & SQLITE_DETERMINISTIC;
  122959. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  122960. #ifndef SQLITE_OMIT_UTF16
  122961. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  122962. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  122963. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  122964. **
  122965. ** If SQLITE_ANY is specified, add three versions of the function
  122966. ** to the hash table.
  122967. */
  122968. if( enc==SQLITE_UTF16 ){
  122969. enc = SQLITE_UTF16NATIVE;
  122970. }else if( enc==SQLITE_ANY ){
  122971. int rc;
  122972. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  122973. pUserData, xFunc, xStep, xFinal, pDestructor);
  122974. if( rc==SQLITE_OK ){
  122975. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  122976. pUserData, xFunc, xStep, xFinal, pDestructor);
  122977. }
  122978. if( rc!=SQLITE_OK ){
  122979. return rc;
  122980. }
  122981. enc = SQLITE_UTF16BE;
  122982. }
  122983. #else
  122984. enc = SQLITE_UTF8;
  122985. #endif
  122986. /* Check if an existing function is being overridden or deleted. If so,
  122987. ** and there are active VMs, then return SQLITE_BUSY. If a function
  122988. ** is being overridden/deleted but there are no active VMs, allow the
  122989. ** operation to continue but invalidate all precompiled statements.
  122990. */
  122991. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  122992. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  122993. if( db->nVdbeActive ){
  122994. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  122995. "unable to delete/modify user-function due to active statements");
  122996. assert( !db->mallocFailed );
  122997. return SQLITE_BUSY;
  122998. }else{
  122999. sqlite3ExpirePreparedStatements(db);
  123000. }
  123001. }
  123002. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  123003. assert(p || db->mallocFailed);
  123004. if( !p ){
  123005. return SQLITE_NOMEM;
  123006. }
  123007. /* If an older version of the function with a configured destructor is
  123008. ** being replaced invoke the destructor function here. */
  123009. functionDestroy(db, p);
  123010. if( pDestructor ){
  123011. pDestructor->nRef++;
  123012. }
  123013. p->pDestructor = pDestructor;
  123014. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  123015. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  123016. p->xFunc = xFunc;
  123017. p->xStep = xStep;
  123018. p->xFinalize = xFinal;
  123019. p->pUserData = pUserData;
  123020. p->nArg = (u16)nArg;
  123021. return SQLITE_OK;
  123022. }
  123023. /*
  123024. ** Create new user functions.
  123025. */
  123026. SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
  123027. sqlite3 *db,
  123028. const char *zFunc,
  123029. int nArg,
  123030. int enc,
  123031. void *p,
  123032. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  123033. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  123034. void (*xFinal)(sqlite3_context*)
  123035. ){
  123036. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  123037. xFinal, 0);
  123038. }
  123039. SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
  123040. sqlite3 *db,
  123041. const char *zFunc,
  123042. int nArg,
  123043. int enc,
  123044. void *p,
  123045. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  123046. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  123047. void (*xFinal)(sqlite3_context*),
  123048. void (*xDestroy)(void *)
  123049. ){
  123050. int rc = SQLITE_ERROR;
  123051. FuncDestructor *pArg = 0;
  123052. #ifdef SQLITE_ENABLE_API_ARMOR
  123053. if( !sqlite3SafetyCheckOk(db) ){
  123054. return SQLITE_MISUSE_BKPT;
  123055. }
  123056. #endif
  123057. sqlite3_mutex_enter(db->mutex);
  123058. if( xDestroy ){
  123059. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  123060. if( !pArg ){
  123061. xDestroy(p);
  123062. goto out;
  123063. }
  123064. pArg->xDestroy = xDestroy;
  123065. pArg->pUserData = p;
  123066. }
  123067. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  123068. if( pArg && pArg->nRef==0 ){
  123069. assert( rc!=SQLITE_OK );
  123070. xDestroy(p);
  123071. sqlite3DbFree(db, pArg);
  123072. }
  123073. out:
  123074. rc = sqlite3ApiExit(db, rc);
  123075. sqlite3_mutex_leave(db->mutex);
  123076. return rc;
  123077. }
  123078. #ifndef SQLITE_OMIT_UTF16
  123079. SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
  123080. sqlite3 *db,
  123081. const void *zFunctionName,
  123082. int nArg,
  123083. int eTextRep,
  123084. void *p,
  123085. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  123086. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  123087. void (*xFinal)(sqlite3_context*)
  123088. ){
  123089. int rc;
  123090. char *zFunc8;
  123091. #ifdef SQLITE_ENABLE_API_ARMOR
  123092. if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
  123093. #endif
  123094. sqlite3_mutex_enter(db->mutex);
  123095. assert( !db->mallocFailed );
  123096. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  123097. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  123098. sqlite3DbFree(db, zFunc8);
  123099. rc = sqlite3ApiExit(db, rc);
  123100. sqlite3_mutex_leave(db->mutex);
  123101. return rc;
  123102. }
  123103. #endif
  123104. /*
  123105. ** Declare that a function has been overloaded by a virtual table.
  123106. **
  123107. ** If the function already exists as a regular global function, then
  123108. ** this routine is a no-op. If the function does not exist, then create
  123109. ** a new one that always throws a run-time error.
  123110. **
  123111. ** When virtual tables intend to provide an overloaded function, they
  123112. ** should call this routine to make sure the global function exists.
  123113. ** A global function must exist in order for name resolution to work
  123114. ** properly.
  123115. */
  123116. SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
  123117. sqlite3 *db,
  123118. const char *zName,
  123119. int nArg
  123120. ){
  123121. int nName = sqlite3Strlen30(zName);
  123122. int rc = SQLITE_OK;
  123123. #ifdef SQLITE_ENABLE_API_ARMOR
  123124. if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
  123125. return SQLITE_MISUSE_BKPT;
  123126. }
  123127. #endif
  123128. sqlite3_mutex_enter(db->mutex);
  123129. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  123130. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  123131. 0, sqlite3InvalidFunction, 0, 0, 0);
  123132. }
  123133. rc = sqlite3ApiExit(db, rc);
  123134. sqlite3_mutex_leave(db->mutex);
  123135. return rc;
  123136. }
  123137. #ifndef SQLITE_OMIT_TRACE
  123138. /*
  123139. ** Register a trace function. The pArg from the previously registered trace
  123140. ** is returned.
  123141. **
  123142. ** A NULL trace function means that no tracing is executes. A non-NULL
  123143. ** trace is a pointer to a function that is invoked at the start of each
  123144. ** SQL statement.
  123145. */
  123146. SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  123147. void *pOld;
  123148. #ifdef SQLITE_ENABLE_API_ARMOR
  123149. if( !sqlite3SafetyCheckOk(db) ){
  123150. (void)SQLITE_MISUSE_BKPT;
  123151. return 0;
  123152. }
  123153. #endif
  123154. sqlite3_mutex_enter(db->mutex);
  123155. pOld = db->pTraceArg;
  123156. db->xTrace = xTrace;
  123157. db->pTraceArg = pArg;
  123158. sqlite3_mutex_leave(db->mutex);
  123159. return pOld;
  123160. }
  123161. /*
  123162. ** Register a profile function. The pArg from the previously registered
  123163. ** profile function is returned.
  123164. **
  123165. ** A NULL profile function means that no profiling is executes. A non-NULL
  123166. ** profile is a pointer to a function that is invoked at the conclusion of
  123167. ** each SQL statement that is run.
  123168. */
  123169. SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
  123170. sqlite3 *db,
  123171. void (*xProfile)(void*,const char*,sqlite_uint64),
  123172. void *pArg
  123173. ){
  123174. void *pOld;
  123175. #ifdef SQLITE_ENABLE_API_ARMOR
  123176. if( !sqlite3SafetyCheckOk(db) ){
  123177. (void)SQLITE_MISUSE_BKPT;
  123178. return 0;
  123179. }
  123180. #endif
  123181. sqlite3_mutex_enter(db->mutex);
  123182. pOld = db->pProfileArg;
  123183. db->xProfile = xProfile;
  123184. db->pProfileArg = pArg;
  123185. sqlite3_mutex_leave(db->mutex);
  123186. return pOld;
  123187. }
  123188. #endif /* SQLITE_OMIT_TRACE */
  123189. /*
  123190. ** Register a function to be invoked when a transaction commits.
  123191. ** If the invoked function returns non-zero, then the commit becomes a
  123192. ** rollback.
  123193. */
  123194. SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
  123195. sqlite3 *db, /* Attach the hook to this database */
  123196. int (*xCallback)(void*), /* Function to invoke on each commit */
  123197. void *pArg /* Argument to the function */
  123198. ){
  123199. void *pOld;
  123200. #ifdef SQLITE_ENABLE_API_ARMOR
  123201. if( !sqlite3SafetyCheckOk(db) ){
  123202. (void)SQLITE_MISUSE_BKPT;
  123203. return 0;
  123204. }
  123205. #endif
  123206. sqlite3_mutex_enter(db->mutex);
  123207. pOld = db->pCommitArg;
  123208. db->xCommitCallback = xCallback;
  123209. db->pCommitArg = pArg;
  123210. sqlite3_mutex_leave(db->mutex);
  123211. return pOld;
  123212. }
  123213. /*
  123214. ** Register a callback to be invoked each time a row is updated,
  123215. ** inserted or deleted using this database connection.
  123216. */
  123217. SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
  123218. sqlite3 *db, /* Attach the hook to this database */
  123219. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  123220. void *pArg /* Argument to the function */
  123221. ){
  123222. void *pRet;
  123223. #ifdef SQLITE_ENABLE_API_ARMOR
  123224. if( !sqlite3SafetyCheckOk(db) ){
  123225. (void)SQLITE_MISUSE_BKPT;
  123226. return 0;
  123227. }
  123228. #endif
  123229. sqlite3_mutex_enter(db->mutex);
  123230. pRet = db->pUpdateArg;
  123231. db->xUpdateCallback = xCallback;
  123232. db->pUpdateArg = pArg;
  123233. sqlite3_mutex_leave(db->mutex);
  123234. return pRet;
  123235. }
  123236. /*
  123237. ** Register a callback to be invoked each time a transaction is rolled
  123238. ** back by this database connection.
  123239. */
  123240. SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
  123241. sqlite3 *db, /* Attach the hook to this database */
  123242. void (*xCallback)(void*), /* Callback function */
  123243. void *pArg /* Argument to the function */
  123244. ){
  123245. void *pRet;
  123246. #ifdef SQLITE_ENABLE_API_ARMOR
  123247. if( !sqlite3SafetyCheckOk(db) ){
  123248. (void)SQLITE_MISUSE_BKPT;
  123249. return 0;
  123250. }
  123251. #endif
  123252. sqlite3_mutex_enter(db->mutex);
  123253. pRet = db->pRollbackArg;
  123254. db->xRollbackCallback = xCallback;
  123255. db->pRollbackArg = pArg;
  123256. sqlite3_mutex_leave(db->mutex);
  123257. return pRet;
  123258. }
  123259. #ifndef SQLITE_OMIT_WAL
  123260. /*
  123261. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  123262. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  123263. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  123264. ** wal_autocheckpoint()).
  123265. */
  123266. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  123267. void *pClientData, /* Argument */
  123268. sqlite3 *db, /* Connection */
  123269. const char *zDb, /* Database */
  123270. int nFrame /* Size of WAL */
  123271. ){
  123272. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  123273. sqlite3BeginBenignMalloc();
  123274. sqlite3_wal_checkpoint(db, zDb);
  123275. sqlite3EndBenignMalloc();
  123276. }
  123277. return SQLITE_OK;
  123278. }
  123279. #endif /* SQLITE_OMIT_WAL */
  123280. /*
  123281. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  123282. ** a database after committing a transaction if there are nFrame or
  123283. ** more frames in the log file. Passing zero or a negative value as the
  123284. ** nFrame parameter disables automatic checkpoints entirely.
  123285. **
  123286. ** The callback registered by this function replaces any existing callback
  123287. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  123288. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  123289. ** configured by this function.
  123290. */
  123291. SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  123292. #ifdef SQLITE_OMIT_WAL
  123293. UNUSED_PARAMETER(db);
  123294. UNUSED_PARAMETER(nFrame);
  123295. #else
  123296. #ifdef SQLITE_ENABLE_API_ARMOR
  123297. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123298. #endif
  123299. if( nFrame>0 ){
  123300. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  123301. }else{
  123302. sqlite3_wal_hook(db, 0, 0);
  123303. }
  123304. #endif
  123305. return SQLITE_OK;
  123306. }
  123307. /*
  123308. ** Register a callback to be invoked each time a transaction is written
  123309. ** into the write-ahead-log by this database connection.
  123310. */
  123311. SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
  123312. sqlite3 *db, /* Attach the hook to this db handle */
  123313. int(*xCallback)(void *, sqlite3*, const char*, int),
  123314. void *pArg /* First argument passed to xCallback() */
  123315. ){
  123316. #ifndef SQLITE_OMIT_WAL
  123317. void *pRet;
  123318. #ifdef SQLITE_ENABLE_API_ARMOR
  123319. if( !sqlite3SafetyCheckOk(db) ){
  123320. (void)SQLITE_MISUSE_BKPT;
  123321. return 0;
  123322. }
  123323. #endif
  123324. sqlite3_mutex_enter(db->mutex);
  123325. pRet = db->pWalArg;
  123326. db->xWalCallback = xCallback;
  123327. db->pWalArg = pArg;
  123328. sqlite3_mutex_leave(db->mutex);
  123329. return pRet;
  123330. #else
  123331. return 0;
  123332. #endif
  123333. }
  123334. /*
  123335. ** Checkpoint database zDb.
  123336. */
  123337. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
  123338. sqlite3 *db, /* Database handle */
  123339. const char *zDb, /* Name of attached database (or NULL) */
  123340. int eMode, /* SQLITE_CHECKPOINT_* value */
  123341. int *pnLog, /* OUT: Size of WAL log in frames */
  123342. int *pnCkpt /* OUT: Total number of frames checkpointed */
  123343. ){
  123344. #ifdef SQLITE_OMIT_WAL
  123345. return SQLITE_OK;
  123346. #else
  123347. int rc; /* Return code */
  123348. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  123349. #ifdef SQLITE_ENABLE_API_ARMOR
  123350. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  123351. #endif
  123352. /* Initialize the output variables to -1 in case an error occurs. */
  123353. if( pnLog ) *pnLog = -1;
  123354. if( pnCkpt ) *pnCkpt = -1;
  123355. assert( SQLITE_CHECKPOINT_PASSIVE==0 );
  123356. assert( SQLITE_CHECKPOINT_FULL==1 );
  123357. assert( SQLITE_CHECKPOINT_RESTART==2 );
  123358. assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
  123359. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
  123360. /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
  123361. ** mode: */
  123362. return SQLITE_MISUSE;
  123363. }
  123364. sqlite3_mutex_enter(db->mutex);
  123365. if( zDb && zDb[0] ){
  123366. iDb = sqlite3FindDbName(db, zDb);
  123367. }
  123368. if( iDb<0 ){
  123369. rc = SQLITE_ERROR;
  123370. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  123371. }else{
  123372. db->busyHandler.nBusy = 0;
  123373. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  123374. sqlite3Error(db, rc);
  123375. }
  123376. rc = sqlite3ApiExit(db, rc);
  123377. sqlite3_mutex_leave(db->mutex);
  123378. return rc;
  123379. #endif
  123380. }
  123381. /*
  123382. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  123383. ** to contains a zero-length string, all attached databases are
  123384. ** checkpointed.
  123385. */
  123386. SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  123387. /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
  123388. ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
  123389. return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
  123390. }
  123391. #ifndef SQLITE_OMIT_WAL
  123392. /*
  123393. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  123394. ** not currently open in WAL mode.
  123395. **
  123396. ** If a transaction is open on the database being checkpointed, this
  123397. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  123398. ** an error occurs while running the checkpoint, an SQLite error code is
  123399. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  123400. **
  123401. ** The mutex on database handle db should be held by the caller. The mutex
  123402. ** associated with the specific b-tree being checkpointed is taken by
  123403. ** this function while the checkpoint is running.
  123404. **
  123405. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  123406. ** checkpointed. If an error is encountered it is returned immediately -
  123407. ** no attempt is made to checkpoint any remaining databases.
  123408. **
  123409. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  123410. */
  123411. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  123412. int rc = SQLITE_OK; /* Return code */
  123413. int i; /* Used to iterate through attached dbs */
  123414. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  123415. assert( sqlite3_mutex_held(db->mutex) );
  123416. assert( !pnLog || *pnLog==-1 );
  123417. assert( !pnCkpt || *pnCkpt==-1 );
  123418. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  123419. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  123420. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  123421. pnLog = 0;
  123422. pnCkpt = 0;
  123423. if( rc==SQLITE_BUSY ){
  123424. bBusy = 1;
  123425. rc = SQLITE_OK;
  123426. }
  123427. }
  123428. }
  123429. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  123430. }
  123431. #endif /* SQLITE_OMIT_WAL */
  123432. /*
  123433. ** This function returns true if main-memory should be used instead of
  123434. ** a temporary file for transient pager files and statement journals.
  123435. ** The value returned depends on the value of db->temp_store (runtime
  123436. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  123437. ** following table describes the relationship between these two values
  123438. ** and this functions return value.
  123439. **
  123440. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  123441. ** ----------------- -------------- ------------------------------
  123442. ** 0 any file (return 0)
  123443. ** 1 1 file (return 0)
  123444. ** 1 2 memory (return 1)
  123445. ** 1 0 file (return 0)
  123446. ** 2 1 file (return 0)
  123447. ** 2 2 memory (return 1)
  123448. ** 2 0 memory (return 1)
  123449. ** 3 any memory (return 1)
  123450. */
  123451. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  123452. #if SQLITE_TEMP_STORE==1
  123453. return ( db->temp_store==2 );
  123454. #endif
  123455. #if SQLITE_TEMP_STORE==2
  123456. return ( db->temp_store!=1 );
  123457. #endif
  123458. #if SQLITE_TEMP_STORE==3
  123459. UNUSED_PARAMETER(db);
  123460. return 1;
  123461. #endif
  123462. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  123463. UNUSED_PARAMETER(db);
  123464. return 0;
  123465. #endif
  123466. }
  123467. /*
  123468. ** Return UTF-8 encoded English language explanation of the most recent
  123469. ** error.
  123470. */
  123471. SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
  123472. const char *z;
  123473. if( !db ){
  123474. return sqlite3ErrStr(SQLITE_NOMEM);
  123475. }
  123476. if( !sqlite3SafetyCheckSickOrOk(db) ){
  123477. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  123478. }
  123479. sqlite3_mutex_enter(db->mutex);
  123480. if( db->mallocFailed ){
  123481. z = sqlite3ErrStr(SQLITE_NOMEM);
  123482. }else{
  123483. testcase( db->pErr==0 );
  123484. z = (char*)sqlite3_value_text(db->pErr);
  123485. assert( !db->mallocFailed );
  123486. if( z==0 ){
  123487. z = sqlite3ErrStr(db->errCode);
  123488. }
  123489. }
  123490. sqlite3_mutex_leave(db->mutex);
  123491. return z;
  123492. }
  123493. #ifndef SQLITE_OMIT_UTF16
  123494. /*
  123495. ** Return UTF-16 encoded English language explanation of the most recent
  123496. ** error.
  123497. */
  123498. SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
  123499. static const u16 outOfMem[] = {
  123500. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  123501. };
  123502. static const u16 misuse[] = {
  123503. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  123504. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  123505. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  123506. 'o', 'u', 't', ' ',
  123507. 'o', 'f', ' ',
  123508. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  123509. };
  123510. const void *z;
  123511. if( !db ){
  123512. return (void *)outOfMem;
  123513. }
  123514. if( !sqlite3SafetyCheckSickOrOk(db) ){
  123515. return (void *)misuse;
  123516. }
  123517. sqlite3_mutex_enter(db->mutex);
  123518. if( db->mallocFailed ){
  123519. z = (void *)outOfMem;
  123520. }else{
  123521. z = sqlite3_value_text16(db->pErr);
  123522. if( z==0 ){
  123523. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  123524. z = sqlite3_value_text16(db->pErr);
  123525. }
  123526. /* A malloc() may have failed within the call to sqlite3_value_text16()
  123527. ** above. If this is the case, then the db->mallocFailed flag needs to
  123528. ** be cleared before returning. Do this directly, instead of via
  123529. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  123530. */
  123531. db->mallocFailed = 0;
  123532. }
  123533. sqlite3_mutex_leave(db->mutex);
  123534. return z;
  123535. }
  123536. #endif /* SQLITE_OMIT_UTF16 */
  123537. /*
  123538. ** Return the most recent error code generated by an SQLite routine. If NULL is
  123539. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  123540. */
  123541. SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
  123542. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  123543. return SQLITE_MISUSE_BKPT;
  123544. }
  123545. if( !db || db->mallocFailed ){
  123546. return SQLITE_NOMEM;
  123547. }
  123548. return db->errCode & db->errMask;
  123549. }
  123550. SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
  123551. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  123552. return SQLITE_MISUSE_BKPT;
  123553. }
  123554. if( !db || db->mallocFailed ){
  123555. return SQLITE_NOMEM;
  123556. }
  123557. return db->errCode;
  123558. }
  123559. /*
  123560. ** Return a string that describes the kind of error specified in the
  123561. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  123562. ** function.
  123563. */
  123564. SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
  123565. return sqlite3ErrStr(rc);
  123566. }
  123567. /*
  123568. ** Create a new collating function for database "db". The name is zName
  123569. ** and the encoding is enc.
  123570. */
  123571. static int createCollation(
  123572. sqlite3* db,
  123573. const char *zName,
  123574. u8 enc,
  123575. void* pCtx,
  123576. int(*xCompare)(void*,int,const void*,int,const void*),
  123577. void(*xDel)(void*)
  123578. ){
  123579. CollSeq *pColl;
  123580. int enc2;
  123581. assert( sqlite3_mutex_held(db->mutex) );
  123582. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  123583. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  123584. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  123585. */
  123586. enc2 = enc;
  123587. testcase( enc2==SQLITE_UTF16 );
  123588. testcase( enc2==SQLITE_UTF16_ALIGNED );
  123589. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  123590. enc2 = SQLITE_UTF16NATIVE;
  123591. }
  123592. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  123593. return SQLITE_MISUSE_BKPT;
  123594. }
  123595. /* Check if this call is removing or replacing an existing collation
  123596. ** sequence. If so, and there are active VMs, return busy. If there
  123597. ** are no active VMs, invalidate any pre-compiled statements.
  123598. */
  123599. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  123600. if( pColl && pColl->xCmp ){
  123601. if( db->nVdbeActive ){
  123602. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  123603. "unable to delete/modify collation sequence due to active statements");
  123604. return SQLITE_BUSY;
  123605. }
  123606. sqlite3ExpirePreparedStatements(db);
  123607. /* If collation sequence pColl was created directly by a call to
  123608. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  123609. ** then any copies made by synthCollSeq() need to be invalidated.
  123610. ** Also, collation destructor - CollSeq.xDel() - function may need
  123611. ** to be called.
  123612. */
  123613. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  123614. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  123615. int j;
  123616. for(j=0; j<3; j++){
  123617. CollSeq *p = &aColl[j];
  123618. if( p->enc==pColl->enc ){
  123619. if( p->xDel ){
  123620. p->xDel(p->pUser);
  123621. }
  123622. p->xCmp = 0;
  123623. }
  123624. }
  123625. }
  123626. }
  123627. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  123628. if( pColl==0 ) return SQLITE_NOMEM;
  123629. pColl->xCmp = xCompare;
  123630. pColl->pUser = pCtx;
  123631. pColl->xDel = xDel;
  123632. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  123633. sqlite3Error(db, SQLITE_OK);
  123634. return SQLITE_OK;
  123635. }
  123636. /*
  123637. ** This array defines hard upper bounds on limit values. The
  123638. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  123639. ** #defines in sqlite3.h.
  123640. */
  123641. static const int aHardLimit[] = {
  123642. SQLITE_MAX_LENGTH,
  123643. SQLITE_MAX_SQL_LENGTH,
  123644. SQLITE_MAX_COLUMN,
  123645. SQLITE_MAX_EXPR_DEPTH,
  123646. SQLITE_MAX_COMPOUND_SELECT,
  123647. SQLITE_MAX_VDBE_OP,
  123648. SQLITE_MAX_FUNCTION_ARG,
  123649. SQLITE_MAX_ATTACHED,
  123650. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  123651. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  123652. SQLITE_MAX_TRIGGER_DEPTH,
  123653. SQLITE_MAX_WORKER_THREADS,
  123654. };
  123655. /*
  123656. ** Make sure the hard limits are set to reasonable values
  123657. */
  123658. #if SQLITE_MAX_LENGTH<100
  123659. # error SQLITE_MAX_LENGTH must be at least 100
  123660. #endif
  123661. #if SQLITE_MAX_SQL_LENGTH<100
  123662. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  123663. #endif
  123664. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  123665. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  123666. #endif
  123667. #if SQLITE_MAX_COMPOUND_SELECT<2
  123668. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  123669. #endif
  123670. #if SQLITE_MAX_VDBE_OP<40
  123671. # error SQLITE_MAX_VDBE_OP must be at least 40
  123672. #endif
  123673. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  123674. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  123675. #endif
  123676. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  123677. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  123678. #endif
  123679. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  123680. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  123681. #endif
  123682. #if SQLITE_MAX_COLUMN>32767
  123683. # error SQLITE_MAX_COLUMN must not exceed 32767
  123684. #endif
  123685. #if SQLITE_MAX_TRIGGER_DEPTH<1
  123686. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  123687. #endif
  123688. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  123689. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  123690. #endif
  123691. /*
  123692. ** Change the value of a limit. Report the old value.
  123693. ** If an invalid limit index is supplied, report -1.
  123694. ** Make no changes but still report the old value if the
  123695. ** new limit is negative.
  123696. **
  123697. ** A new lower limit does not shrink existing constructs.
  123698. ** It merely prevents new constructs that exceed the limit
  123699. ** from forming.
  123700. */
  123701. SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  123702. int oldLimit;
  123703. #ifdef SQLITE_ENABLE_API_ARMOR
  123704. if( !sqlite3SafetyCheckOk(db) ){
  123705. (void)SQLITE_MISUSE_BKPT;
  123706. return -1;
  123707. }
  123708. #endif
  123709. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  123710. ** there is a hard upper bound set at compile-time by a C preprocessor
  123711. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  123712. ** "_MAX_".)
  123713. */
  123714. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  123715. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  123716. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  123717. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  123718. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  123719. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  123720. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  123721. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  123722. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  123723. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  123724. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  123725. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  123726. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  123727. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  123728. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  123729. return -1;
  123730. }
  123731. oldLimit = db->aLimit[limitId];
  123732. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  123733. if( newLimit>aHardLimit[limitId] ){
  123734. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  123735. }
  123736. db->aLimit[limitId] = newLimit;
  123737. }
  123738. return oldLimit; /* IMP: R-53341-35419 */
  123739. }
  123740. /*
  123741. ** This function is used to parse both URIs and non-URI filenames passed by the
  123742. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  123743. ** URIs specified as part of ATTACH statements.
  123744. **
  123745. ** The first argument to this function is the name of the VFS to use (or
  123746. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  123747. ** query parameter. The second argument contains the URI (or non-URI filename)
  123748. ** itself. When this function is called the *pFlags variable should contain
  123749. ** the default flags to open the database handle with. The value stored in
  123750. ** *pFlags may be updated before returning if the URI filename contains
  123751. ** "cache=xxx" or "mode=xxx" query parameters.
  123752. **
  123753. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  123754. ** the VFS that should be used to open the database file. *pzFile is set to
  123755. ** point to a buffer containing the name of the file to open. It is the
  123756. ** responsibility of the caller to eventually call sqlite3_free() to release
  123757. ** this buffer.
  123758. **
  123759. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  123760. ** may be set to point to a buffer containing an English language error
  123761. ** message. It is the responsibility of the caller to eventually release
  123762. ** this buffer by calling sqlite3_free().
  123763. */
  123764. SQLITE_PRIVATE int sqlite3ParseUri(
  123765. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  123766. const char *zUri, /* Nul-terminated URI to parse */
  123767. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  123768. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  123769. char **pzFile, /* OUT: Filename component of URI */
  123770. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  123771. ){
  123772. int rc = SQLITE_OK;
  123773. unsigned int flags = *pFlags;
  123774. const char *zVfs = zDefaultVfs;
  123775. char *zFile;
  123776. char c;
  123777. int nUri = sqlite3Strlen30(zUri);
  123778. assert( *pzErrMsg==0 );
  123779. if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
  123780. || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
  123781. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  123782. ){
  123783. char *zOpt;
  123784. int eState; /* Parser state when parsing URI */
  123785. int iIn; /* Input character index */
  123786. int iOut = 0; /* Output character index */
  123787. u64 nByte = nUri+2; /* Bytes of space to allocate */
  123788. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  123789. ** method that there may be extra parameters following the file-name. */
  123790. flags |= SQLITE_OPEN_URI;
  123791. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  123792. zFile = sqlite3_malloc64(nByte);
  123793. if( !zFile ) return SQLITE_NOMEM;
  123794. iIn = 5;
  123795. #ifdef SQLITE_ALLOW_URI_AUTHORITY
  123796. if( strncmp(zUri+5, "///", 3)==0 ){
  123797. iIn = 7;
  123798. /* The following condition causes URIs with five leading / characters
  123799. ** like file://///host/path to be converted into UNCs like //host/path.
  123800. ** The correct URI for that UNC has only two or four leading / characters
  123801. ** file://host/path or file:////host/path. But 5 leading slashes is a
  123802. ** common error, we are told, so we handle it as a special case. */
  123803. if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
  123804. }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
  123805. iIn = 16;
  123806. }
  123807. #else
  123808. /* Discard the scheme and authority segments of the URI. */
  123809. if( zUri[5]=='/' && zUri[6]=='/' ){
  123810. iIn = 7;
  123811. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  123812. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  123813. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  123814. iIn-7, &zUri[7]);
  123815. rc = SQLITE_ERROR;
  123816. goto parse_uri_out;
  123817. }
  123818. }
  123819. #endif
  123820. /* Copy the filename and any query parameters into the zFile buffer.
  123821. ** Decode %HH escape codes along the way.
  123822. **
  123823. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  123824. ** on the parsing context. As follows:
  123825. **
  123826. ** 0: Parsing file-name.
  123827. ** 1: Parsing name section of a name=value query parameter.
  123828. ** 2: Parsing value section of a name=value query parameter.
  123829. */
  123830. eState = 0;
  123831. while( (c = zUri[iIn])!=0 && c!='#' ){
  123832. iIn++;
  123833. if( c=='%'
  123834. && sqlite3Isxdigit(zUri[iIn])
  123835. && sqlite3Isxdigit(zUri[iIn+1])
  123836. ){
  123837. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  123838. octet += sqlite3HexToInt(zUri[iIn++]);
  123839. assert( octet>=0 && octet<256 );
  123840. if( octet==0 ){
  123841. /* This branch is taken when "%00" appears within the URI. In this
  123842. ** case we ignore all text in the remainder of the path, name or
  123843. ** value currently being parsed. So ignore the current character
  123844. ** and skip to the next "?", "=" or "&", as appropriate. */
  123845. while( (c = zUri[iIn])!=0 && c!='#'
  123846. && (eState!=0 || c!='?')
  123847. && (eState!=1 || (c!='=' && c!='&'))
  123848. && (eState!=2 || c!='&')
  123849. ){
  123850. iIn++;
  123851. }
  123852. continue;
  123853. }
  123854. c = octet;
  123855. }else if( eState==1 && (c=='&' || c=='=') ){
  123856. if( zFile[iOut-1]==0 ){
  123857. /* An empty option name. Ignore this option altogether. */
  123858. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  123859. continue;
  123860. }
  123861. if( c=='&' ){
  123862. zFile[iOut++] = '\0';
  123863. }else{
  123864. eState = 2;
  123865. }
  123866. c = 0;
  123867. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  123868. c = 0;
  123869. eState = 1;
  123870. }
  123871. zFile[iOut++] = c;
  123872. }
  123873. if( eState==1 ) zFile[iOut++] = '\0';
  123874. zFile[iOut++] = '\0';
  123875. zFile[iOut++] = '\0';
  123876. /* Check if there were any options specified that should be interpreted
  123877. ** here. Options that are interpreted here include "vfs" and those that
  123878. ** correspond to flags that may be passed to the sqlite3_open_v2()
  123879. ** method. */
  123880. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  123881. while( zOpt[0] ){
  123882. int nOpt = sqlite3Strlen30(zOpt);
  123883. char *zVal = &zOpt[nOpt+1];
  123884. int nVal = sqlite3Strlen30(zVal);
  123885. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  123886. zVfs = zVal;
  123887. }else{
  123888. struct OpenMode {
  123889. const char *z;
  123890. int mode;
  123891. } *aMode = 0;
  123892. char *zModeType = 0;
  123893. int mask = 0;
  123894. int limit = 0;
  123895. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  123896. static struct OpenMode aCacheMode[] = {
  123897. { "shared", SQLITE_OPEN_SHAREDCACHE },
  123898. { "private", SQLITE_OPEN_PRIVATECACHE },
  123899. { 0, 0 }
  123900. };
  123901. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  123902. aMode = aCacheMode;
  123903. limit = mask;
  123904. zModeType = "cache";
  123905. }
  123906. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  123907. static struct OpenMode aOpenMode[] = {
  123908. { "ro", SQLITE_OPEN_READONLY },
  123909. { "rw", SQLITE_OPEN_READWRITE },
  123910. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  123911. { "memory", SQLITE_OPEN_MEMORY },
  123912. { 0, 0 }
  123913. };
  123914. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  123915. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  123916. aMode = aOpenMode;
  123917. limit = mask & flags;
  123918. zModeType = "access";
  123919. }
  123920. if( aMode ){
  123921. int i;
  123922. int mode = 0;
  123923. for(i=0; aMode[i].z; i++){
  123924. const char *z = aMode[i].z;
  123925. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  123926. mode = aMode[i].mode;
  123927. break;
  123928. }
  123929. }
  123930. if( mode==0 ){
  123931. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  123932. rc = SQLITE_ERROR;
  123933. goto parse_uri_out;
  123934. }
  123935. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  123936. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  123937. zModeType, zVal);
  123938. rc = SQLITE_PERM;
  123939. goto parse_uri_out;
  123940. }
  123941. flags = (flags & ~mask) | mode;
  123942. }
  123943. }
  123944. zOpt = &zVal[nVal+1];
  123945. }
  123946. }else{
  123947. zFile = sqlite3_malloc64(nUri+2);
  123948. if( !zFile ) return SQLITE_NOMEM;
  123949. memcpy(zFile, zUri, nUri);
  123950. zFile[nUri] = '\0';
  123951. zFile[nUri+1] = '\0';
  123952. flags &= ~SQLITE_OPEN_URI;
  123953. }
  123954. *ppVfs = sqlite3_vfs_find(zVfs);
  123955. if( *ppVfs==0 ){
  123956. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  123957. rc = SQLITE_ERROR;
  123958. }
  123959. parse_uri_out:
  123960. if( rc!=SQLITE_OK ){
  123961. sqlite3_free(zFile);
  123962. zFile = 0;
  123963. }
  123964. *pFlags = flags;
  123965. *pzFile = zFile;
  123966. return rc;
  123967. }
  123968. /*
  123969. ** This routine does the work of opening a database on behalf of
  123970. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  123971. ** is UTF-8 encoded.
  123972. */
  123973. static int openDatabase(
  123974. const char *zFilename, /* Database filename UTF-8 encoded */
  123975. sqlite3 **ppDb, /* OUT: Returned database handle */
  123976. unsigned int flags, /* Operational flags */
  123977. const char *zVfs /* Name of the VFS to use */
  123978. ){
  123979. sqlite3 *db; /* Store allocated handle here */
  123980. int rc; /* Return code */
  123981. int isThreadsafe; /* True for threadsafe connections */
  123982. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  123983. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  123984. #ifdef SQLITE_ENABLE_API_ARMOR
  123985. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  123986. #endif
  123987. *ppDb = 0;
  123988. #ifndef SQLITE_OMIT_AUTOINIT
  123989. rc = sqlite3_initialize();
  123990. if( rc ) return rc;
  123991. #endif
  123992. /* Only allow sensible combinations of bits in the flags argument.
  123993. ** Throw an error if any non-sense combination is used. If we
  123994. ** do not block illegal combinations here, it could trigger
  123995. ** assert() statements in deeper layers. Sensible combinations
  123996. ** are:
  123997. **
  123998. ** 1: SQLITE_OPEN_READONLY
  123999. ** 2: SQLITE_OPEN_READWRITE
  124000. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  124001. */
  124002. assert( SQLITE_OPEN_READONLY == 0x01 );
  124003. assert( SQLITE_OPEN_READWRITE == 0x02 );
  124004. assert( SQLITE_OPEN_CREATE == 0x04 );
  124005. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  124006. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  124007. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  124008. if( ((1<<(flags&7)) & 0x46)==0 ){
  124009. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  124010. }
  124011. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  124012. isThreadsafe = 0;
  124013. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  124014. isThreadsafe = 0;
  124015. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  124016. isThreadsafe = 1;
  124017. }else{
  124018. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  124019. }
  124020. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  124021. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  124022. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  124023. flags |= SQLITE_OPEN_SHAREDCACHE;
  124024. }
  124025. /* Remove harmful bits from the flags parameter
  124026. **
  124027. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  124028. ** dealt with in the previous code block. Besides these, the only
  124029. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  124030. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  124031. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  124032. ** off all other flags.
  124033. */
  124034. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  124035. SQLITE_OPEN_EXCLUSIVE |
  124036. SQLITE_OPEN_MAIN_DB |
  124037. SQLITE_OPEN_TEMP_DB |
  124038. SQLITE_OPEN_TRANSIENT_DB |
  124039. SQLITE_OPEN_MAIN_JOURNAL |
  124040. SQLITE_OPEN_TEMP_JOURNAL |
  124041. SQLITE_OPEN_SUBJOURNAL |
  124042. SQLITE_OPEN_MASTER_JOURNAL |
  124043. SQLITE_OPEN_NOMUTEX |
  124044. SQLITE_OPEN_FULLMUTEX |
  124045. SQLITE_OPEN_WAL
  124046. );
  124047. /* Allocate the sqlite data structure */
  124048. db = sqlite3MallocZero( sizeof(sqlite3) );
  124049. if( db==0 ) goto opendb_out;
  124050. if( isThreadsafe ){
  124051. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  124052. if( db->mutex==0 ){
  124053. sqlite3_free(db);
  124054. db = 0;
  124055. goto opendb_out;
  124056. }
  124057. }
  124058. sqlite3_mutex_enter(db->mutex);
  124059. db->errMask = 0xff;
  124060. db->nDb = 2;
  124061. db->magic = SQLITE_MAGIC_BUSY;
  124062. db->aDb = db->aDbStatic;
  124063. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  124064. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  124065. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  124066. db->autoCommit = 1;
  124067. db->nextAutovac = -1;
  124068. db->szMmap = sqlite3GlobalConfig.szMmap;
  124069. db->nextPagesize = 0;
  124070. db->nMaxSorterMmap = 0x7FFFFFFF;
  124071. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  124072. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  124073. | SQLITE_AutoIndex
  124074. #endif
  124075. #if SQLITE_DEFAULT_CKPTFULLFSYNC
  124076. | SQLITE_CkptFullFSync
  124077. #endif
  124078. #if SQLITE_DEFAULT_FILE_FORMAT<4
  124079. | SQLITE_LegacyFileFmt
  124080. #endif
  124081. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  124082. | SQLITE_LoadExtension
  124083. #endif
  124084. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  124085. | SQLITE_RecTriggers
  124086. #endif
  124087. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  124088. | SQLITE_ForeignKeys
  124089. #endif
  124090. #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
  124091. | SQLITE_ReverseOrder
  124092. #endif
  124093. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  124094. | SQLITE_CellSizeCk
  124095. #endif
  124096. ;
  124097. sqlite3HashInit(&db->aCollSeq);
  124098. #ifndef SQLITE_OMIT_VIRTUALTABLE
  124099. sqlite3HashInit(&db->aModule);
  124100. #endif
  124101. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  124102. ** and UTF-16, so add a version for each to avoid any unnecessary
  124103. ** conversions. The only error that can occur here is a malloc() failure.
  124104. **
  124105. ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
  124106. ** functions:
  124107. */
  124108. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  124109. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  124110. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  124111. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  124112. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  124113. if( db->mallocFailed ){
  124114. goto opendb_out;
  124115. }
  124116. /* EVIDENCE-OF: R-08308-17224 The default collating function for all
  124117. ** strings is BINARY.
  124118. */
  124119. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  124120. assert( db->pDfltColl!=0 );
  124121. /* Parse the filename/URI argument. */
  124122. db->openFlags = flags;
  124123. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  124124. if( rc!=SQLITE_OK ){
  124125. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  124126. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  124127. sqlite3_free(zErrMsg);
  124128. goto opendb_out;
  124129. }
  124130. /* Open the backend database driver */
  124131. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  124132. flags | SQLITE_OPEN_MAIN_DB);
  124133. if( rc!=SQLITE_OK ){
  124134. if( rc==SQLITE_IOERR_NOMEM ){
  124135. rc = SQLITE_NOMEM;
  124136. }
  124137. sqlite3Error(db, rc);
  124138. goto opendb_out;
  124139. }
  124140. sqlite3BtreeEnter(db->aDb[0].pBt);
  124141. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  124142. if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
  124143. sqlite3BtreeLeave(db->aDb[0].pBt);
  124144. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  124145. /* The default safety_level for the main database is 'full'; for the temp
  124146. ** database it is 'NONE'. This matches the pager layer defaults.
  124147. */
  124148. db->aDb[0].zName = "main";
  124149. db->aDb[0].safety_level = 3;
  124150. db->aDb[1].zName = "temp";
  124151. db->aDb[1].safety_level = 1;
  124152. db->magic = SQLITE_MAGIC_OPEN;
  124153. if( db->mallocFailed ){
  124154. goto opendb_out;
  124155. }
  124156. /* Register all built-in functions, but do not attempt to read the
  124157. ** database schema yet. This is delayed until the first time the database
  124158. ** is accessed.
  124159. */
  124160. sqlite3Error(db, SQLITE_OK);
  124161. sqlite3RegisterBuiltinFunctions(db);
  124162. /* Load automatic extensions - extensions that have been registered
  124163. ** using the sqlite3_automatic_extension() API.
  124164. */
  124165. rc = sqlite3_errcode(db);
  124166. if( rc==SQLITE_OK ){
  124167. sqlite3AutoLoadExtensions(db);
  124168. rc = sqlite3_errcode(db);
  124169. if( rc!=SQLITE_OK ){
  124170. goto opendb_out;
  124171. }
  124172. }
  124173. #ifdef SQLITE_ENABLE_FTS1
  124174. if( !db->mallocFailed ){
  124175. extern int sqlite3Fts1Init(sqlite3*);
  124176. rc = sqlite3Fts1Init(db);
  124177. }
  124178. #endif
  124179. #ifdef SQLITE_ENABLE_FTS2
  124180. if( !db->mallocFailed && rc==SQLITE_OK ){
  124181. extern int sqlite3Fts2Init(sqlite3*);
  124182. rc = sqlite3Fts2Init(db);
  124183. }
  124184. #endif
  124185. #ifdef SQLITE_ENABLE_FTS3
  124186. if( !db->mallocFailed && rc==SQLITE_OK ){
  124187. rc = sqlite3Fts3Init(db);
  124188. }
  124189. #endif
  124190. #ifdef SQLITE_ENABLE_ICU
  124191. if( !db->mallocFailed && rc==SQLITE_OK ){
  124192. rc = sqlite3IcuInit(db);
  124193. }
  124194. #endif
  124195. #ifdef SQLITE_ENABLE_RTREE
  124196. if( !db->mallocFailed && rc==SQLITE_OK){
  124197. rc = sqlite3RtreeInit(db);
  124198. }
  124199. #endif
  124200. #ifdef SQLITE_ENABLE_DBSTAT_VTAB
  124201. if( !db->mallocFailed && rc==SQLITE_OK){
  124202. rc = sqlite3DbstatRegister(db);
  124203. }
  124204. #endif
  124205. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  124206. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  124207. ** mode. Doing nothing at all also makes NORMAL the default.
  124208. */
  124209. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  124210. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  124211. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  124212. SQLITE_DEFAULT_LOCKING_MODE);
  124213. #endif
  124214. if( rc ) sqlite3Error(db, rc);
  124215. /* Enable the lookaside-malloc subsystem */
  124216. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  124217. sqlite3GlobalConfig.nLookaside);
  124218. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  124219. opendb_out:
  124220. sqlite3_free(zOpen);
  124221. if( db ){
  124222. assert( db->mutex!=0 || isThreadsafe==0
  124223. || sqlite3GlobalConfig.bFullMutex==0 );
  124224. sqlite3_mutex_leave(db->mutex);
  124225. }
  124226. rc = sqlite3_errcode(db);
  124227. assert( db!=0 || rc==SQLITE_NOMEM );
  124228. if( rc==SQLITE_NOMEM ){
  124229. sqlite3_close(db);
  124230. db = 0;
  124231. }else if( rc!=SQLITE_OK ){
  124232. db->magic = SQLITE_MAGIC_SICK;
  124233. }
  124234. *ppDb = db;
  124235. #ifdef SQLITE_ENABLE_SQLLOG
  124236. if( sqlite3GlobalConfig.xSqllog ){
  124237. /* Opening a db handle. Fourth parameter is passed 0. */
  124238. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  124239. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  124240. }
  124241. #endif
  124242. return rc & 0xff;
  124243. }
  124244. /*
  124245. ** Open a new database handle.
  124246. */
  124247. SQLITE_API int SQLITE_STDCALL sqlite3_open(
  124248. const char *zFilename,
  124249. sqlite3 **ppDb
  124250. ){
  124251. return openDatabase(zFilename, ppDb,
  124252. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  124253. }
  124254. SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
  124255. const char *filename, /* Database filename (UTF-8) */
  124256. sqlite3 **ppDb, /* OUT: SQLite db handle */
  124257. int flags, /* Flags */
  124258. const char *zVfs /* Name of VFS module to use */
  124259. ){
  124260. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  124261. }
  124262. #ifndef SQLITE_OMIT_UTF16
  124263. /*
  124264. ** Open a new database handle.
  124265. */
  124266. SQLITE_API int SQLITE_STDCALL sqlite3_open16(
  124267. const void *zFilename,
  124268. sqlite3 **ppDb
  124269. ){
  124270. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  124271. sqlite3_value *pVal;
  124272. int rc;
  124273. #ifdef SQLITE_ENABLE_API_ARMOR
  124274. if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
  124275. #endif
  124276. *ppDb = 0;
  124277. #ifndef SQLITE_OMIT_AUTOINIT
  124278. rc = sqlite3_initialize();
  124279. if( rc ) return rc;
  124280. #endif
  124281. if( zFilename==0 ) zFilename = "\000\000";
  124282. pVal = sqlite3ValueNew(0);
  124283. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  124284. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  124285. if( zFilename8 ){
  124286. rc = openDatabase(zFilename8, ppDb,
  124287. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  124288. assert( *ppDb || rc==SQLITE_NOMEM );
  124289. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  124290. SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
  124291. }
  124292. }else{
  124293. rc = SQLITE_NOMEM;
  124294. }
  124295. sqlite3ValueFree(pVal);
  124296. return rc & 0xff;
  124297. }
  124298. #endif /* SQLITE_OMIT_UTF16 */
  124299. /*
  124300. ** Register a new collation sequence with the database handle db.
  124301. */
  124302. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
  124303. sqlite3* db,
  124304. const char *zName,
  124305. int enc,
  124306. void* pCtx,
  124307. int(*xCompare)(void*,int,const void*,int,const void*)
  124308. ){
  124309. return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
  124310. }
  124311. /*
  124312. ** Register a new collation sequence with the database handle db.
  124313. */
  124314. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
  124315. sqlite3* db,
  124316. const char *zName,
  124317. int enc,
  124318. void* pCtx,
  124319. int(*xCompare)(void*,int,const void*,int,const void*),
  124320. void(*xDel)(void*)
  124321. ){
  124322. int rc;
  124323. #ifdef SQLITE_ENABLE_API_ARMOR
  124324. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  124325. #endif
  124326. sqlite3_mutex_enter(db->mutex);
  124327. assert( !db->mallocFailed );
  124328. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  124329. rc = sqlite3ApiExit(db, rc);
  124330. sqlite3_mutex_leave(db->mutex);
  124331. return rc;
  124332. }
  124333. #ifndef SQLITE_OMIT_UTF16
  124334. /*
  124335. ** Register a new collation sequence with the database handle db.
  124336. */
  124337. SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
  124338. sqlite3* db,
  124339. const void *zName,
  124340. int enc,
  124341. void* pCtx,
  124342. int(*xCompare)(void*,int,const void*,int,const void*)
  124343. ){
  124344. int rc = SQLITE_OK;
  124345. char *zName8;
  124346. #ifdef SQLITE_ENABLE_API_ARMOR
  124347. if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
  124348. #endif
  124349. sqlite3_mutex_enter(db->mutex);
  124350. assert( !db->mallocFailed );
  124351. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  124352. if( zName8 ){
  124353. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  124354. sqlite3DbFree(db, zName8);
  124355. }
  124356. rc = sqlite3ApiExit(db, rc);
  124357. sqlite3_mutex_leave(db->mutex);
  124358. return rc;
  124359. }
  124360. #endif /* SQLITE_OMIT_UTF16 */
  124361. /*
  124362. ** Register a collation sequence factory callback with the database handle
  124363. ** db. Replace any previously installed collation sequence factory.
  124364. */
  124365. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
  124366. sqlite3 *db,
  124367. void *pCollNeededArg,
  124368. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  124369. ){
  124370. #ifdef SQLITE_ENABLE_API_ARMOR
  124371. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124372. #endif
  124373. sqlite3_mutex_enter(db->mutex);
  124374. db->xCollNeeded = xCollNeeded;
  124375. db->xCollNeeded16 = 0;
  124376. db->pCollNeededArg = pCollNeededArg;
  124377. sqlite3_mutex_leave(db->mutex);
  124378. return SQLITE_OK;
  124379. }
  124380. #ifndef SQLITE_OMIT_UTF16
  124381. /*
  124382. ** Register a collation sequence factory callback with the database handle
  124383. ** db. Replace any previously installed collation sequence factory.
  124384. */
  124385. SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
  124386. sqlite3 *db,
  124387. void *pCollNeededArg,
  124388. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  124389. ){
  124390. #ifdef SQLITE_ENABLE_API_ARMOR
  124391. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124392. #endif
  124393. sqlite3_mutex_enter(db->mutex);
  124394. db->xCollNeeded = 0;
  124395. db->xCollNeeded16 = xCollNeeded16;
  124396. db->pCollNeededArg = pCollNeededArg;
  124397. sqlite3_mutex_leave(db->mutex);
  124398. return SQLITE_OK;
  124399. }
  124400. #endif /* SQLITE_OMIT_UTF16 */
  124401. #ifndef SQLITE_OMIT_DEPRECATED
  124402. /*
  124403. ** This function is now an anachronism. It used to be used to recover from a
  124404. ** malloc() failure, but SQLite now does this automatically.
  124405. */
  124406. SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
  124407. return SQLITE_OK;
  124408. }
  124409. #endif
  124410. /*
  124411. ** Test to see whether or not the database connection is in autocommit
  124412. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  124413. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  124414. ** by the next COMMIT or ROLLBACK.
  124415. */
  124416. SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
  124417. #ifdef SQLITE_ENABLE_API_ARMOR
  124418. if( !sqlite3SafetyCheckOk(db) ){
  124419. (void)SQLITE_MISUSE_BKPT;
  124420. return 0;
  124421. }
  124422. #endif
  124423. return db->autoCommit;
  124424. }
  124425. /*
  124426. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  124427. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  124428. ** constants. They serve two purposes:
  124429. **
  124430. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  124431. ** to detect when version error conditions occurs.
  124432. **
  124433. ** 2. Invoke sqlite3_log() to provide the source code location where
  124434. ** a low-level error is first detected.
  124435. */
  124436. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  124437. testcase( sqlite3GlobalConfig.xLog!=0 );
  124438. sqlite3_log(SQLITE_CORRUPT,
  124439. "database corruption at line %d of [%.10s]",
  124440. lineno, 20+sqlite3_sourceid());
  124441. return SQLITE_CORRUPT;
  124442. }
  124443. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  124444. testcase( sqlite3GlobalConfig.xLog!=0 );
  124445. sqlite3_log(SQLITE_MISUSE,
  124446. "misuse at line %d of [%.10s]",
  124447. lineno, 20+sqlite3_sourceid());
  124448. return SQLITE_MISUSE;
  124449. }
  124450. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  124451. testcase( sqlite3GlobalConfig.xLog!=0 );
  124452. sqlite3_log(SQLITE_CANTOPEN,
  124453. "cannot open file at line %d of [%.10s]",
  124454. lineno, 20+sqlite3_sourceid());
  124455. return SQLITE_CANTOPEN;
  124456. }
  124457. #ifndef SQLITE_OMIT_DEPRECATED
  124458. /*
  124459. ** This is a convenience routine that makes sure that all thread-specific
  124460. ** data for this thread has been deallocated.
  124461. **
  124462. ** SQLite no longer uses thread-specific data so this routine is now a
  124463. ** no-op. It is retained for historical compatibility.
  124464. */
  124465. SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
  124466. }
  124467. #endif
  124468. /*
  124469. ** Return meta information about a specific column of a database table.
  124470. ** See comment in sqlite3.h (sqlite.h.in) for details.
  124471. */
  124472. SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
  124473. sqlite3 *db, /* Connection handle */
  124474. const char *zDbName, /* Database name or NULL */
  124475. const char *zTableName, /* Table name */
  124476. const char *zColumnName, /* Column name */
  124477. char const **pzDataType, /* OUTPUT: Declared data type */
  124478. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  124479. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  124480. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  124481. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  124482. ){
  124483. int rc;
  124484. char *zErrMsg = 0;
  124485. Table *pTab = 0;
  124486. Column *pCol = 0;
  124487. int iCol = 0;
  124488. char const *zDataType = 0;
  124489. char const *zCollSeq = 0;
  124490. int notnull = 0;
  124491. int primarykey = 0;
  124492. int autoinc = 0;
  124493. #ifdef SQLITE_ENABLE_API_ARMOR
  124494. if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
  124495. return SQLITE_MISUSE_BKPT;
  124496. }
  124497. #endif
  124498. /* Ensure the database schema has been loaded */
  124499. sqlite3_mutex_enter(db->mutex);
  124500. sqlite3BtreeEnterAll(db);
  124501. rc = sqlite3Init(db, &zErrMsg);
  124502. if( SQLITE_OK!=rc ){
  124503. goto error_out;
  124504. }
  124505. /* Locate the table in question */
  124506. pTab = sqlite3FindTable(db, zTableName, zDbName);
  124507. if( !pTab || pTab->pSelect ){
  124508. pTab = 0;
  124509. goto error_out;
  124510. }
  124511. /* Find the column for which info is requested */
  124512. if( zColumnName==0 ){
  124513. /* Query for existance of table only */
  124514. }else{
  124515. for(iCol=0; iCol<pTab->nCol; iCol++){
  124516. pCol = &pTab->aCol[iCol];
  124517. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  124518. break;
  124519. }
  124520. }
  124521. if( iCol==pTab->nCol ){
  124522. if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
  124523. iCol = pTab->iPKey;
  124524. pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
  124525. }else{
  124526. pTab = 0;
  124527. goto error_out;
  124528. }
  124529. }
  124530. }
  124531. /* The following block stores the meta information that will be returned
  124532. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  124533. ** and autoinc. At this point there are two possibilities:
  124534. **
  124535. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  124536. ** and there is no explicitly declared IPK column.
  124537. **
  124538. ** 2. The table is not a view and the column name identified an
  124539. ** explicitly declared column. Copy meta information from *pCol.
  124540. */
  124541. if( pCol ){
  124542. zDataType = pCol->zType;
  124543. zCollSeq = pCol->zColl;
  124544. notnull = pCol->notNull!=0;
  124545. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  124546. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  124547. }else{
  124548. zDataType = "INTEGER";
  124549. primarykey = 1;
  124550. }
  124551. if( !zCollSeq ){
  124552. zCollSeq = "BINARY";
  124553. }
  124554. error_out:
  124555. sqlite3BtreeLeaveAll(db);
  124556. /* Whether the function call succeeded or failed, set the output parameters
  124557. ** to whatever their local counterparts contain. If an error did occur,
  124558. ** this has the effect of zeroing all output parameters.
  124559. */
  124560. if( pzDataType ) *pzDataType = zDataType;
  124561. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  124562. if( pNotNull ) *pNotNull = notnull;
  124563. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  124564. if( pAutoinc ) *pAutoinc = autoinc;
  124565. if( SQLITE_OK==rc && !pTab ){
  124566. sqlite3DbFree(db, zErrMsg);
  124567. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  124568. zColumnName);
  124569. rc = SQLITE_ERROR;
  124570. }
  124571. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  124572. sqlite3DbFree(db, zErrMsg);
  124573. rc = sqlite3ApiExit(db, rc);
  124574. sqlite3_mutex_leave(db->mutex);
  124575. return rc;
  124576. }
  124577. /*
  124578. ** Sleep for a little while. Return the amount of time slept.
  124579. */
  124580. SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
  124581. sqlite3_vfs *pVfs;
  124582. int rc;
  124583. pVfs = sqlite3_vfs_find(0);
  124584. if( pVfs==0 ) return 0;
  124585. /* This function works in milliseconds, but the underlying OsSleep()
  124586. ** API uses microseconds. Hence the 1000's.
  124587. */
  124588. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  124589. return rc;
  124590. }
  124591. /*
  124592. ** Enable or disable the extended result codes.
  124593. */
  124594. SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  124595. #ifdef SQLITE_ENABLE_API_ARMOR
  124596. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124597. #endif
  124598. sqlite3_mutex_enter(db->mutex);
  124599. db->errMask = onoff ? 0xffffffff : 0xff;
  124600. sqlite3_mutex_leave(db->mutex);
  124601. return SQLITE_OK;
  124602. }
  124603. /*
  124604. ** Invoke the xFileControl method on a particular database.
  124605. */
  124606. SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  124607. int rc = SQLITE_ERROR;
  124608. Btree *pBtree;
  124609. #ifdef SQLITE_ENABLE_API_ARMOR
  124610. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  124611. #endif
  124612. sqlite3_mutex_enter(db->mutex);
  124613. pBtree = sqlite3DbNameToBtree(db, zDbName);
  124614. if( pBtree ){
  124615. Pager *pPager;
  124616. sqlite3_file *fd;
  124617. sqlite3BtreeEnter(pBtree);
  124618. pPager = sqlite3BtreePager(pBtree);
  124619. assert( pPager!=0 );
  124620. fd = sqlite3PagerFile(pPager);
  124621. assert( fd!=0 );
  124622. if( op==SQLITE_FCNTL_FILE_POINTER ){
  124623. *(sqlite3_file**)pArg = fd;
  124624. rc = SQLITE_OK;
  124625. }else if( fd->pMethods ){
  124626. rc = sqlite3OsFileControl(fd, op, pArg);
  124627. }else{
  124628. rc = SQLITE_NOTFOUND;
  124629. }
  124630. sqlite3BtreeLeave(pBtree);
  124631. }
  124632. sqlite3_mutex_leave(db->mutex);
  124633. return rc;
  124634. }
  124635. /*
  124636. ** Interface to the testing logic.
  124637. */
  124638. SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
  124639. int rc = 0;
  124640. #ifdef SQLITE_OMIT_BUILTIN_TEST
  124641. UNUSED_PARAMETER(op);
  124642. #else
  124643. va_list ap;
  124644. va_start(ap, op);
  124645. switch( op ){
  124646. /*
  124647. ** Save the current state of the PRNG.
  124648. */
  124649. case SQLITE_TESTCTRL_PRNG_SAVE: {
  124650. sqlite3PrngSaveState();
  124651. break;
  124652. }
  124653. /*
  124654. ** Restore the state of the PRNG to the last state saved using
  124655. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  124656. ** this verb acts like PRNG_RESET.
  124657. */
  124658. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  124659. sqlite3PrngRestoreState();
  124660. break;
  124661. }
  124662. /*
  124663. ** Reset the PRNG back to its uninitialized state. The next call
  124664. ** to sqlite3_randomness() will reseed the PRNG using a single call
  124665. ** to the xRandomness method of the default VFS.
  124666. */
  124667. case SQLITE_TESTCTRL_PRNG_RESET: {
  124668. sqlite3_randomness(0,0);
  124669. break;
  124670. }
  124671. /*
  124672. ** sqlite3_test_control(BITVEC_TEST, size, program)
  124673. **
  124674. ** Run a test against a Bitvec object of size. The program argument
  124675. ** is an array of integers that defines the test. Return -1 on a
  124676. ** memory allocation error, 0 on success, or non-zero for an error.
  124677. ** See the sqlite3BitvecBuiltinTest() for additional information.
  124678. */
  124679. case SQLITE_TESTCTRL_BITVEC_TEST: {
  124680. int sz = va_arg(ap, int);
  124681. int *aProg = va_arg(ap, int*);
  124682. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  124683. break;
  124684. }
  124685. /*
  124686. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  124687. **
  124688. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  124689. ** if xCallback is not NULL.
  124690. **
  124691. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  124692. ** is called immediately after installing the new callback and the return
  124693. ** value from sqlite3FaultSim(0) becomes the return from
  124694. ** sqlite3_test_control().
  124695. */
  124696. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  124697. /* MSVC is picky about pulling func ptrs from va lists.
  124698. ** http://support.microsoft.com/kb/47961
  124699. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  124700. */
  124701. typedef int(*TESTCALLBACKFUNC_t)(int);
  124702. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  124703. rc = sqlite3FaultSim(0);
  124704. break;
  124705. }
  124706. /*
  124707. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  124708. **
  124709. ** Register hooks to call to indicate which malloc() failures
  124710. ** are benign.
  124711. */
  124712. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  124713. typedef void (*void_function)(void);
  124714. void_function xBenignBegin;
  124715. void_function xBenignEnd;
  124716. xBenignBegin = va_arg(ap, void_function);
  124717. xBenignEnd = va_arg(ap, void_function);
  124718. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  124719. break;
  124720. }
  124721. /*
  124722. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  124723. **
  124724. ** Set the PENDING byte to the value in the argument, if X>0.
  124725. ** Make no changes if X==0. Return the value of the pending byte
  124726. ** as it existing before this routine was called.
  124727. **
  124728. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  124729. ** an incompatible database file format. Changing the PENDING byte
  124730. ** while any database connection is open results in undefined and
  124731. ** deleterious behavior.
  124732. */
  124733. case SQLITE_TESTCTRL_PENDING_BYTE: {
  124734. rc = PENDING_BYTE;
  124735. #ifndef SQLITE_OMIT_WSD
  124736. {
  124737. unsigned int newVal = va_arg(ap, unsigned int);
  124738. if( newVal ) sqlite3PendingByte = newVal;
  124739. }
  124740. #endif
  124741. break;
  124742. }
  124743. /*
  124744. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  124745. **
  124746. ** This action provides a run-time test to see whether or not
  124747. ** assert() was enabled at compile-time. If X is true and assert()
  124748. ** is enabled, then the return value is true. If X is true and
  124749. ** assert() is disabled, then the return value is zero. If X is
  124750. ** false and assert() is enabled, then the assertion fires and the
  124751. ** process aborts. If X is false and assert() is disabled, then the
  124752. ** return value is zero.
  124753. */
  124754. case SQLITE_TESTCTRL_ASSERT: {
  124755. volatile int x = 0;
  124756. assert( (x = va_arg(ap,int))!=0 );
  124757. rc = x;
  124758. break;
  124759. }
  124760. /*
  124761. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  124762. **
  124763. ** This action provides a run-time test to see how the ALWAYS and
  124764. ** NEVER macros were defined at compile-time.
  124765. **
  124766. ** The return value is ALWAYS(X).
  124767. **
  124768. ** The recommended test is X==2. If the return value is 2, that means
  124769. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  124770. ** default setting. If the return value is 1, then ALWAYS() is either
  124771. ** hard-coded to true or else it asserts if its argument is false.
  124772. ** The first behavior (hard-coded to true) is the case if
  124773. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  124774. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  124775. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  124776. **
  124777. ** The run-time test procedure might look something like this:
  124778. **
  124779. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  124780. ** // ALWAYS() and NEVER() are no-op pass-through macros
  124781. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  124782. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  124783. ** }else{
  124784. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  124785. ** }
  124786. */
  124787. case SQLITE_TESTCTRL_ALWAYS: {
  124788. int x = va_arg(ap,int);
  124789. rc = ALWAYS(x);
  124790. break;
  124791. }
  124792. /*
  124793. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  124794. **
  124795. ** The integer returned reveals the byte-order of the computer on which
  124796. ** SQLite is running:
  124797. **
  124798. ** 1 big-endian, determined at run-time
  124799. ** 10 little-endian, determined at run-time
  124800. ** 432101 big-endian, determined at compile-time
  124801. ** 123410 little-endian, determined at compile-time
  124802. */
  124803. case SQLITE_TESTCTRL_BYTEORDER: {
  124804. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  124805. break;
  124806. }
  124807. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  124808. **
  124809. ** Set the nReserve size to N for the main database on the database
  124810. ** connection db.
  124811. */
  124812. case SQLITE_TESTCTRL_RESERVE: {
  124813. sqlite3 *db = va_arg(ap, sqlite3*);
  124814. int x = va_arg(ap,int);
  124815. sqlite3_mutex_enter(db->mutex);
  124816. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  124817. sqlite3_mutex_leave(db->mutex);
  124818. break;
  124819. }
  124820. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  124821. **
  124822. ** Enable or disable various optimizations for testing purposes. The
  124823. ** argument N is a bitmask of optimizations to be disabled. For normal
  124824. ** operation N should be 0. The idea is that a test program (like the
  124825. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  124826. ** with various optimizations disabled to verify that the same answer
  124827. ** is obtained in every case.
  124828. */
  124829. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  124830. sqlite3 *db = va_arg(ap, sqlite3*);
  124831. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  124832. break;
  124833. }
  124834. #ifdef SQLITE_N_KEYWORD
  124835. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  124836. **
  124837. ** If zWord is a keyword recognized by the parser, then return the
  124838. ** number of keywords. Or if zWord is not a keyword, return 0.
  124839. **
  124840. ** This test feature is only available in the amalgamation since
  124841. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  124842. ** is built using separate source files.
  124843. */
  124844. case SQLITE_TESTCTRL_ISKEYWORD: {
  124845. const char *zWord = va_arg(ap, const char*);
  124846. int n = sqlite3Strlen30(zWord);
  124847. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  124848. break;
  124849. }
  124850. #endif
  124851. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  124852. **
  124853. ** Pass pFree into sqlite3ScratchFree().
  124854. ** If sz>0 then allocate a scratch buffer into pNew.
  124855. */
  124856. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  124857. void *pFree, **ppNew;
  124858. int sz;
  124859. sz = va_arg(ap, int);
  124860. ppNew = va_arg(ap, void**);
  124861. pFree = va_arg(ap, void*);
  124862. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  124863. sqlite3ScratchFree(pFree);
  124864. break;
  124865. }
  124866. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  124867. **
  124868. ** If parameter onoff is non-zero, configure the wrappers so that all
  124869. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  124870. ** undo this setting.
  124871. */
  124872. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  124873. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  124874. break;
  124875. }
  124876. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  124877. **
  124878. ** Set or clear a flag that indicates that the database file is always well-
  124879. ** formed and never corrupt. This flag is clear by default, indicating that
  124880. ** database files might have arbitrary corruption. Setting the flag during
  124881. ** testing causes certain assert() statements in the code to be activated
  124882. ** that demonstrat invariants on well-formed database files.
  124883. */
  124884. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  124885. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  124886. break;
  124887. }
  124888. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  124889. **
  124890. ** Set the VDBE coverage callback function to xCallback with context
  124891. ** pointer ptr.
  124892. */
  124893. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  124894. #ifdef SQLITE_VDBE_COVERAGE
  124895. typedef void (*branch_callback)(void*,int,u8,u8);
  124896. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  124897. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  124898. #endif
  124899. break;
  124900. }
  124901. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  124902. case SQLITE_TESTCTRL_SORTER_MMAP: {
  124903. sqlite3 *db = va_arg(ap, sqlite3*);
  124904. db->nMaxSorterMmap = va_arg(ap, int);
  124905. break;
  124906. }
  124907. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  124908. **
  124909. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  124910. ** not.
  124911. */
  124912. case SQLITE_TESTCTRL_ISINIT: {
  124913. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  124914. break;
  124915. }
  124916. /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
  124917. **
  124918. ** This test control is used to create imposter tables. "db" is a pointer
  124919. ** to the database connection. dbName is the database name (ex: "main" or
  124920. ** "temp") which will receive the imposter. "onOff" turns imposter mode on
  124921. ** or off. "tnum" is the root page of the b-tree to which the imposter
  124922. ** table should connect.
  124923. **
  124924. ** Enable imposter mode only when the schema has already been parsed. Then
  124925. ** run a single CREATE TABLE statement to construct the imposter table in
  124926. ** the parsed schema. Then turn imposter mode back off again.
  124927. **
  124928. ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
  124929. ** the schema to be reparsed the next time it is needed. This has the
  124930. ** effect of erasing all imposter tables.
  124931. */
  124932. case SQLITE_TESTCTRL_IMPOSTER: {
  124933. sqlite3 *db = va_arg(ap, sqlite3*);
  124934. sqlite3_mutex_enter(db->mutex);
  124935. db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
  124936. db->init.busy = db->init.imposterTable = va_arg(ap,int);
  124937. db->init.newTnum = va_arg(ap,int);
  124938. if( db->init.busy==0 && db->init.newTnum>0 ){
  124939. sqlite3ResetAllSchemasOfConnection(db);
  124940. }
  124941. sqlite3_mutex_leave(db->mutex);
  124942. break;
  124943. }
  124944. }
  124945. va_end(ap);
  124946. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  124947. return rc;
  124948. }
  124949. /*
  124950. ** This is a utility routine, useful to VFS implementations, that checks
  124951. ** to see if a database file was a URI that contained a specific query
  124952. ** parameter, and if so obtains the value of the query parameter.
  124953. **
  124954. ** The zFilename argument is the filename pointer passed into the xOpen()
  124955. ** method of a VFS implementation. The zParam argument is the name of the
  124956. ** query parameter we seek. This routine returns the value of the zParam
  124957. ** parameter if it exists. If the parameter does not exist, this routine
  124958. ** returns a NULL pointer.
  124959. */
  124960. SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  124961. if( zFilename==0 || zParam==0 ) return 0;
  124962. zFilename += sqlite3Strlen30(zFilename) + 1;
  124963. while( zFilename[0] ){
  124964. int x = strcmp(zFilename, zParam);
  124965. zFilename += sqlite3Strlen30(zFilename) + 1;
  124966. if( x==0 ) return zFilename;
  124967. zFilename += sqlite3Strlen30(zFilename) + 1;
  124968. }
  124969. return 0;
  124970. }
  124971. /*
  124972. ** Return a boolean value for a query parameter.
  124973. */
  124974. SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  124975. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  124976. bDflt = bDflt!=0;
  124977. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  124978. }
  124979. /*
  124980. ** Return a 64-bit integer value for a query parameter.
  124981. */
  124982. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
  124983. const char *zFilename, /* Filename as passed to xOpen */
  124984. const char *zParam, /* URI parameter sought */
  124985. sqlite3_int64 bDflt /* return if parameter is missing */
  124986. ){
  124987. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  124988. sqlite3_int64 v;
  124989. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  124990. bDflt = v;
  124991. }
  124992. return bDflt;
  124993. }
  124994. /*
  124995. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  124996. */
  124997. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  124998. int i;
  124999. for(i=0; i<db->nDb; i++){
  125000. if( db->aDb[i].pBt
  125001. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  125002. ){
  125003. return db->aDb[i].pBt;
  125004. }
  125005. }
  125006. return 0;
  125007. }
  125008. /*
  125009. ** Return the filename of the database associated with a database
  125010. ** connection.
  125011. */
  125012. SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  125013. Btree *pBt;
  125014. #ifdef SQLITE_ENABLE_API_ARMOR
  125015. if( !sqlite3SafetyCheckOk(db) ){
  125016. (void)SQLITE_MISUSE_BKPT;
  125017. return 0;
  125018. }
  125019. #endif
  125020. pBt = sqlite3DbNameToBtree(db, zDbName);
  125021. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  125022. }
  125023. /*
  125024. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  125025. ** no such database exists.
  125026. */
  125027. SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  125028. Btree *pBt;
  125029. #ifdef SQLITE_ENABLE_API_ARMOR
  125030. if( !sqlite3SafetyCheckOk(db) ){
  125031. (void)SQLITE_MISUSE_BKPT;
  125032. return -1;
  125033. }
  125034. #endif
  125035. pBt = sqlite3DbNameToBtree(db, zDbName);
  125036. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  125037. }
  125038. /************** End of main.c ************************************************/
  125039. /************** Begin file notify.c ******************************************/
  125040. /*
  125041. ** 2009 March 3
  125042. **
  125043. ** The author disclaims copyright to this source code. In place of
  125044. ** a legal notice, here is a blessing:
  125045. **
  125046. ** May you do good and not evil.
  125047. ** May you find forgiveness for yourself and forgive others.
  125048. ** May you share freely, never taking more than you give.
  125049. **
  125050. *************************************************************************
  125051. **
  125052. ** This file contains the implementation of the sqlite3_unlock_notify()
  125053. ** API method and its associated functionality.
  125054. */
  125055. /* #include "sqliteInt.h" */
  125056. /* #include "btreeInt.h" */
  125057. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  125058. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  125059. /*
  125060. ** Public interfaces:
  125061. **
  125062. ** sqlite3ConnectionBlocked()
  125063. ** sqlite3ConnectionUnlocked()
  125064. ** sqlite3ConnectionClosed()
  125065. ** sqlite3_unlock_notify()
  125066. */
  125067. #define assertMutexHeld() \
  125068. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  125069. /*
  125070. ** Head of a linked list of all sqlite3 objects created by this process
  125071. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  125072. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  125073. ** mutex is held.
  125074. */
  125075. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  125076. #ifndef NDEBUG
  125077. /*
  125078. ** This function is a complex assert() that verifies the following
  125079. ** properties of the blocked connections list:
  125080. **
  125081. ** 1) Each entry in the list has a non-NULL value for either
  125082. ** pUnlockConnection or pBlockingConnection, or both.
  125083. **
  125084. ** 2) All entries in the list that share a common value for
  125085. ** xUnlockNotify are grouped together.
  125086. **
  125087. ** 3) If the argument db is not NULL, then none of the entries in the
  125088. ** blocked connections list have pUnlockConnection or pBlockingConnection
  125089. ** set to db. This is used when closing connection db.
  125090. */
  125091. static void checkListProperties(sqlite3 *db){
  125092. sqlite3 *p;
  125093. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  125094. int seen = 0;
  125095. sqlite3 *p2;
  125096. /* Verify property (1) */
  125097. assert( p->pUnlockConnection || p->pBlockingConnection );
  125098. /* Verify property (2) */
  125099. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  125100. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  125101. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  125102. assert( db==0 || p->pUnlockConnection!=db );
  125103. assert( db==0 || p->pBlockingConnection!=db );
  125104. }
  125105. }
  125106. }
  125107. #else
  125108. # define checkListProperties(x)
  125109. #endif
  125110. /*
  125111. ** Remove connection db from the blocked connections list. If connection
  125112. ** db is not currently a part of the list, this function is a no-op.
  125113. */
  125114. static void removeFromBlockedList(sqlite3 *db){
  125115. sqlite3 **pp;
  125116. assertMutexHeld();
  125117. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  125118. if( *pp==db ){
  125119. *pp = (*pp)->pNextBlocked;
  125120. break;
  125121. }
  125122. }
  125123. }
  125124. /*
  125125. ** Add connection db to the blocked connections list. It is assumed
  125126. ** that it is not already a part of the list.
  125127. */
  125128. static void addToBlockedList(sqlite3 *db){
  125129. sqlite3 **pp;
  125130. assertMutexHeld();
  125131. for(
  125132. pp=&sqlite3BlockedList;
  125133. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  125134. pp=&(*pp)->pNextBlocked
  125135. );
  125136. db->pNextBlocked = *pp;
  125137. *pp = db;
  125138. }
  125139. /*
  125140. ** Obtain the STATIC_MASTER mutex.
  125141. */
  125142. static void enterMutex(void){
  125143. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  125144. checkListProperties(0);
  125145. }
  125146. /*
  125147. ** Release the STATIC_MASTER mutex.
  125148. */
  125149. static void leaveMutex(void){
  125150. assertMutexHeld();
  125151. checkListProperties(0);
  125152. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  125153. }
  125154. /*
  125155. ** Register an unlock-notify callback.
  125156. **
  125157. ** This is called after connection "db" has attempted some operation
  125158. ** but has received an SQLITE_LOCKED error because another connection
  125159. ** (call it pOther) in the same process was busy using the same shared
  125160. ** cache. pOther is found by looking at db->pBlockingConnection.
  125161. **
  125162. ** If there is no blocking connection, the callback is invoked immediately,
  125163. ** before this routine returns.
  125164. **
  125165. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  125166. ** a deadlock.
  125167. **
  125168. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  125169. ** its locks.
  125170. **
  125171. ** Each call to this routine overrides any prior callbacks registered
  125172. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  125173. ** cancelled.
  125174. */
  125175. SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
  125176. sqlite3 *db,
  125177. void (*xNotify)(void **, int),
  125178. void *pArg
  125179. ){
  125180. int rc = SQLITE_OK;
  125181. sqlite3_mutex_enter(db->mutex);
  125182. enterMutex();
  125183. if( xNotify==0 ){
  125184. removeFromBlockedList(db);
  125185. db->pBlockingConnection = 0;
  125186. db->pUnlockConnection = 0;
  125187. db->xUnlockNotify = 0;
  125188. db->pUnlockArg = 0;
  125189. }else if( 0==db->pBlockingConnection ){
  125190. /* The blocking transaction has been concluded. Or there never was a
  125191. ** blocking transaction. In either case, invoke the notify callback
  125192. ** immediately.
  125193. */
  125194. xNotify(&pArg, 1);
  125195. }else{
  125196. sqlite3 *p;
  125197. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  125198. if( p ){
  125199. rc = SQLITE_LOCKED; /* Deadlock detected. */
  125200. }else{
  125201. db->pUnlockConnection = db->pBlockingConnection;
  125202. db->xUnlockNotify = xNotify;
  125203. db->pUnlockArg = pArg;
  125204. removeFromBlockedList(db);
  125205. addToBlockedList(db);
  125206. }
  125207. }
  125208. leaveMutex();
  125209. assert( !db->mallocFailed );
  125210. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  125211. sqlite3_mutex_leave(db->mutex);
  125212. return rc;
  125213. }
  125214. /*
  125215. ** This function is called while stepping or preparing a statement
  125216. ** associated with connection db. The operation will return SQLITE_LOCKED
  125217. ** to the user because it requires a lock that will not be available
  125218. ** until connection pBlocker concludes its current transaction.
  125219. */
  125220. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  125221. enterMutex();
  125222. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  125223. addToBlockedList(db);
  125224. }
  125225. db->pBlockingConnection = pBlocker;
  125226. leaveMutex();
  125227. }
  125228. /*
  125229. ** This function is called when
  125230. ** the transaction opened by database db has just finished. Locks held
  125231. ** by database connection db have been released.
  125232. **
  125233. ** This function loops through each entry in the blocked connections
  125234. ** list and does the following:
  125235. **
  125236. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  125237. ** set to db, then set pBlockingConnection=0.
  125238. **
  125239. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  125240. ** set to db, then invoke the configured unlock-notify callback and
  125241. ** set pUnlockConnection=0.
  125242. **
  125243. ** 3) If the two steps above mean that pBlockingConnection==0 and
  125244. ** pUnlockConnection==0, remove the entry from the blocked connections
  125245. ** list.
  125246. */
  125247. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  125248. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  125249. int nArg = 0; /* Number of entries in aArg[] */
  125250. sqlite3 **pp; /* Iterator variable */
  125251. void **aArg; /* Arguments to the unlock callback */
  125252. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  125253. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  125254. aArg = aStatic;
  125255. enterMutex(); /* Enter STATIC_MASTER mutex */
  125256. /* This loop runs once for each entry in the blocked-connections list. */
  125257. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  125258. sqlite3 *p = *pp;
  125259. /* Step 1. */
  125260. if( p->pBlockingConnection==db ){
  125261. p->pBlockingConnection = 0;
  125262. }
  125263. /* Step 2. */
  125264. if( p->pUnlockConnection==db ){
  125265. assert( p->xUnlockNotify );
  125266. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  125267. xUnlockNotify(aArg, nArg);
  125268. nArg = 0;
  125269. }
  125270. sqlite3BeginBenignMalloc();
  125271. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  125272. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  125273. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  125274. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  125275. ){
  125276. /* The aArg[] array needs to grow. */
  125277. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  125278. if( pNew ){
  125279. memcpy(pNew, aArg, nArg*sizeof(void *));
  125280. sqlite3_free(aDyn);
  125281. aDyn = aArg = pNew;
  125282. }else{
  125283. /* This occurs when the array of context pointers that need to
  125284. ** be passed to the unlock-notify callback is larger than the
  125285. ** aStatic[] array allocated on the stack and the attempt to
  125286. ** allocate a larger array from the heap has failed.
  125287. **
  125288. ** This is a difficult situation to handle. Returning an error
  125289. ** code to the caller is insufficient, as even if an error code
  125290. ** is returned the transaction on connection db will still be
  125291. ** closed and the unlock-notify callbacks on blocked connections
  125292. ** will go unissued. This might cause the application to wait
  125293. ** indefinitely for an unlock-notify callback that will never
  125294. ** arrive.
  125295. **
  125296. ** Instead, invoke the unlock-notify callback with the context
  125297. ** array already accumulated. We can then clear the array and
  125298. ** begin accumulating any further context pointers without
  125299. ** requiring any dynamic allocation. This is sub-optimal because
  125300. ** it means that instead of one callback with a large array of
  125301. ** context pointers the application will receive two or more
  125302. ** callbacks with smaller arrays of context pointers, which will
  125303. ** reduce the applications ability to prioritize multiple
  125304. ** connections. But it is the best that can be done under the
  125305. ** circumstances.
  125306. */
  125307. xUnlockNotify(aArg, nArg);
  125308. nArg = 0;
  125309. }
  125310. }
  125311. sqlite3EndBenignMalloc();
  125312. aArg[nArg++] = p->pUnlockArg;
  125313. xUnlockNotify = p->xUnlockNotify;
  125314. p->pUnlockConnection = 0;
  125315. p->xUnlockNotify = 0;
  125316. p->pUnlockArg = 0;
  125317. }
  125318. /* Step 3. */
  125319. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  125320. /* Remove connection p from the blocked connections list. */
  125321. *pp = p->pNextBlocked;
  125322. p->pNextBlocked = 0;
  125323. }else{
  125324. pp = &p->pNextBlocked;
  125325. }
  125326. }
  125327. if( nArg!=0 ){
  125328. xUnlockNotify(aArg, nArg);
  125329. }
  125330. sqlite3_free(aDyn);
  125331. leaveMutex(); /* Leave STATIC_MASTER mutex */
  125332. }
  125333. /*
  125334. ** This is called when the database connection passed as an argument is
  125335. ** being closed. The connection is removed from the blocked list.
  125336. */
  125337. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  125338. sqlite3ConnectionUnlocked(db);
  125339. enterMutex();
  125340. removeFromBlockedList(db);
  125341. checkListProperties(db);
  125342. leaveMutex();
  125343. }
  125344. #endif
  125345. /************** End of notify.c **********************************************/
  125346. /************** Begin file fts3.c ********************************************/
  125347. /*
  125348. ** 2006 Oct 10
  125349. **
  125350. ** The author disclaims copyright to this source code. In place of
  125351. ** a legal notice, here is a blessing:
  125352. **
  125353. ** May you do good and not evil.
  125354. ** May you find forgiveness for yourself and forgive others.
  125355. ** May you share freely, never taking more than you give.
  125356. **
  125357. ******************************************************************************
  125358. **
  125359. ** This is an SQLite module implementing full-text search.
  125360. */
  125361. /*
  125362. ** The code in this file is only compiled if:
  125363. **
  125364. ** * The FTS3 module is being built as an extension
  125365. ** (in which case SQLITE_CORE is not defined), or
  125366. **
  125367. ** * The FTS3 module is being built into the core of
  125368. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  125369. */
  125370. /* The full-text index is stored in a series of b+tree (-like)
  125371. ** structures called segments which map terms to doclists. The
  125372. ** structures are like b+trees in layout, but are constructed from the
  125373. ** bottom up in optimal fashion and are not updatable. Since trees
  125374. ** are built from the bottom up, things will be described from the
  125375. ** bottom up.
  125376. **
  125377. **
  125378. **** Varints ****
  125379. ** The basic unit of encoding is a variable-length integer called a
  125380. ** varint. We encode variable-length integers in little-endian order
  125381. ** using seven bits * per byte as follows:
  125382. **
  125383. ** KEY:
  125384. ** A = 0xxxxxxx 7 bits of data and one flag bit
  125385. ** B = 1xxxxxxx 7 bits of data and one flag bit
  125386. **
  125387. ** 7 bits - A
  125388. ** 14 bits - BA
  125389. ** 21 bits - BBA
  125390. ** and so on.
  125391. **
  125392. ** This is similar in concept to how sqlite encodes "varints" but
  125393. ** the encoding is not the same. SQLite varints are big-endian
  125394. ** are are limited to 9 bytes in length whereas FTS3 varints are
  125395. ** little-endian and can be up to 10 bytes in length (in theory).
  125396. **
  125397. ** Example encodings:
  125398. **
  125399. ** 1: 0x01
  125400. ** 127: 0x7f
  125401. ** 128: 0x81 0x00
  125402. **
  125403. **
  125404. **** Document lists ****
  125405. ** A doclist (document list) holds a docid-sorted list of hits for a
  125406. ** given term. Doclists hold docids and associated token positions.
  125407. ** A docid is the unique integer identifier for a single document.
  125408. ** A position is the index of a word within the document. The first
  125409. ** word of the document has a position of 0.
  125410. **
  125411. ** FTS3 used to optionally store character offsets using a compile-time
  125412. ** option. But that functionality is no longer supported.
  125413. **
  125414. ** A doclist is stored like this:
  125415. **
  125416. ** array {
  125417. ** varint docid; (delta from previous doclist)
  125418. ** array { (position list for column 0)
  125419. ** varint position; (2 more than the delta from previous position)
  125420. ** }
  125421. ** array {
  125422. ** varint POS_COLUMN; (marks start of position list for new column)
  125423. ** varint column; (index of new column)
  125424. ** array {
  125425. ** varint position; (2 more than the delta from previous position)
  125426. ** }
  125427. ** }
  125428. ** varint POS_END; (marks end of positions for this document.
  125429. ** }
  125430. **
  125431. ** Here, array { X } means zero or more occurrences of X, adjacent in
  125432. ** memory. A "position" is an index of a token in the token stream
  125433. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  125434. ** in the same logical place as the position element, and act as sentinals
  125435. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  125436. ** The positions numbers are not stored literally but rather as two more
  125437. ** than the difference from the prior position, or the just the position plus
  125438. ** 2 for the first position. Example:
  125439. **
  125440. ** label: A B C D E F G H I J K
  125441. ** value: 123 5 9 1 1 14 35 0 234 72 0
  125442. **
  125443. ** The 123 value is the first docid. For column zero in this document
  125444. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  125445. ** at D signals the start of a new column; the 1 at E indicates that the
  125446. ** new column is column number 1. There are two positions at 12 and 45
  125447. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  125448. ** 234 at I is the delta to next docid (357). It has one position 70
  125449. ** (72-2) and then terminates with the 0 at K.
  125450. **
  125451. ** A "position-list" is the list of positions for multiple columns for
  125452. ** a single docid. A "column-list" is the set of positions for a single
  125453. ** column. Hence, a position-list consists of one or more column-lists,
  125454. ** a document record consists of a docid followed by a position-list and
  125455. ** a doclist consists of one or more document records.
  125456. **
  125457. ** A bare doclist omits the position information, becoming an
  125458. ** array of varint-encoded docids.
  125459. **
  125460. **** Segment leaf nodes ****
  125461. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  125462. ** nodes are written using LeafWriter, and read using LeafReader (to
  125463. ** iterate through a single leaf node's data) and LeavesReader (to
  125464. ** iterate through a segment's entire leaf layer). Leaf nodes have
  125465. ** the format:
  125466. **
  125467. ** varint iHeight; (height from leaf level, always 0)
  125468. ** varint nTerm; (length of first term)
  125469. ** char pTerm[nTerm]; (content of first term)
  125470. ** varint nDoclist; (length of term's associated doclist)
  125471. ** char pDoclist[nDoclist]; (content of doclist)
  125472. ** array {
  125473. ** (further terms are delta-encoded)
  125474. ** varint nPrefix; (length of prefix shared with previous term)
  125475. ** varint nSuffix; (length of unshared suffix)
  125476. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  125477. ** varint nDoclist; (length of term's associated doclist)
  125478. ** char pDoclist[nDoclist]; (content of doclist)
  125479. ** }
  125480. **
  125481. ** Here, array { X } means zero or more occurrences of X, adjacent in
  125482. ** memory.
  125483. **
  125484. ** Leaf nodes are broken into blocks which are stored contiguously in
  125485. ** the %_segments table in sorted order. This means that when the end
  125486. ** of a node is reached, the next term is in the node with the next
  125487. ** greater node id.
  125488. **
  125489. ** New data is spilled to a new leaf node when the current node
  125490. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  125491. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  125492. ** node (a leaf node with a single term and doclist). The goal of
  125493. ** these settings is to pack together groups of small doclists while
  125494. ** making it efficient to directly access large doclists. The
  125495. ** assumption is that large doclists represent terms which are more
  125496. ** likely to be query targets.
  125497. **
  125498. ** TODO(shess) It may be useful for blocking decisions to be more
  125499. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  125500. ** node rather than splitting into 2k and .5k nodes. My intuition is
  125501. ** that this might extend through 2x or 4x the pagesize.
  125502. **
  125503. **
  125504. **** Segment interior nodes ****
  125505. ** Segment interior nodes store blockids for subtree nodes and terms
  125506. ** to describe what data is stored by the each subtree. Interior
  125507. ** nodes are written using InteriorWriter, and read using
  125508. ** InteriorReader. InteriorWriters are created as needed when
  125509. ** SegmentWriter creates new leaf nodes, or when an interior node
  125510. ** itself grows too big and must be split. The format of interior
  125511. ** nodes:
  125512. **
  125513. ** varint iHeight; (height from leaf level, always >0)
  125514. ** varint iBlockid; (block id of node's leftmost subtree)
  125515. ** optional {
  125516. ** varint nTerm; (length of first term)
  125517. ** char pTerm[nTerm]; (content of first term)
  125518. ** array {
  125519. ** (further terms are delta-encoded)
  125520. ** varint nPrefix; (length of shared prefix with previous term)
  125521. ** varint nSuffix; (length of unshared suffix)
  125522. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  125523. ** }
  125524. ** }
  125525. **
  125526. ** Here, optional { X } means an optional element, while array { X }
  125527. ** means zero or more occurrences of X, adjacent in memory.
  125528. **
  125529. ** An interior node encodes n terms separating n+1 subtrees. The
  125530. ** subtree blocks are contiguous, so only the first subtree's blockid
  125531. ** is encoded. The subtree at iBlockid will contain all terms less
  125532. ** than the first term encoded (or all terms if no term is encoded).
  125533. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  125534. ** than pTerm[i+1], the subtree for that term will be rooted at
  125535. ** iBlockid+i. Interior nodes only store enough term data to
  125536. ** distinguish adjacent children (if the rightmost term of the left
  125537. ** child is "something", and the leftmost term of the right child is
  125538. ** "wicked", only "w" is stored).
  125539. **
  125540. ** New data is spilled to a new interior node at the same height when
  125541. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  125542. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  125543. ** interior nodes and making the tree too skinny. The interior nodes
  125544. ** at a given height are naturally tracked by interior nodes at
  125545. ** height+1, and so on.
  125546. **
  125547. **
  125548. **** Segment directory ****
  125549. ** The segment directory in table %_segdir stores meta-information for
  125550. ** merging and deleting segments, and also the root node of the
  125551. ** segment's tree.
  125552. **
  125553. ** The root node is the top node of the segment's tree after encoding
  125554. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  125555. ** This could be either a leaf node or an interior node. If the top
  125556. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  125557. ** and a new root interior node is generated (which should always fit
  125558. ** within ROOT_MAX because it only needs space for 2 varints, the
  125559. ** height and the blockid of the previous root).
  125560. **
  125561. ** The meta-information in the segment directory is:
  125562. ** level - segment level (see below)
  125563. ** idx - index within level
  125564. ** - (level,idx uniquely identify a segment)
  125565. ** start_block - first leaf node
  125566. ** leaves_end_block - last leaf node
  125567. ** end_block - last block (including interior nodes)
  125568. ** root - contents of root node
  125569. **
  125570. ** If the root node is a leaf node, then start_block,
  125571. ** leaves_end_block, and end_block are all 0.
  125572. **
  125573. **
  125574. **** Segment merging ****
  125575. ** To amortize update costs, segments are grouped into levels and
  125576. ** merged in batches. Each increase in level represents exponentially
  125577. ** more documents.
  125578. **
  125579. ** New documents (actually, document updates) are tokenized and
  125580. ** written individually (using LeafWriter) to a level 0 segment, with
  125581. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  125582. ** level 0 segments are merged into a single level 1 segment. Level 1
  125583. ** is populated like level 0, and eventually MERGE_COUNT level 1
  125584. ** segments are merged to a single level 2 segment (representing
  125585. ** MERGE_COUNT^2 updates), and so on.
  125586. **
  125587. ** A segment merge traverses all segments at a given level in
  125588. ** parallel, performing a straightforward sorted merge. Since segment
  125589. ** leaf nodes are written in to the %_segments table in order, this
  125590. ** merge traverses the underlying sqlite disk structures efficiently.
  125591. ** After the merge, all segment blocks from the merged level are
  125592. ** deleted.
  125593. **
  125594. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  125595. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  125596. ** very similar performance numbers to 16 on insertion, though they're
  125597. ** a tiny bit slower (perhaps due to more overhead in merge-time
  125598. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  125599. ** 16, 2 about 66% slower than 16.
  125600. **
  125601. ** At query time, high MERGE_COUNT increases the number of segments
  125602. ** which need to be scanned and merged. For instance, with 100k docs
  125603. ** inserted:
  125604. **
  125605. ** MERGE_COUNT segments
  125606. ** 16 25
  125607. ** 8 12
  125608. ** 4 10
  125609. ** 2 6
  125610. **
  125611. ** This appears to have only a moderate impact on queries for very
  125612. ** frequent terms (which are somewhat dominated by segment merge
  125613. ** costs), and infrequent and non-existent terms still seem to be fast
  125614. ** even with many segments.
  125615. **
  125616. ** TODO(shess) That said, it would be nice to have a better query-side
  125617. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  125618. ** optimizations to things like doclist merging will swing the sweet
  125619. ** spot around.
  125620. **
  125621. **
  125622. **
  125623. **** Handling of deletions and updates ****
  125624. ** Since we're using a segmented structure, with no docid-oriented
  125625. ** index into the term index, we clearly cannot simply update the term
  125626. ** index when a document is deleted or updated. For deletions, we
  125627. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  125628. ** we simply write the new doclist. Segment merges overwrite older
  125629. ** data for a particular docid with newer data, so deletes or updates
  125630. ** will eventually overtake the earlier data and knock it out. The
  125631. ** query logic likewise merges doclists so that newer data knocks out
  125632. ** older data.
  125633. */
  125634. /************** Include fts3Int.h in the middle of fts3.c ********************/
  125635. /************** Begin file fts3Int.h *****************************************/
  125636. /*
  125637. ** 2009 Nov 12
  125638. **
  125639. ** The author disclaims copyright to this source code. In place of
  125640. ** a legal notice, here is a blessing:
  125641. **
  125642. ** May you do good and not evil.
  125643. ** May you find forgiveness for yourself and forgive others.
  125644. ** May you share freely, never taking more than you give.
  125645. **
  125646. ******************************************************************************
  125647. **
  125648. */
  125649. #ifndef _FTSINT_H
  125650. #define _FTSINT_H
  125651. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  125652. # define NDEBUG 1
  125653. #endif
  125654. /*
  125655. ** FTS4 is really an extension for FTS3. It is enabled using the
  125656. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  125657. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  125658. */
  125659. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  125660. # define SQLITE_ENABLE_FTS3
  125661. #endif
  125662. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125663. /* If not building as part of the core, include sqlite3ext.h. */
  125664. #ifndef SQLITE_CORE
  125665. /* # include "sqlite3ext.h" */
  125666. SQLITE_EXTENSION_INIT3
  125667. #endif
  125668. /* #include "sqlite3.h" */
  125669. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  125670. /************** Begin file fts3_tokenizer.h **********************************/
  125671. /*
  125672. ** 2006 July 10
  125673. **
  125674. ** The author disclaims copyright to this source code.
  125675. **
  125676. *************************************************************************
  125677. ** Defines the interface to tokenizers used by fulltext-search. There
  125678. ** are three basic components:
  125679. **
  125680. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  125681. ** interface functions. This is essentially the class structure for
  125682. ** tokenizers.
  125683. **
  125684. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  125685. ** including customization information defined at creation time.
  125686. **
  125687. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  125688. ** tokens from a particular input.
  125689. */
  125690. #ifndef _FTS3_TOKENIZER_H_
  125691. #define _FTS3_TOKENIZER_H_
  125692. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  125693. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  125694. ** we will need a way to register the API consistently.
  125695. */
  125696. /* #include "sqlite3.h" */
  125697. /*
  125698. ** Structures used by the tokenizer interface. When a new tokenizer
  125699. ** implementation is registered, the caller provides a pointer to
  125700. ** an sqlite3_tokenizer_module containing pointers to the callback
  125701. ** functions that make up an implementation.
  125702. **
  125703. ** When an fts3 table is created, it passes any arguments passed to
  125704. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  125705. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  125706. ** implementation. The xCreate() function in turn returns an
  125707. ** sqlite3_tokenizer structure representing the specific tokenizer to
  125708. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  125709. **
  125710. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  125711. ** method is called. It returns an sqlite3_tokenizer_cursor object
  125712. ** that may be used to tokenize a specific input buffer based on
  125713. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  125714. ** object.
  125715. */
  125716. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  125717. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  125718. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  125719. struct sqlite3_tokenizer_module {
  125720. /*
  125721. ** Structure version. Should always be set to 0 or 1.
  125722. */
  125723. int iVersion;
  125724. /*
  125725. ** Create a new tokenizer. The values in the argv[] array are the
  125726. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  125727. ** TABLE statement that created the fts3 table. For example, if
  125728. ** the following SQL is executed:
  125729. **
  125730. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  125731. **
  125732. ** then argc is set to 2, and the argv[] array contains pointers
  125733. ** to the strings "arg1" and "arg2".
  125734. **
  125735. ** This method should return either SQLITE_OK (0), or an SQLite error
  125736. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  125737. ** to point at the newly created tokenizer structure. The generic
  125738. ** sqlite3_tokenizer.pModule variable should not be initialized by
  125739. ** this callback. The caller will do so.
  125740. */
  125741. int (*xCreate)(
  125742. int argc, /* Size of argv array */
  125743. const char *const*argv, /* Tokenizer argument strings */
  125744. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  125745. );
  125746. /*
  125747. ** Destroy an existing tokenizer. The fts3 module calls this method
  125748. ** exactly once for each successful call to xCreate().
  125749. */
  125750. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  125751. /*
  125752. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  125753. ** is responsible for ensuring that the input buffer remains valid
  125754. ** until the cursor is closed (using the xClose() method).
  125755. */
  125756. int (*xOpen)(
  125757. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  125758. const char *pInput, int nBytes, /* Input buffer */
  125759. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  125760. );
  125761. /*
  125762. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  125763. ** method exactly once for each successful call to xOpen().
  125764. */
  125765. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  125766. /*
  125767. ** Retrieve the next token from the tokenizer cursor pCursor. This
  125768. ** method should either return SQLITE_OK and set the values of the
  125769. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  125770. ** the end of the buffer has been reached, or an SQLite error code.
  125771. **
  125772. ** *ppToken should be set to point at a buffer containing the
  125773. ** normalized version of the token (i.e. after any case-folding and/or
  125774. ** stemming has been performed). *pnBytes should be set to the length
  125775. ** of this buffer in bytes. The input text that generated the token is
  125776. ** identified by the byte offsets returned in *piStartOffset and
  125777. ** *piEndOffset. *piStartOffset should be set to the index of the first
  125778. ** byte of the token in the input buffer. *piEndOffset should be set
  125779. ** to the index of the first byte just past the end of the token in
  125780. ** the input buffer.
  125781. **
  125782. ** The buffer *ppToken is set to point at is managed by the tokenizer
  125783. ** implementation. It is only required to be valid until the next call
  125784. ** to xNext() or xClose().
  125785. */
  125786. /* TODO(shess) current implementation requires pInput to be
  125787. ** nul-terminated. This should either be fixed, or pInput/nBytes
  125788. ** should be converted to zInput.
  125789. */
  125790. int (*xNext)(
  125791. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  125792. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  125793. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  125794. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  125795. int *piPosition /* OUT: Number of tokens returned before this one */
  125796. );
  125797. /***********************************************************************
  125798. ** Methods below this point are only available if iVersion>=1.
  125799. */
  125800. /*
  125801. ** Configure the language id of a tokenizer cursor.
  125802. */
  125803. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  125804. };
  125805. struct sqlite3_tokenizer {
  125806. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  125807. /* Tokenizer implementations will typically add additional fields */
  125808. };
  125809. struct sqlite3_tokenizer_cursor {
  125810. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  125811. /* Tokenizer implementations will typically add additional fields */
  125812. };
  125813. int fts3_global_term_cnt(int iTerm, int iCol);
  125814. int fts3_term_cnt(int iTerm, int iCol);
  125815. #endif /* _FTS3_TOKENIZER_H_ */
  125816. /************** End of fts3_tokenizer.h **************************************/
  125817. /************** Continuing where we left off in fts3Int.h ********************/
  125818. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  125819. /************** Begin file fts3_hash.h ***************************************/
  125820. /*
  125821. ** 2001 September 22
  125822. **
  125823. ** The author disclaims copyright to this source code. In place of
  125824. ** a legal notice, here is a blessing:
  125825. **
  125826. ** May you do good and not evil.
  125827. ** May you find forgiveness for yourself and forgive others.
  125828. ** May you share freely, never taking more than you give.
  125829. **
  125830. *************************************************************************
  125831. ** This is the header file for the generic hash-table implementation
  125832. ** used in SQLite. We've modified it slightly to serve as a standalone
  125833. ** hash table implementation for the full-text indexing module.
  125834. **
  125835. */
  125836. #ifndef _FTS3_HASH_H_
  125837. #define _FTS3_HASH_H_
  125838. /* Forward declarations of structures. */
  125839. typedef struct Fts3Hash Fts3Hash;
  125840. typedef struct Fts3HashElem Fts3HashElem;
  125841. /* A complete hash table is an instance of the following structure.
  125842. ** The internals of this structure are intended to be opaque -- client
  125843. ** code should not attempt to access or modify the fields of this structure
  125844. ** directly. Change this structure only by using the routines below.
  125845. ** However, many of the "procedures" and "functions" for modifying and
  125846. ** accessing this structure are really macros, so we can't really make
  125847. ** this structure opaque.
  125848. */
  125849. struct Fts3Hash {
  125850. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  125851. char copyKey; /* True if copy of key made on insert */
  125852. int count; /* Number of entries in this table */
  125853. Fts3HashElem *first; /* The first element of the array */
  125854. int htsize; /* Number of buckets in the hash table */
  125855. struct _fts3ht { /* the hash table */
  125856. int count; /* Number of entries with this hash */
  125857. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  125858. } *ht;
  125859. };
  125860. /* Each element in the hash table is an instance of the following
  125861. ** structure. All elements are stored on a single doubly-linked list.
  125862. **
  125863. ** Again, this structure is intended to be opaque, but it can't really
  125864. ** be opaque because it is used by macros.
  125865. */
  125866. struct Fts3HashElem {
  125867. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  125868. void *data; /* Data associated with this element */
  125869. void *pKey; int nKey; /* Key associated with this element */
  125870. };
  125871. /*
  125872. ** There are 2 different modes of operation for a hash table:
  125873. **
  125874. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  125875. ** (including the null-terminator, if any). Case
  125876. ** is respected in comparisons.
  125877. **
  125878. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  125879. ** memcmp() is used to compare keys.
  125880. **
  125881. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  125882. */
  125883. #define FTS3_HASH_STRING 1
  125884. #define FTS3_HASH_BINARY 2
  125885. /*
  125886. ** Access routines. To delete, insert a NULL pointer.
  125887. */
  125888. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  125889. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  125890. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  125891. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  125892. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  125893. /*
  125894. ** Shorthand for the functions above
  125895. */
  125896. #define fts3HashInit sqlite3Fts3HashInit
  125897. #define fts3HashInsert sqlite3Fts3HashInsert
  125898. #define fts3HashFind sqlite3Fts3HashFind
  125899. #define fts3HashClear sqlite3Fts3HashClear
  125900. #define fts3HashFindElem sqlite3Fts3HashFindElem
  125901. /*
  125902. ** Macros for looping over all elements of a hash table. The idiom is
  125903. ** like this:
  125904. **
  125905. ** Fts3Hash h;
  125906. ** Fts3HashElem *p;
  125907. ** ...
  125908. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  125909. ** SomeStructure *pData = fts3HashData(p);
  125910. ** // do something with pData
  125911. ** }
  125912. */
  125913. #define fts3HashFirst(H) ((H)->first)
  125914. #define fts3HashNext(E) ((E)->next)
  125915. #define fts3HashData(E) ((E)->data)
  125916. #define fts3HashKey(E) ((E)->pKey)
  125917. #define fts3HashKeysize(E) ((E)->nKey)
  125918. /*
  125919. ** Number of entries in a hash table
  125920. */
  125921. #define fts3HashCount(H) ((H)->count)
  125922. #endif /* _FTS3_HASH_H_ */
  125923. /************** End of fts3_hash.h *******************************************/
  125924. /************** Continuing where we left off in fts3Int.h ********************/
  125925. /*
  125926. ** This constant determines the maximum depth of an FTS expression tree
  125927. ** that the library will create and use. FTS uses recursion to perform
  125928. ** various operations on the query tree, so the disadvantage of a large
  125929. ** limit is that it may allow very large queries to use large amounts
  125930. ** of stack space (perhaps causing a stack overflow).
  125931. */
  125932. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  125933. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  125934. #endif
  125935. /*
  125936. ** This constant controls how often segments are merged. Once there are
  125937. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  125938. ** segment of level N+1.
  125939. */
  125940. #define FTS3_MERGE_COUNT 16
  125941. /*
  125942. ** This is the maximum amount of data (in bytes) to store in the
  125943. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  125944. ** populated as documents are inserted/updated/deleted in a transaction
  125945. ** and used to create a new segment when the transaction is committed.
  125946. ** However if this limit is reached midway through a transaction, a new
  125947. ** segment is created and the hash table cleared immediately.
  125948. */
  125949. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  125950. /*
  125951. ** Macro to return the number of elements in an array. SQLite has a
  125952. ** similar macro called ArraySize(). Use a different name to avoid
  125953. ** a collision when building an amalgamation with built-in FTS3.
  125954. */
  125955. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  125956. #ifndef MIN
  125957. # define MIN(x,y) ((x)<(y)?(x):(y))
  125958. #endif
  125959. #ifndef MAX
  125960. # define MAX(x,y) ((x)>(y)?(x):(y))
  125961. #endif
  125962. /*
  125963. ** Maximum length of a varint encoded integer. The varint format is different
  125964. ** from that used by SQLite, so the maximum length is 10, not 9.
  125965. */
  125966. #define FTS3_VARINT_MAX 10
  125967. /*
  125968. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  125969. ** in the document set and zero or more prefix indexes. All indexes are stored
  125970. ** as one or more b+-trees in the %_segments and %_segdir tables.
  125971. **
  125972. ** It is possible to determine which index a b+-tree belongs to based on the
  125973. ** value stored in the "%_segdir.level" column. Given this value L, the index
  125974. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  125975. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  125976. ** between 1024 and 2047 to index 1, and so on.
  125977. **
  125978. ** It is considered impossible for an index to use more than 1024 levels. In
  125979. ** theory though this may happen, but only after at least
  125980. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  125981. */
  125982. #define FTS3_SEGDIR_MAXLEVEL 1024
  125983. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  125984. /*
  125985. ** The testcase() macro is only used by the amalgamation. If undefined,
  125986. ** make it a no-op.
  125987. */
  125988. #ifndef testcase
  125989. # define testcase(X)
  125990. #endif
  125991. /*
  125992. ** Terminator values for position-lists and column-lists.
  125993. */
  125994. #define POS_COLUMN (1) /* Column-list terminator */
  125995. #define POS_END (0) /* Position-list terminator */
  125996. /*
  125997. ** This section provides definitions to allow the
  125998. ** FTS3 extension to be compiled outside of the
  125999. ** amalgamation.
  126000. */
  126001. #ifndef SQLITE_AMALGAMATION
  126002. /*
  126003. ** Macros indicating that conditional expressions are always true or
  126004. ** false.
  126005. */
  126006. #ifdef SQLITE_COVERAGE_TEST
  126007. # define ALWAYS(x) (1)
  126008. # define NEVER(X) (0)
  126009. #elif defined(SQLITE_DEBUG)
  126010. # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
  126011. # define NEVER(x) sqlite3Fts3Never((x)!=0)
  126012. SQLITE_PRIVATE int sqlite3Fts3Always(int b);
  126013. SQLITE_PRIVATE int sqlite3Fts3Never(int b);
  126014. #else
  126015. # define ALWAYS(x) (x)
  126016. # define NEVER(x) (x)
  126017. #endif
  126018. /*
  126019. ** Internal types used by SQLite.
  126020. */
  126021. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  126022. typedef short int i16; /* 2-byte (or larger) signed integer */
  126023. typedef unsigned int u32; /* 4-byte unsigned integer */
  126024. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  126025. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  126026. /*
  126027. ** Macro used to suppress compiler warnings for unused parameters.
  126028. */
  126029. #define UNUSED_PARAMETER(x) (void)(x)
  126030. /*
  126031. ** Activate assert() only if SQLITE_TEST is enabled.
  126032. */
  126033. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  126034. # define NDEBUG 1
  126035. #endif
  126036. /*
  126037. ** The TESTONLY macro is used to enclose variable declarations or
  126038. ** other bits of code that are needed to support the arguments
  126039. ** within testcase() and assert() macros.
  126040. */
  126041. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  126042. # define TESTONLY(X) X
  126043. #else
  126044. # define TESTONLY(X)
  126045. #endif
  126046. #endif /* SQLITE_AMALGAMATION */
  126047. #ifdef SQLITE_DEBUG
  126048. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  126049. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  126050. #else
  126051. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  126052. #endif
  126053. typedef struct Fts3Table Fts3Table;
  126054. typedef struct Fts3Cursor Fts3Cursor;
  126055. typedef struct Fts3Expr Fts3Expr;
  126056. typedef struct Fts3Phrase Fts3Phrase;
  126057. typedef struct Fts3PhraseToken Fts3PhraseToken;
  126058. typedef struct Fts3Doclist Fts3Doclist;
  126059. typedef struct Fts3SegFilter Fts3SegFilter;
  126060. typedef struct Fts3DeferredToken Fts3DeferredToken;
  126061. typedef struct Fts3SegReader Fts3SegReader;
  126062. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  126063. typedef struct MatchinfoBuffer MatchinfoBuffer;
  126064. /*
  126065. ** A connection to a fulltext index is an instance of the following
  126066. ** structure. The xCreate and xConnect methods create an instance
  126067. ** of this structure and xDestroy and xDisconnect free that instance.
  126068. ** All other methods receive a pointer to the structure as one of their
  126069. ** arguments.
  126070. */
  126071. struct Fts3Table {
  126072. sqlite3_vtab base; /* Base class used by SQLite core */
  126073. sqlite3 *db; /* The database connection */
  126074. const char *zDb; /* logical database name */
  126075. const char *zName; /* virtual table name */
  126076. int nColumn; /* number of named columns in virtual table */
  126077. char **azColumn; /* column names. malloced */
  126078. u8 *abNotindexed; /* True for 'notindexed' columns */
  126079. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  126080. char *zContentTbl; /* content=xxx option, or NULL */
  126081. char *zLanguageid; /* languageid=xxx option, or NULL */
  126082. int nAutoincrmerge; /* Value configured by 'automerge' */
  126083. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  126084. /* Precompiled statements used by the implementation. Each of these
  126085. ** statements is run and reset within a single virtual table API call.
  126086. */
  126087. sqlite3_stmt *aStmt[40];
  126088. char *zReadExprlist;
  126089. char *zWriteExprlist;
  126090. int nNodeSize; /* Soft limit for node size */
  126091. u8 bFts4; /* True for FTS4, false for FTS3 */
  126092. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  126093. u8 bHasDocsize; /* True if %_docsize table exists */
  126094. u8 bDescIdx; /* True if doclists are in reverse order */
  126095. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  126096. int nPgsz; /* Page size for host database */
  126097. char *zSegmentsTbl; /* Name of %_segments table */
  126098. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  126099. /*
  126100. ** The following array of hash tables is used to buffer pending index
  126101. ** updates during transactions. All pending updates buffered at any one
  126102. ** time must share a common language-id (see the FTS4 langid= feature).
  126103. ** The current language id is stored in variable iPrevLangid.
  126104. **
  126105. ** A single FTS4 table may have multiple full-text indexes. For each index
  126106. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  126107. ** terms that appear in the document set. Each subsequent index in aIndex[]
  126108. ** is an index of prefixes of a specific length.
  126109. **
  126110. ** Variable nPendingData contains an estimate the memory consumed by the
  126111. ** pending data structures, including hash table overhead, but not including
  126112. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  126113. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  126114. ** recently inserted record.
  126115. */
  126116. int nIndex; /* Size of aIndex[] */
  126117. struct Fts3Index {
  126118. int nPrefix; /* Prefix length (0 for main terms index) */
  126119. Fts3Hash hPending; /* Pending terms table for this index */
  126120. } *aIndex;
  126121. int nMaxPendingData; /* Max pending data before flush to disk */
  126122. int nPendingData; /* Current bytes of pending data */
  126123. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  126124. int iPrevLangid; /* Langid of recently inserted document */
  126125. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  126126. /* State variables used for validating that the transaction control
  126127. ** methods of the virtual table are called at appropriate times. These
  126128. ** values do not contribute to FTS functionality; they are used for
  126129. ** verifying the operation of the SQLite core.
  126130. */
  126131. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  126132. int mxSavepoint; /* Largest valid xSavepoint integer */
  126133. #endif
  126134. #ifdef SQLITE_TEST
  126135. /* True to disable the incremental doclist optimization. This is controled
  126136. ** by special insert command 'test-no-incr-doclist'. */
  126137. int bNoIncrDoclist;
  126138. #endif
  126139. };
  126140. /*
  126141. ** When the core wants to read from the virtual table, it creates a
  126142. ** virtual table cursor (an instance of the following structure) using
  126143. ** the xOpen method. Cursors are destroyed using the xClose method.
  126144. */
  126145. struct Fts3Cursor {
  126146. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  126147. i16 eSearch; /* Search strategy (see below) */
  126148. u8 isEof; /* True if at End Of Results */
  126149. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  126150. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  126151. Fts3Expr *pExpr; /* Parsed MATCH query string */
  126152. int iLangid; /* Language being queried for */
  126153. int nPhrase; /* Number of matchable phrases in query */
  126154. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  126155. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  126156. char *pNextId; /* Pointer into the body of aDoclist */
  126157. char *aDoclist; /* List of docids for full-text queries */
  126158. int nDoclist; /* Size of buffer at aDoclist */
  126159. u8 bDesc; /* True to sort in descending order */
  126160. int eEvalmode; /* An FTS3_EVAL_XX constant */
  126161. int nRowAvg; /* Average size of database rows, in pages */
  126162. sqlite3_int64 nDoc; /* Documents in table */
  126163. i64 iMinDocid; /* Minimum docid to return */
  126164. i64 iMaxDocid; /* Maximum docid to return */
  126165. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  126166. MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
  126167. };
  126168. #define FTS3_EVAL_FILTER 0
  126169. #define FTS3_EVAL_NEXT 1
  126170. #define FTS3_EVAL_MATCHINFO 2
  126171. /*
  126172. ** The Fts3Cursor.eSearch member is always set to one of the following.
  126173. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  126174. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  126175. ** of the column to be searched. For example, in
  126176. **
  126177. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  126178. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  126179. **
  126180. ** Because the LHS of the MATCH operator is 2nd column "b",
  126181. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  126182. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  126183. ** indicating that all columns should be searched,
  126184. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  126185. */
  126186. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  126187. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  126188. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  126189. /*
  126190. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  126191. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  126192. ** above. The upper 16-bits contain a combination of the following
  126193. ** bits, used to describe extra constraints on full-text searches.
  126194. */
  126195. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  126196. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  126197. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  126198. struct Fts3Doclist {
  126199. char *aAll; /* Array containing doclist (or NULL) */
  126200. int nAll; /* Size of a[] in bytes */
  126201. char *pNextDocid; /* Pointer to next docid */
  126202. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  126203. int bFreeList; /* True if pList should be sqlite3_free()d */
  126204. char *pList; /* Pointer to position list following iDocid */
  126205. int nList; /* Length of position list */
  126206. };
  126207. /*
  126208. ** A "phrase" is a sequence of one or more tokens that must match in
  126209. ** sequence. A single token is the base case and the most common case.
  126210. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  126211. ** nToken will be the number of tokens in the string.
  126212. */
  126213. struct Fts3PhraseToken {
  126214. char *z; /* Text of the token */
  126215. int n; /* Number of bytes in buffer z */
  126216. int isPrefix; /* True if token ends with a "*" character */
  126217. int bFirst; /* True if token must appear at position 0 */
  126218. /* Variables above this point are populated when the expression is
  126219. ** parsed (by code in fts3_expr.c). Below this point the variables are
  126220. ** used when evaluating the expression. */
  126221. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  126222. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  126223. };
  126224. struct Fts3Phrase {
  126225. /* Cache of doclist for this phrase. */
  126226. Fts3Doclist doclist;
  126227. int bIncr; /* True if doclist is loaded incrementally */
  126228. int iDoclistToken;
  126229. /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
  126230. ** OR condition. */
  126231. char *pOrPoslist;
  126232. i64 iOrDocid;
  126233. /* Variables below this point are populated by fts3_expr.c when parsing
  126234. ** a MATCH expression. Everything above is part of the evaluation phase.
  126235. */
  126236. int nToken; /* Number of tokens in the phrase */
  126237. int iColumn; /* Index of column this phrase must match */
  126238. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  126239. };
  126240. /*
  126241. ** A tree of these objects forms the RHS of a MATCH operator.
  126242. **
  126243. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  126244. ** points to a malloced buffer, size nDoclist bytes, containing the results
  126245. ** of this phrase query in FTS3 doclist format. As usual, the initial
  126246. ** "Length" field found in doclists stored on disk is omitted from this
  126247. ** buffer.
  126248. **
  126249. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  126250. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  126251. ** where nCol is the number of columns in the queried FTS table. The array
  126252. ** is populated as follows:
  126253. **
  126254. ** aMI[iCol*3 + 0] = Undefined
  126255. ** aMI[iCol*3 + 1] = Number of occurrences
  126256. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  126257. **
  126258. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  126259. ** when the expression node is.
  126260. */
  126261. struct Fts3Expr {
  126262. int eType; /* One of the FTSQUERY_XXX values defined below */
  126263. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  126264. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  126265. Fts3Expr *pLeft; /* Left operand */
  126266. Fts3Expr *pRight; /* Right operand */
  126267. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  126268. /* The following are used by the fts3_eval.c module. */
  126269. sqlite3_int64 iDocid; /* Current docid */
  126270. u8 bEof; /* True this expression is at EOF already */
  126271. u8 bStart; /* True if iDocid is valid */
  126272. u8 bDeferred; /* True if this expression is entirely deferred */
  126273. /* The following are used by the fts3_snippet.c module. */
  126274. int iPhrase; /* Index of this phrase in matchinfo() results */
  126275. u32 *aMI; /* See above */
  126276. };
  126277. /*
  126278. ** Candidate values for Fts3Query.eType. Note that the order of the first
  126279. ** four values is in order of precedence when parsing expressions. For
  126280. ** example, the following:
  126281. **
  126282. ** "a OR b AND c NOT d NEAR e"
  126283. **
  126284. ** is equivalent to:
  126285. **
  126286. ** "a OR (b AND (c NOT (d NEAR e)))"
  126287. */
  126288. #define FTSQUERY_NEAR 1
  126289. #define FTSQUERY_NOT 2
  126290. #define FTSQUERY_AND 3
  126291. #define FTSQUERY_OR 4
  126292. #define FTSQUERY_PHRASE 5
  126293. /* fts3_write.c */
  126294. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  126295. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  126296. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  126297. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  126298. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  126299. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  126300. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  126301. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  126302. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  126303. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  126304. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  126305. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  126306. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  126307. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  126308. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  126309. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  126310. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  126311. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  126312. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  126313. #else
  126314. # define sqlite3Fts3FreeDeferredTokens(x)
  126315. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  126316. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  126317. # define sqlite3Fts3FreeDeferredDoclists(x)
  126318. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  126319. #endif
  126320. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  126321. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  126322. /* Special values interpreted by sqlite3SegReaderCursor() */
  126323. #define FTS3_SEGCURSOR_PENDING -1
  126324. #define FTS3_SEGCURSOR_ALL -2
  126325. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  126326. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  126327. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  126328. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  126329. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  126330. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  126331. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  126332. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  126333. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  126334. #define FTS3_SEGMENT_PREFIX 0x00000008
  126335. #define FTS3_SEGMENT_SCAN 0x00000010
  126336. #define FTS3_SEGMENT_FIRST 0x00000020
  126337. /* Type passed as 4th argument to SegmentReaderIterate() */
  126338. struct Fts3SegFilter {
  126339. const char *zTerm;
  126340. int nTerm;
  126341. int iCol;
  126342. int flags;
  126343. };
  126344. struct Fts3MultiSegReader {
  126345. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  126346. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  126347. int nSegment; /* Size of apSegment array */
  126348. int nAdvance; /* How many seg-readers to advance */
  126349. Fts3SegFilter *pFilter; /* Pointer to filter object */
  126350. char *aBuffer; /* Buffer to merge doclists in */
  126351. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  126352. int iColFilter; /* If >=0, filter for this column */
  126353. int bRestart;
  126354. /* Used by fts3.c only. */
  126355. int nCost; /* Cost of running iterator */
  126356. int bLookup; /* True if a lookup of a single entry. */
  126357. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  126358. char *zTerm; /* Pointer to term buffer */
  126359. int nTerm; /* Size of zTerm in bytes */
  126360. char *aDoclist; /* Pointer to doclist buffer */
  126361. int nDoclist; /* Size of aDoclist[] in bytes */
  126362. };
  126363. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  126364. #define fts3GetVarint32(p, piVal) ( \
  126365. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  126366. )
  126367. /* fts3.c */
  126368. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
  126369. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  126370. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  126371. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  126372. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  126373. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  126374. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  126375. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  126376. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  126377. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  126378. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
  126379. /* fts3_tokenizer.c */
  126380. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  126381. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  126382. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  126383. sqlite3_tokenizer **, char **
  126384. );
  126385. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  126386. /* fts3_snippet.c */
  126387. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  126388. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  126389. const char *, const char *, int, int
  126390. );
  126391. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  126392. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
  126393. /* fts3_expr.c */
  126394. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  126395. char **, int, int, int, const char *, int, Fts3Expr **, char **
  126396. );
  126397. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  126398. #ifdef SQLITE_TEST
  126399. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  126400. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  126401. #endif
  126402. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  126403. sqlite3_tokenizer_cursor **
  126404. );
  126405. /* fts3_aux.c */
  126406. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  126407. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  126408. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  126409. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  126410. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  126411. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  126412. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  126413. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  126414. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  126415. /* fts3_tokenize_vtab.c */
  126416. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  126417. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  126418. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  126419. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  126420. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  126421. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  126422. #endif
  126423. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  126424. #endif /* _FTSINT_H */
  126425. /************** End of fts3Int.h *********************************************/
  126426. /************** Continuing where we left off in fts3.c ***********************/
  126427. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  126428. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  126429. # define SQLITE_CORE 1
  126430. #endif
  126431. /* #include <assert.h> */
  126432. /* #include <stdlib.h> */
  126433. /* #include <stddef.h> */
  126434. /* #include <stdio.h> */
  126435. /* #include <string.h> */
  126436. /* #include <stdarg.h> */
  126437. /* #include "fts3.h" */
  126438. #ifndef SQLITE_CORE
  126439. /* # include "sqlite3ext.h" */
  126440. SQLITE_EXTENSION_INIT1
  126441. #endif
  126442. static int fts3EvalNext(Fts3Cursor *pCsr);
  126443. static int fts3EvalStart(Fts3Cursor *pCsr);
  126444. static int fts3TermSegReaderCursor(
  126445. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  126446. #ifndef SQLITE_AMALGAMATION
  126447. # if defined(SQLITE_DEBUG)
  126448. SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
  126449. SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
  126450. # endif
  126451. #endif
  126452. /*
  126453. ** Write a 64-bit variable-length integer to memory starting at p[0].
  126454. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  126455. ** The number of bytes written is returned.
  126456. */
  126457. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  126458. unsigned char *q = (unsigned char *) p;
  126459. sqlite_uint64 vu = v;
  126460. do{
  126461. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  126462. vu >>= 7;
  126463. }while( vu!=0 );
  126464. q[-1] &= 0x7f; /* turn off high bit in final byte */
  126465. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  126466. return (int) (q - (unsigned char *)p);
  126467. }
  126468. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  126469. v = (v & mask1) | ( (*ptr++) << shift ); \
  126470. if( (v & mask2)==0 ){ var = v; return ret; }
  126471. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  126472. v = (*ptr++); \
  126473. if( (v & mask2)==0 ){ var = v; return ret; }
  126474. /*
  126475. ** Read a 64-bit variable-length integer from memory starting at p[0].
  126476. ** Return the number of bytes read, or 0 on error.
  126477. ** The value is stored in *v.
  126478. */
  126479. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  126480. const char *pStart = p;
  126481. u32 a;
  126482. u64 b;
  126483. int shift;
  126484. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  126485. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  126486. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  126487. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  126488. b = (a & 0x0FFFFFFF );
  126489. for(shift=28; shift<=63; shift+=7){
  126490. u64 c = *p++;
  126491. b += (c&0x7F) << shift;
  126492. if( (c & 0x80)==0 ) break;
  126493. }
  126494. *v = b;
  126495. return (int)(p - pStart);
  126496. }
  126497. /*
  126498. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  126499. ** 32-bit integer before it is returned.
  126500. */
  126501. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  126502. u32 a;
  126503. #ifndef fts3GetVarint32
  126504. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  126505. #else
  126506. a = (*p++);
  126507. assert( a & 0x80 );
  126508. #endif
  126509. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  126510. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  126511. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  126512. a = (a & 0x0FFFFFFF );
  126513. *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
  126514. return 5;
  126515. }
  126516. /*
  126517. ** Return the number of bytes required to encode v as a varint
  126518. */
  126519. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  126520. int i = 0;
  126521. do{
  126522. i++;
  126523. v >>= 7;
  126524. }while( v!=0 );
  126525. return i;
  126526. }
  126527. /*
  126528. ** Convert an SQL-style quoted string into a normal string by removing
  126529. ** the quote characters. The conversion is done in-place. If the
  126530. ** input does not begin with a quote character, then this routine
  126531. ** is a no-op.
  126532. **
  126533. ** Examples:
  126534. **
  126535. ** "abc" becomes abc
  126536. ** 'xyz' becomes xyz
  126537. ** [pqr] becomes pqr
  126538. ** `mno` becomes mno
  126539. **
  126540. */
  126541. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  126542. char quote; /* Quote character (if any ) */
  126543. quote = z[0];
  126544. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  126545. int iIn = 1; /* Index of next byte to read from input */
  126546. int iOut = 0; /* Index of next byte to write to output */
  126547. /* If the first byte was a '[', then the close-quote character is a ']' */
  126548. if( quote=='[' ) quote = ']';
  126549. while( z[iIn] ){
  126550. if( z[iIn]==quote ){
  126551. if( z[iIn+1]!=quote ) break;
  126552. z[iOut++] = quote;
  126553. iIn += 2;
  126554. }else{
  126555. z[iOut++] = z[iIn++];
  126556. }
  126557. }
  126558. z[iOut] = '\0';
  126559. }
  126560. }
  126561. /*
  126562. ** Read a single varint from the doclist at *pp and advance *pp to point
  126563. ** to the first byte past the end of the varint. Add the value of the varint
  126564. ** to *pVal.
  126565. */
  126566. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  126567. sqlite3_int64 iVal;
  126568. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  126569. *pVal += iVal;
  126570. }
  126571. /*
  126572. ** When this function is called, *pp points to the first byte following a
  126573. ** varint that is part of a doclist (or position-list, or any other list
  126574. ** of varints). This function moves *pp to point to the start of that varint,
  126575. ** and sets *pVal by the varint value.
  126576. **
  126577. ** Argument pStart points to the first byte of the doclist that the
  126578. ** varint is part of.
  126579. */
  126580. static void fts3GetReverseVarint(
  126581. char **pp,
  126582. char *pStart,
  126583. sqlite3_int64 *pVal
  126584. ){
  126585. sqlite3_int64 iVal;
  126586. char *p;
  126587. /* Pointer p now points at the first byte past the varint we are
  126588. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  126589. ** clear on character p[-1]. */
  126590. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  126591. p++;
  126592. *pp = p;
  126593. sqlite3Fts3GetVarint(p, &iVal);
  126594. *pVal = iVal;
  126595. }
  126596. /*
  126597. ** The xDisconnect() virtual table method.
  126598. */
  126599. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  126600. Fts3Table *p = (Fts3Table *)pVtab;
  126601. int i;
  126602. assert( p->nPendingData==0 );
  126603. assert( p->pSegments==0 );
  126604. /* Free any prepared statements held */
  126605. for(i=0; i<SizeofArray(p->aStmt); i++){
  126606. sqlite3_finalize(p->aStmt[i]);
  126607. }
  126608. sqlite3_free(p->zSegmentsTbl);
  126609. sqlite3_free(p->zReadExprlist);
  126610. sqlite3_free(p->zWriteExprlist);
  126611. sqlite3_free(p->zContentTbl);
  126612. sqlite3_free(p->zLanguageid);
  126613. /* Invoke the tokenizer destructor to free the tokenizer. */
  126614. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  126615. sqlite3_free(p);
  126616. return SQLITE_OK;
  126617. }
  126618. /*
  126619. ** Write an error message into *pzErr
  126620. */
  126621. SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
  126622. va_list ap;
  126623. sqlite3_free(*pzErr);
  126624. va_start(ap, zFormat);
  126625. *pzErr = sqlite3_vmprintf(zFormat, ap);
  126626. va_end(ap);
  126627. }
  126628. /*
  126629. ** Construct one or more SQL statements from the format string given
  126630. ** and then evaluate those statements. The success code is written
  126631. ** into *pRc.
  126632. **
  126633. ** If *pRc is initially non-zero then this routine is a no-op.
  126634. */
  126635. static void fts3DbExec(
  126636. int *pRc, /* Success code */
  126637. sqlite3 *db, /* Database in which to run SQL */
  126638. const char *zFormat, /* Format string for SQL */
  126639. ... /* Arguments to the format string */
  126640. ){
  126641. va_list ap;
  126642. char *zSql;
  126643. if( *pRc ) return;
  126644. va_start(ap, zFormat);
  126645. zSql = sqlite3_vmprintf(zFormat, ap);
  126646. va_end(ap);
  126647. if( zSql==0 ){
  126648. *pRc = SQLITE_NOMEM;
  126649. }else{
  126650. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  126651. sqlite3_free(zSql);
  126652. }
  126653. }
  126654. /*
  126655. ** The xDestroy() virtual table method.
  126656. */
  126657. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  126658. Fts3Table *p = (Fts3Table *)pVtab;
  126659. int rc = SQLITE_OK; /* Return code */
  126660. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  126661. sqlite3 *db = p->db; /* Database handle */
  126662. /* Drop the shadow tables */
  126663. if( p->zContentTbl==0 ){
  126664. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  126665. }
  126666. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  126667. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  126668. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  126669. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  126670. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  126671. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  126672. ** Otherwise, return an SQLite error code.
  126673. */
  126674. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  126675. }
  126676. /*
  126677. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  126678. ** passed as the first argument. This is done as part of the xConnect()
  126679. ** and xCreate() methods.
  126680. **
  126681. ** If *pRc is non-zero when this function is called, it is a no-op.
  126682. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  126683. ** before returning.
  126684. */
  126685. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  126686. if( *pRc==SQLITE_OK ){
  126687. int i; /* Iterator variable */
  126688. int rc; /* Return code */
  126689. char *zSql; /* SQL statement passed to declare_vtab() */
  126690. char *zCols; /* List of user defined columns */
  126691. const char *zLanguageid;
  126692. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  126693. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  126694. /* Create a list of user columns for the virtual table */
  126695. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  126696. for(i=1; zCols && i<p->nColumn; i++){
  126697. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  126698. }
  126699. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  126700. zSql = sqlite3_mprintf(
  126701. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  126702. zCols, p->zName, zLanguageid
  126703. );
  126704. if( !zCols || !zSql ){
  126705. rc = SQLITE_NOMEM;
  126706. }else{
  126707. rc = sqlite3_declare_vtab(p->db, zSql);
  126708. }
  126709. sqlite3_free(zSql);
  126710. sqlite3_free(zCols);
  126711. *pRc = rc;
  126712. }
  126713. }
  126714. /*
  126715. ** Create the %_stat table if it does not already exist.
  126716. */
  126717. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  126718. fts3DbExec(pRc, p->db,
  126719. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  126720. "(id INTEGER PRIMARY KEY, value BLOB);",
  126721. p->zDb, p->zName
  126722. );
  126723. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  126724. }
  126725. /*
  126726. ** Create the backing store tables (%_content, %_segments and %_segdir)
  126727. ** required by the FTS3 table passed as the only argument. This is done
  126728. ** as part of the vtab xCreate() method.
  126729. **
  126730. ** If the p->bHasDocsize boolean is true (indicating that this is an
  126731. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  126732. ** %_stat tables required by FTS4.
  126733. */
  126734. static int fts3CreateTables(Fts3Table *p){
  126735. int rc = SQLITE_OK; /* Return code */
  126736. int i; /* Iterator variable */
  126737. sqlite3 *db = p->db; /* The database connection */
  126738. if( p->zContentTbl==0 ){
  126739. const char *zLanguageid = p->zLanguageid;
  126740. char *zContentCols; /* Columns of %_content table */
  126741. /* Create a list of user columns for the content table */
  126742. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  126743. for(i=0; zContentCols && i<p->nColumn; i++){
  126744. char *z = p->azColumn[i];
  126745. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  126746. }
  126747. if( zLanguageid && zContentCols ){
  126748. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  126749. }
  126750. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  126751. /* Create the content table */
  126752. fts3DbExec(&rc, db,
  126753. "CREATE TABLE %Q.'%q_content'(%s)",
  126754. p->zDb, p->zName, zContentCols
  126755. );
  126756. sqlite3_free(zContentCols);
  126757. }
  126758. /* Create other tables */
  126759. fts3DbExec(&rc, db,
  126760. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  126761. p->zDb, p->zName
  126762. );
  126763. fts3DbExec(&rc, db,
  126764. "CREATE TABLE %Q.'%q_segdir'("
  126765. "level INTEGER,"
  126766. "idx INTEGER,"
  126767. "start_block INTEGER,"
  126768. "leaves_end_block INTEGER,"
  126769. "end_block INTEGER,"
  126770. "root BLOB,"
  126771. "PRIMARY KEY(level, idx)"
  126772. ");",
  126773. p->zDb, p->zName
  126774. );
  126775. if( p->bHasDocsize ){
  126776. fts3DbExec(&rc, db,
  126777. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  126778. p->zDb, p->zName
  126779. );
  126780. }
  126781. assert( p->bHasStat==p->bFts4 );
  126782. if( p->bHasStat ){
  126783. sqlite3Fts3CreateStatTable(&rc, p);
  126784. }
  126785. return rc;
  126786. }
  126787. /*
  126788. ** Store the current database page-size in bytes in p->nPgsz.
  126789. **
  126790. ** If *pRc is non-zero when this function is called, it is a no-op.
  126791. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  126792. ** before returning.
  126793. */
  126794. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  126795. if( *pRc==SQLITE_OK ){
  126796. int rc; /* Return code */
  126797. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  126798. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  126799. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  126800. if( !zSql ){
  126801. rc = SQLITE_NOMEM;
  126802. }else{
  126803. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  126804. if( rc==SQLITE_OK ){
  126805. sqlite3_step(pStmt);
  126806. p->nPgsz = sqlite3_column_int(pStmt, 0);
  126807. rc = sqlite3_finalize(pStmt);
  126808. }else if( rc==SQLITE_AUTH ){
  126809. p->nPgsz = 1024;
  126810. rc = SQLITE_OK;
  126811. }
  126812. }
  126813. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  126814. sqlite3_free(zSql);
  126815. *pRc = rc;
  126816. }
  126817. }
  126818. /*
  126819. ** "Special" FTS4 arguments are column specifications of the following form:
  126820. **
  126821. ** <key> = <value>
  126822. **
  126823. ** There may not be whitespace surrounding the "=" character. The <value>
  126824. ** term may be quoted, but the <key> may not.
  126825. */
  126826. static int fts3IsSpecialColumn(
  126827. const char *z,
  126828. int *pnKey,
  126829. char **pzValue
  126830. ){
  126831. char *zValue;
  126832. const char *zCsr = z;
  126833. while( *zCsr!='=' ){
  126834. if( *zCsr=='\0' ) return 0;
  126835. zCsr++;
  126836. }
  126837. *pnKey = (int)(zCsr-z);
  126838. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  126839. if( zValue ){
  126840. sqlite3Fts3Dequote(zValue);
  126841. }
  126842. *pzValue = zValue;
  126843. return 1;
  126844. }
  126845. /*
  126846. ** Append the output of a printf() style formatting to an existing string.
  126847. */
  126848. static void fts3Appendf(
  126849. int *pRc, /* IN/OUT: Error code */
  126850. char **pz, /* IN/OUT: Pointer to string buffer */
  126851. const char *zFormat, /* Printf format string to append */
  126852. ... /* Arguments for printf format string */
  126853. ){
  126854. if( *pRc==SQLITE_OK ){
  126855. va_list ap;
  126856. char *z;
  126857. va_start(ap, zFormat);
  126858. z = sqlite3_vmprintf(zFormat, ap);
  126859. va_end(ap);
  126860. if( z && *pz ){
  126861. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  126862. sqlite3_free(z);
  126863. z = z2;
  126864. }
  126865. if( z==0 ) *pRc = SQLITE_NOMEM;
  126866. sqlite3_free(*pz);
  126867. *pz = z;
  126868. }
  126869. }
  126870. /*
  126871. ** Return a copy of input string zInput enclosed in double-quotes (") and
  126872. ** with all double quote characters escaped. For example:
  126873. **
  126874. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  126875. **
  126876. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  126877. ** is the callers responsibility to call sqlite3_free() to release this
  126878. ** memory.
  126879. */
  126880. static char *fts3QuoteId(char const *zInput){
  126881. int nRet;
  126882. char *zRet;
  126883. nRet = 2 + (int)strlen(zInput)*2 + 1;
  126884. zRet = sqlite3_malloc(nRet);
  126885. if( zRet ){
  126886. int i;
  126887. char *z = zRet;
  126888. *(z++) = '"';
  126889. for(i=0; zInput[i]; i++){
  126890. if( zInput[i]=='"' ) *(z++) = '"';
  126891. *(z++) = zInput[i];
  126892. }
  126893. *(z++) = '"';
  126894. *(z++) = '\0';
  126895. }
  126896. return zRet;
  126897. }
  126898. /*
  126899. ** Return a list of comma separated SQL expressions and a FROM clause that
  126900. ** could be used in a SELECT statement such as the following:
  126901. **
  126902. ** SELECT <list of expressions> FROM %_content AS x ...
  126903. **
  126904. ** to return the docid, followed by each column of text data in order
  126905. ** from left to write. If parameter zFunc is not NULL, then instead of
  126906. ** being returned directly each column of text data is passed to an SQL
  126907. ** function named zFunc first. For example, if zFunc is "unzip" and the
  126908. ** table has the three user-defined columns "a", "b", and "c", the following
  126909. ** string is returned:
  126910. **
  126911. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  126912. **
  126913. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  126914. ** is the responsibility of the caller to eventually free it.
  126915. **
  126916. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  126917. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  126918. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  126919. ** no error occurs, *pRc is left unmodified.
  126920. */
  126921. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  126922. char *zRet = 0;
  126923. char *zFree = 0;
  126924. char *zFunction;
  126925. int i;
  126926. if( p->zContentTbl==0 ){
  126927. if( !zFunc ){
  126928. zFunction = "";
  126929. }else{
  126930. zFree = zFunction = fts3QuoteId(zFunc);
  126931. }
  126932. fts3Appendf(pRc, &zRet, "docid");
  126933. for(i=0; i<p->nColumn; i++){
  126934. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  126935. }
  126936. if( p->zLanguageid ){
  126937. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  126938. }
  126939. sqlite3_free(zFree);
  126940. }else{
  126941. fts3Appendf(pRc, &zRet, "rowid");
  126942. for(i=0; i<p->nColumn; i++){
  126943. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  126944. }
  126945. if( p->zLanguageid ){
  126946. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  126947. }
  126948. }
  126949. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  126950. p->zDb,
  126951. (p->zContentTbl ? p->zContentTbl : p->zName),
  126952. (p->zContentTbl ? "" : "_content")
  126953. );
  126954. return zRet;
  126955. }
  126956. /*
  126957. ** Return a list of N comma separated question marks, where N is the number
  126958. ** of columns in the %_content table (one for the docid plus one for each
  126959. ** user-defined text column).
  126960. **
  126961. ** If argument zFunc is not NULL, then all but the first question mark
  126962. ** is preceded by zFunc and an open bracket, and followed by a closed
  126963. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  126964. ** user-defined text columns, the following string is returned:
  126965. **
  126966. ** "?, zip(?), zip(?), zip(?)"
  126967. **
  126968. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  126969. ** is the responsibility of the caller to eventually free it.
  126970. **
  126971. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  126972. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  126973. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  126974. ** no error occurs, *pRc is left unmodified.
  126975. */
  126976. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  126977. char *zRet = 0;
  126978. char *zFree = 0;
  126979. char *zFunction;
  126980. int i;
  126981. if( !zFunc ){
  126982. zFunction = "";
  126983. }else{
  126984. zFree = zFunction = fts3QuoteId(zFunc);
  126985. }
  126986. fts3Appendf(pRc, &zRet, "?");
  126987. for(i=0; i<p->nColumn; i++){
  126988. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  126989. }
  126990. if( p->zLanguageid ){
  126991. fts3Appendf(pRc, &zRet, ", ?");
  126992. }
  126993. sqlite3_free(zFree);
  126994. return zRet;
  126995. }
  126996. /*
  126997. ** This function interprets the string at (*pp) as a non-negative integer
  126998. ** value. It reads the integer and sets *pnOut to the value read, then
  126999. ** sets *pp to point to the byte immediately following the last byte of
  127000. ** the integer value.
  127001. **
  127002. ** Only decimal digits ('0'..'9') may be part of an integer value.
  127003. **
  127004. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  127005. ** the output value undefined. Otherwise SQLITE_OK is returned.
  127006. **
  127007. ** This function is used when parsing the "prefix=" FTS4 parameter.
  127008. */
  127009. static int fts3GobbleInt(const char **pp, int *pnOut){
  127010. const int MAX_NPREFIX = 10000000;
  127011. const char *p; /* Iterator pointer */
  127012. int nInt = 0; /* Output value */
  127013. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  127014. nInt = nInt * 10 + (p[0] - '0');
  127015. if( nInt>MAX_NPREFIX ){
  127016. nInt = 0;
  127017. break;
  127018. }
  127019. }
  127020. if( p==*pp ) return SQLITE_ERROR;
  127021. *pnOut = nInt;
  127022. *pp = p;
  127023. return SQLITE_OK;
  127024. }
  127025. /*
  127026. ** This function is called to allocate an array of Fts3Index structures
  127027. ** representing the indexes maintained by the current FTS table. FTS tables
  127028. ** always maintain the main "terms" index, but may also maintain one or
  127029. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  127030. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  127031. **
  127032. ** Argument zParam is passed the value of the "prefix=" option if one was
  127033. ** specified, or NULL otherwise.
  127034. **
  127035. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  127036. ** the allocated array. *pnIndex is set to the number of elements in the
  127037. ** array. If an error does occur, an SQLite error code is returned.
  127038. **
  127039. ** Regardless of whether or not an error is returned, it is the responsibility
  127040. ** of the caller to call sqlite3_free() on the output array to free it.
  127041. */
  127042. static int fts3PrefixParameter(
  127043. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  127044. int *pnIndex, /* OUT: size of *apIndex[] array */
  127045. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  127046. ){
  127047. struct Fts3Index *aIndex; /* Allocated array */
  127048. int nIndex = 1; /* Number of entries in array */
  127049. if( zParam && zParam[0] ){
  127050. const char *p;
  127051. nIndex++;
  127052. for(p=zParam; *p; p++){
  127053. if( *p==',' ) nIndex++;
  127054. }
  127055. }
  127056. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  127057. *apIndex = aIndex;
  127058. if( !aIndex ){
  127059. return SQLITE_NOMEM;
  127060. }
  127061. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  127062. if( zParam ){
  127063. const char *p = zParam;
  127064. int i;
  127065. for(i=1; i<nIndex; i++){
  127066. int nPrefix = 0;
  127067. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  127068. assert( nPrefix>=0 );
  127069. if( nPrefix==0 ){
  127070. nIndex--;
  127071. i--;
  127072. }else{
  127073. aIndex[i].nPrefix = nPrefix;
  127074. }
  127075. p++;
  127076. }
  127077. }
  127078. *pnIndex = nIndex;
  127079. return SQLITE_OK;
  127080. }
  127081. /*
  127082. ** This function is called when initializing an FTS4 table that uses the
  127083. ** content=xxx option. It determines the number of and names of the columns
  127084. ** of the new FTS4 table.
  127085. **
  127086. ** The third argument passed to this function is the value passed to the
  127087. ** config=xxx option (i.e. "xxx"). This function queries the database for
  127088. ** a table of that name. If found, the output variables are populated
  127089. ** as follows:
  127090. **
  127091. ** *pnCol: Set to the number of columns table xxx has,
  127092. **
  127093. ** *pnStr: Set to the total amount of space required to store a copy
  127094. ** of each columns name, including the nul-terminator.
  127095. **
  127096. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  127097. ** the name of the corresponding column in table xxx. The array
  127098. ** and its contents are allocated using a single allocation. It
  127099. ** is the responsibility of the caller to free this allocation
  127100. ** by eventually passing the *pazCol value to sqlite3_free().
  127101. **
  127102. ** If the table cannot be found, an error code is returned and the output
  127103. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  127104. ** returned (and the output variables are undefined).
  127105. */
  127106. static int fts3ContentColumns(
  127107. sqlite3 *db, /* Database handle */
  127108. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  127109. const char *zTbl, /* Name of content table */
  127110. const char ***pazCol, /* OUT: Malloc'd array of column names */
  127111. int *pnCol, /* OUT: Size of array *pazCol */
  127112. int *pnStr, /* OUT: Bytes of string content */
  127113. char **pzErr /* OUT: error message */
  127114. ){
  127115. int rc = SQLITE_OK; /* Return code */
  127116. char *zSql; /* "SELECT *" statement on zTbl */
  127117. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  127118. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  127119. if( !zSql ){
  127120. rc = SQLITE_NOMEM;
  127121. }else{
  127122. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  127123. if( rc!=SQLITE_OK ){
  127124. sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
  127125. }
  127126. }
  127127. sqlite3_free(zSql);
  127128. if( rc==SQLITE_OK ){
  127129. const char **azCol; /* Output array */
  127130. int nStr = 0; /* Size of all column names (incl. 0x00) */
  127131. int nCol; /* Number of table columns */
  127132. int i; /* Used to iterate through columns */
  127133. /* Loop through the returned columns. Set nStr to the number of bytes of
  127134. ** space required to store a copy of each column name, including the
  127135. ** nul-terminator byte. */
  127136. nCol = sqlite3_column_count(pStmt);
  127137. for(i=0; i<nCol; i++){
  127138. const char *zCol = sqlite3_column_name(pStmt, i);
  127139. nStr += (int)strlen(zCol) + 1;
  127140. }
  127141. /* Allocate and populate the array to return. */
  127142. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  127143. if( azCol==0 ){
  127144. rc = SQLITE_NOMEM;
  127145. }else{
  127146. char *p = (char *)&azCol[nCol];
  127147. for(i=0; i<nCol; i++){
  127148. const char *zCol = sqlite3_column_name(pStmt, i);
  127149. int n = (int)strlen(zCol)+1;
  127150. memcpy(p, zCol, n);
  127151. azCol[i] = p;
  127152. p += n;
  127153. }
  127154. }
  127155. sqlite3_finalize(pStmt);
  127156. /* Set the output variables. */
  127157. *pnCol = nCol;
  127158. *pnStr = nStr;
  127159. *pazCol = azCol;
  127160. }
  127161. return rc;
  127162. }
  127163. /*
  127164. ** This function is the implementation of both the xConnect and xCreate
  127165. ** methods of the FTS3 virtual table.
  127166. **
  127167. ** The argv[] array contains the following:
  127168. **
  127169. ** argv[0] -> module name ("fts3" or "fts4")
  127170. ** argv[1] -> database name
  127171. ** argv[2] -> table name
  127172. ** argv[...] -> "column name" and other module argument fields.
  127173. */
  127174. static int fts3InitVtab(
  127175. int isCreate, /* True for xCreate, false for xConnect */
  127176. sqlite3 *db, /* The SQLite database connection */
  127177. void *pAux, /* Hash table containing tokenizers */
  127178. int argc, /* Number of elements in argv array */
  127179. const char * const *argv, /* xCreate/xConnect argument array */
  127180. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  127181. char **pzErr /* Write any error message here */
  127182. ){
  127183. Fts3Hash *pHash = (Fts3Hash *)pAux;
  127184. Fts3Table *p = 0; /* Pointer to allocated vtab */
  127185. int rc = SQLITE_OK; /* Return code */
  127186. int i; /* Iterator variable */
  127187. int nByte; /* Size of allocation used for *p */
  127188. int iCol; /* Column index */
  127189. int nString = 0; /* Bytes required to hold all column names */
  127190. int nCol = 0; /* Number of columns in the FTS table */
  127191. char *zCsr; /* Space for holding column names */
  127192. int nDb; /* Bytes required to hold database name */
  127193. int nName; /* Bytes required to hold table name */
  127194. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  127195. const char **aCol; /* Array of column names */
  127196. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  127197. int nIndex = 0; /* Size of aIndex[] array */
  127198. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  127199. /* The results of parsing supported FTS4 key=value options: */
  127200. int bNoDocsize = 0; /* True to omit %_docsize table */
  127201. int bDescIdx = 0; /* True to store descending indexes */
  127202. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  127203. char *zCompress = 0; /* compress=? parameter (or NULL) */
  127204. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  127205. char *zContent = 0; /* content=? parameter (or NULL) */
  127206. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  127207. char **azNotindexed = 0; /* The set of notindexed= columns */
  127208. int nNotindexed = 0; /* Size of azNotindexed[] array */
  127209. assert( strlen(argv[0])==4 );
  127210. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  127211. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  127212. );
  127213. nDb = (int)strlen(argv[1]) + 1;
  127214. nName = (int)strlen(argv[2]) + 1;
  127215. nByte = sizeof(const char *) * (argc-2);
  127216. aCol = (const char **)sqlite3_malloc(nByte);
  127217. if( aCol ){
  127218. memset((void*)aCol, 0, nByte);
  127219. azNotindexed = (char **)sqlite3_malloc(nByte);
  127220. }
  127221. if( azNotindexed ){
  127222. memset(azNotindexed, 0, nByte);
  127223. }
  127224. if( !aCol || !azNotindexed ){
  127225. rc = SQLITE_NOMEM;
  127226. goto fts3_init_out;
  127227. }
  127228. /* Loop through all of the arguments passed by the user to the FTS3/4
  127229. ** module (i.e. all the column names and special arguments). This loop
  127230. ** does the following:
  127231. **
  127232. ** + Figures out the number of columns the FTSX table will have, and
  127233. ** the number of bytes of space that must be allocated to store copies
  127234. ** of the column names.
  127235. **
  127236. ** + If there is a tokenizer specification included in the arguments,
  127237. ** initializes the tokenizer pTokenizer.
  127238. */
  127239. for(i=3; rc==SQLITE_OK && i<argc; i++){
  127240. char const *z = argv[i];
  127241. int nKey;
  127242. char *zVal;
  127243. /* Check if this is a tokenizer specification */
  127244. if( !pTokenizer
  127245. && strlen(z)>8
  127246. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  127247. && 0==sqlite3Fts3IsIdChar(z[8])
  127248. ){
  127249. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  127250. }
  127251. /* Check if it is an FTS4 special argument. */
  127252. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  127253. struct Fts4Option {
  127254. const char *zOpt;
  127255. int nOpt;
  127256. } aFts4Opt[] = {
  127257. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  127258. { "prefix", 6 }, /* 1 -> PREFIX */
  127259. { "compress", 8 }, /* 2 -> COMPRESS */
  127260. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  127261. { "order", 5 }, /* 4 -> ORDER */
  127262. { "content", 7 }, /* 5 -> CONTENT */
  127263. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  127264. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  127265. };
  127266. int iOpt;
  127267. if( !zVal ){
  127268. rc = SQLITE_NOMEM;
  127269. }else{
  127270. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  127271. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  127272. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  127273. break;
  127274. }
  127275. }
  127276. if( iOpt==SizeofArray(aFts4Opt) ){
  127277. sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
  127278. rc = SQLITE_ERROR;
  127279. }else{
  127280. switch( iOpt ){
  127281. case 0: /* MATCHINFO */
  127282. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  127283. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
  127284. rc = SQLITE_ERROR;
  127285. }
  127286. bNoDocsize = 1;
  127287. break;
  127288. case 1: /* PREFIX */
  127289. sqlite3_free(zPrefix);
  127290. zPrefix = zVal;
  127291. zVal = 0;
  127292. break;
  127293. case 2: /* COMPRESS */
  127294. sqlite3_free(zCompress);
  127295. zCompress = zVal;
  127296. zVal = 0;
  127297. break;
  127298. case 3: /* UNCOMPRESS */
  127299. sqlite3_free(zUncompress);
  127300. zUncompress = zVal;
  127301. zVal = 0;
  127302. break;
  127303. case 4: /* ORDER */
  127304. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  127305. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  127306. ){
  127307. sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
  127308. rc = SQLITE_ERROR;
  127309. }
  127310. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  127311. break;
  127312. case 5: /* CONTENT */
  127313. sqlite3_free(zContent);
  127314. zContent = zVal;
  127315. zVal = 0;
  127316. break;
  127317. case 6: /* LANGUAGEID */
  127318. assert( iOpt==6 );
  127319. sqlite3_free(zLanguageid);
  127320. zLanguageid = zVal;
  127321. zVal = 0;
  127322. break;
  127323. case 7: /* NOTINDEXED */
  127324. azNotindexed[nNotindexed++] = zVal;
  127325. zVal = 0;
  127326. break;
  127327. }
  127328. }
  127329. sqlite3_free(zVal);
  127330. }
  127331. }
  127332. /* Otherwise, the argument is a column name. */
  127333. else {
  127334. nString += (int)(strlen(z) + 1);
  127335. aCol[nCol++] = z;
  127336. }
  127337. }
  127338. /* If a content=xxx option was specified, the following:
  127339. **
  127340. ** 1. Ignore any compress= and uncompress= options.
  127341. **
  127342. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  127343. ** TABLE statement, use all columns from the content table.
  127344. */
  127345. if( rc==SQLITE_OK && zContent ){
  127346. sqlite3_free(zCompress);
  127347. sqlite3_free(zUncompress);
  127348. zCompress = 0;
  127349. zUncompress = 0;
  127350. if( nCol==0 ){
  127351. sqlite3_free((void*)aCol);
  127352. aCol = 0;
  127353. rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
  127354. /* If a languageid= option was specified, remove the language id
  127355. ** column from the aCol[] array. */
  127356. if( rc==SQLITE_OK && zLanguageid ){
  127357. int j;
  127358. for(j=0; j<nCol; j++){
  127359. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  127360. int k;
  127361. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  127362. nCol--;
  127363. break;
  127364. }
  127365. }
  127366. }
  127367. }
  127368. }
  127369. if( rc!=SQLITE_OK ) goto fts3_init_out;
  127370. if( nCol==0 ){
  127371. assert( nString==0 );
  127372. aCol[0] = "content";
  127373. nString = 8;
  127374. nCol = 1;
  127375. }
  127376. if( pTokenizer==0 ){
  127377. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  127378. if( rc!=SQLITE_OK ) goto fts3_init_out;
  127379. }
  127380. assert( pTokenizer );
  127381. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  127382. if( rc==SQLITE_ERROR ){
  127383. assert( zPrefix );
  127384. sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
  127385. }
  127386. if( rc!=SQLITE_OK ) goto fts3_init_out;
  127387. /* Allocate and populate the Fts3Table structure. */
  127388. nByte = sizeof(Fts3Table) + /* Fts3Table */
  127389. nCol * sizeof(char *) + /* azColumn */
  127390. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  127391. nCol * sizeof(u8) + /* abNotindexed */
  127392. nName + /* zName */
  127393. nDb + /* zDb */
  127394. nString; /* Space for azColumn strings */
  127395. p = (Fts3Table*)sqlite3_malloc(nByte);
  127396. if( p==0 ){
  127397. rc = SQLITE_NOMEM;
  127398. goto fts3_init_out;
  127399. }
  127400. memset(p, 0, nByte);
  127401. p->db = db;
  127402. p->nColumn = nCol;
  127403. p->nPendingData = 0;
  127404. p->azColumn = (char **)&p[1];
  127405. p->pTokenizer = pTokenizer;
  127406. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  127407. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  127408. p->bHasStat = isFts4;
  127409. p->bFts4 = isFts4;
  127410. p->bDescIdx = bDescIdx;
  127411. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  127412. p->zContentTbl = zContent;
  127413. p->zLanguageid = zLanguageid;
  127414. zContent = 0;
  127415. zLanguageid = 0;
  127416. TESTONLY( p->inTransaction = -1 );
  127417. TESTONLY( p->mxSavepoint = -1 );
  127418. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  127419. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  127420. p->nIndex = nIndex;
  127421. for(i=0; i<nIndex; i++){
  127422. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  127423. }
  127424. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  127425. /* Fill in the zName and zDb fields of the vtab structure. */
  127426. zCsr = (char *)&p->abNotindexed[nCol];
  127427. p->zName = zCsr;
  127428. memcpy(zCsr, argv[2], nName);
  127429. zCsr += nName;
  127430. p->zDb = zCsr;
  127431. memcpy(zCsr, argv[1], nDb);
  127432. zCsr += nDb;
  127433. /* Fill in the azColumn array */
  127434. for(iCol=0; iCol<nCol; iCol++){
  127435. char *z;
  127436. int n = 0;
  127437. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  127438. memcpy(zCsr, z, n);
  127439. zCsr[n] = '\0';
  127440. sqlite3Fts3Dequote(zCsr);
  127441. p->azColumn[iCol] = zCsr;
  127442. zCsr += n+1;
  127443. assert( zCsr <= &((char *)p)[nByte] );
  127444. }
  127445. /* Fill in the abNotindexed array */
  127446. for(iCol=0; iCol<nCol; iCol++){
  127447. int n = (int)strlen(p->azColumn[iCol]);
  127448. for(i=0; i<nNotindexed; i++){
  127449. char *zNot = azNotindexed[i];
  127450. if( zNot && n==(int)strlen(zNot)
  127451. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  127452. ){
  127453. p->abNotindexed[iCol] = 1;
  127454. sqlite3_free(zNot);
  127455. azNotindexed[i] = 0;
  127456. }
  127457. }
  127458. }
  127459. for(i=0; i<nNotindexed; i++){
  127460. if( azNotindexed[i] ){
  127461. sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
  127462. rc = SQLITE_ERROR;
  127463. }
  127464. }
  127465. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  127466. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  127467. rc = SQLITE_ERROR;
  127468. sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
  127469. }
  127470. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  127471. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  127472. if( rc!=SQLITE_OK ) goto fts3_init_out;
  127473. /* If this is an xCreate call, create the underlying tables in the
  127474. ** database. TODO: For xConnect(), it could verify that said tables exist.
  127475. */
  127476. if( isCreate ){
  127477. rc = fts3CreateTables(p);
  127478. }
  127479. /* Check to see if a legacy fts3 table has been "upgraded" by the
  127480. ** addition of a %_stat table so that it can use incremental merge.
  127481. */
  127482. if( !isFts4 && !isCreate ){
  127483. p->bHasStat = 2;
  127484. }
  127485. /* Figure out the page-size for the database. This is required in order to
  127486. ** estimate the cost of loading large doclists from the database. */
  127487. fts3DatabasePageSize(&rc, p);
  127488. p->nNodeSize = p->nPgsz-35;
  127489. /* Declare the table schema to SQLite. */
  127490. fts3DeclareVtab(&rc, p);
  127491. fts3_init_out:
  127492. sqlite3_free(zPrefix);
  127493. sqlite3_free(aIndex);
  127494. sqlite3_free(zCompress);
  127495. sqlite3_free(zUncompress);
  127496. sqlite3_free(zContent);
  127497. sqlite3_free(zLanguageid);
  127498. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  127499. sqlite3_free((void *)aCol);
  127500. sqlite3_free((void *)azNotindexed);
  127501. if( rc!=SQLITE_OK ){
  127502. if( p ){
  127503. fts3DisconnectMethod((sqlite3_vtab *)p);
  127504. }else if( pTokenizer ){
  127505. pTokenizer->pModule->xDestroy(pTokenizer);
  127506. }
  127507. }else{
  127508. assert( p->pSegments==0 );
  127509. *ppVTab = &p->base;
  127510. }
  127511. return rc;
  127512. }
  127513. /*
  127514. ** The xConnect() and xCreate() methods for the virtual table. All the
  127515. ** work is done in function fts3InitVtab().
  127516. */
  127517. static int fts3ConnectMethod(
  127518. sqlite3 *db, /* Database connection */
  127519. void *pAux, /* Pointer to tokenizer hash table */
  127520. int argc, /* Number of elements in argv array */
  127521. const char * const *argv, /* xCreate/xConnect argument array */
  127522. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  127523. char **pzErr /* OUT: sqlite3_malloc'd error message */
  127524. ){
  127525. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  127526. }
  127527. static int fts3CreateMethod(
  127528. sqlite3 *db, /* Database connection */
  127529. void *pAux, /* Pointer to tokenizer hash table */
  127530. int argc, /* Number of elements in argv array */
  127531. const char * const *argv, /* xCreate/xConnect argument array */
  127532. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  127533. char **pzErr /* OUT: sqlite3_malloc'd error message */
  127534. ){
  127535. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  127536. }
  127537. /*
  127538. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  127539. ** extension is currently being used by a version of SQLite too old to
  127540. ** support estimatedRows. In that case this function is a no-op.
  127541. */
  127542. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  127543. #if SQLITE_VERSION_NUMBER>=3008002
  127544. if( sqlite3_libversion_number()>=3008002 ){
  127545. pIdxInfo->estimatedRows = nRow;
  127546. }
  127547. #endif
  127548. }
  127549. /*
  127550. ** Implementation of the xBestIndex method for FTS3 tables. There
  127551. ** are three possible strategies, in order of preference:
  127552. **
  127553. ** 1. Direct lookup by rowid or docid.
  127554. ** 2. Full-text search using a MATCH operator on a non-docid column.
  127555. ** 3. Linear scan of %_content table.
  127556. */
  127557. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  127558. Fts3Table *p = (Fts3Table *)pVTab;
  127559. int i; /* Iterator variable */
  127560. int iCons = -1; /* Index of constraint to use */
  127561. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  127562. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  127563. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  127564. int iIdx;
  127565. /* By default use a full table scan. This is an expensive option,
  127566. ** so search through the constraints to see if a more efficient
  127567. ** strategy is possible.
  127568. */
  127569. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  127570. pInfo->estimatedCost = 5000000;
  127571. for(i=0; i<pInfo->nConstraint; i++){
  127572. int bDocid; /* True if this constraint is on docid */
  127573. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  127574. if( pCons->usable==0 ){
  127575. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  127576. /* There exists an unusable MATCH constraint. This means that if
  127577. ** the planner does elect to use the results of this call as part
  127578. ** of the overall query plan the user will see an "unable to use
  127579. ** function MATCH in the requested context" error. To discourage
  127580. ** this, return a very high cost here. */
  127581. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  127582. pInfo->estimatedCost = 1e50;
  127583. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  127584. return SQLITE_OK;
  127585. }
  127586. continue;
  127587. }
  127588. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  127589. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  127590. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  127591. pInfo->idxNum = FTS3_DOCID_SEARCH;
  127592. pInfo->estimatedCost = 1.0;
  127593. iCons = i;
  127594. }
  127595. /* A MATCH constraint. Use a full-text search.
  127596. **
  127597. ** If there is more than one MATCH constraint available, use the first
  127598. ** one encountered. If there is both a MATCH constraint and a direct
  127599. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  127600. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  127601. ** it would lead to an "unable to use function MATCH in the requested
  127602. ** context" error.
  127603. */
  127604. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  127605. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  127606. ){
  127607. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  127608. pInfo->estimatedCost = 2.0;
  127609. iCons = i;
  127610. }
  127611. /* Equality constraint on the langid column */
  127612. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  127613. && pCons->iColumn==p->nColumn + 2
  127614. ){
  127615. iLangidCons = i;
  127616. }
  127617. if( bDocid ){
  127618. switch( pCons->op ){
  127619. case SQLITE_INDEX_CONSTRAINT_GE:
  127620. case SQLITE_INDEX_CONSTRAINT_GT:
  127621. iDocidGe = i;
  127622. break;
  127623. case SQLITE_INDEX_CONSTRAINT_LE:
  127624. case SQLITE_INDEX_CONSTRAINT_LT:
  127625. iDocidLe = i;
  127626. break;
  127627. }
  127628. }
  127629. }
  127630. iIdx = 1;
  127631. if( iCons>=0 ){
  127632. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  127633. pInfo->aConstraintUsage[iCons].omit = 1;
  127634. }
  127635. if( iLangidCons>=0 ){
  127636. pInfo->idxNum |= FTS3_HAVE_LANGID;
  127637. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  127638. }
  127639. if( iDocidGe>=0 ){
  127640. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  127641. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  127642. }
  127643. if( iDocidLe>=0 ){
  127644. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  127645. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  127646. }
  127647. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  127648. ** docid) order. Both ascending and descending are possible.
  127649. */
  127650. if( pInfo->nOrderBy==1 ){
  127651. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  127652. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  127653. if( pOrder->desc ){
  127654. pInfo->idxStr = "DESC";
  127655. }else{
  127656. pInfo->idxStr = "ASC";
  127657. }
  127658. pInfo->orderByConsumed = 1;
  127659. }
  127660. }
  127661. assert( p->pSegments==0 );
  127662. return SQLITE_OK;
  127663. }
  127664. /*
  127665. ** Implementation of xOpen method.
  127666. */
  127667. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  127668. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  127669. UNUSED_PARAMETER(pVTab);
  127670. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  127671. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  127672. ** if the allocation fails, return SQLITE_NOMEM.
  127673. */
  127674. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  127675. if( !pCsr ){
  127676. return SQLITE_NOMEM;
  127677. }
  127678. memset(pCsr, 0, sizeof(Fts3Cursor));
  127679. return SQLITE_OK;
  127680. }
  127681. /*
  127682. ** Close the cursor. For additional information see the documentation
  127683. ** on the xClose method of the virtual table interface.
  127684. */
  127685. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  127686. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  127687. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  127688. sqlite3_finalize(pCsr->pStmt);
  127689. sqlite3Fts3ExprFree(pCsr->pExpr);
  127690. sqlite3Fts3FreeDeferredTokens(pCsr);
  127691. sqlite3_free(pCsr->aDoclist);
  127692. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  127693. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  127694. sqlite3_free(pCsr);
  127695. return SQLITE_OK;
  127696. }
  127697. /*
  127698. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  127699. ** compose and prepare an SQL statement of the form:
  127700. **
  127701. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  127702. **
  127703. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  127704. ** it. If an error occurs, return an SQLite error code.
  127705. **
  127706. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  127707. */
  127708. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  127709. int rc = SQLITE_OK;
  127710. if( pCsr->pStmt==0 ){
  127711. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  127712. char *zSql;
  127713. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  127714. if( !zSql ) return SQLITE_NOMEM;
  127715. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  127716. sqlite3_free(zSql);
  127717. }
  127718. *ppStmt = pCsr->pStmt;
  127719. return rc;
  127720. }
  127721. /*
  127722. ** Position the pCsr->pStmt statement so that it is on the row
  127723. ** of the %_content table that contains the last match. Return
  127724. ** SQLITE_OK on success.
  127725. */
  127726. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  127727. int rc = SQLITE_OK;
  127728. if( pCsr->isRequireSeek ){
  127729. sqlite3_stmt *pStmt = 0;
  127730. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  127731. if( rc==SQLITE_OK ){
  127732. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  127733. pCsr->isRequireSeek = 0;
  127734. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  127735. return SQLITE_OK;
  127736. }else{
  127737. rc = sqlite3_reset(pCsr->pStmt);
  127738. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  127739. /* If no row was found and no error has occurred, then the %_content
  127740. ** table is missing a row that is present in the full-text index.
  127741. ** The data structures are corrupt. */
  127742. rc = FTS_CORRUPT_VTAB;
  127743. pCsr->isEof = 1;
  127744. }
  127745. }
  127746. }
  127747. }
  127748. if( rc!=SQLITE_OK && pContext ){
  127749. sqlite3_result_error_code(pContext, rc);
  127750. }
  127751. return rc;
  127752. }
  127753. /*
  127754. ** This function is used to process a single interior node when searching
  127755. ** a b-tree for a term or term prefix. The node data is passed to this
  127756. ** function via the zNode/nNode parameters. The term to search for is
  127757. ** passed in zTerm/nTerm.
  127758. **
  127759. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  127760. ** of the child node that heads the sub-tree that may contain the term.
  127761. **
  127762. ** If piLast is not NULL, then *piLast is set to the right-most child node
  127763. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  127764. ** a prefix.
  127765. **
  127766. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  127767. */
  127768. static int fts3ScanInteriorNode(
  127769. const char *zTerm, /* Term to select leaves for */
  127770. int nTerm, /* Size of term zTerm in bytes */
  127771. const char *zNode, /* Buffer containing segment interior node */
  127772. int nNode, /* Size of buffer at zNode */
  127773. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  127774. sqlite3_int64 *piLast /* OUT: Selected child node */
  127775. ){
  127776. int rc = SQLITE_OK; /* Return code */
  127777. const char *zCsr = zNode; /* Cursor to iterate through node */
  127778. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  127779. char *zBuffer = 0; /* Buffer to load terms into */
  127780. int nAlloc = 0; /* Size of allocated buffer */
  127781. int isFirstTerm = 1; /* True when processing first term on page */
  127782. sqlite3_int64 iChild; /* Block id of child node to descend to */
  127783. /* Skip over the 'height' varint that occurs at the start of every
  127784. ** interior node. Then load the blockid of the left-child of the b-tree
  127785. ** node into variable iChild.
  127786. **
  127787. ** Even if the data structure on disk is corrupted, this (reading two
  127788. ** varints from the buffer) does not risk an overread. If zNode is a
  127789. ** root node, then the buffer comes from a SELECT statement. SQLite does
  127790. ** not make this guarantee explicitly, but in practice there are always
  127791. ** either more than 20 bytes of allocated space following the nNode bytes of
  127792. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  127793. ** table, then there are always 20 bytes of zeroed padding following the
  127794. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  127795. */
  127796. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  127797. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  127798. if( zCsr>zEnd ){
  127799. return FTS_CORRUPT_VTAB;
  127800. }
  127801. while( zCsr<zEnd && (piFirst || piLast) ){
  127802. int cmp; /* memcmp() result */
  127803. int nSuffix; /* Size of term suffix */
  127804. int nPrefix = 0; /* Size of term prefix */
  127805. int nBuffer; /* Total term size */
  127806. /* Load the next term on the node into zBuffer. Use realloc() to expand
  127807. ** the size of zBuffer if required. */
  127808. if( !isFirstTerm ){
  127809. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  127810. }
  127811. isFirstTerm = 0;
  127812. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  127813. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  127814. rc = FTS_CORRUPT_VTAB;
  127815. goto finish_scan;
  127816. }
  127817. if( nPrefix+nSuffix>nAlloc ){
  127818. char *zNew;
  127819. nAlloc = (nPrefix+nSuffix) * 2;
  127820. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  127821. if( !zNew ){
  127822. rc = SQLITE_NOMEM;
  127823. goto finish_scan;
  127824. }
  127825. zBuffer = zNew;
  127826. }
  127827. assert( zBuffer );
  127828. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  127829. nBuffer = nPrefix + nSuffix;
  127830. zCsr += nSuffix;
  127831. /* Compare the term we are searching for with the term just loaded from
  127832. ** the interior node. If the specified term is greater than or equal
  127833. ** to the term from the interior node, then all terms on the sub-tree
  127834. ** headed by node iChild are smaller than zTerm. No need to search
  127835. ** iChild.
  127836. **
  127837. ** If the interior node term is larger than the specified term, then
  127838. ** the tree headed by iChild may contain the specified term.
  127839. */
  127840. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  127841. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  127842. *piFirst = iChild;
  127843. piFirst = 0;
  127844. }
  127845. if( piLast && cmp<0 ){
  127846. *piLast = iChild;
  127847. piLast = 0;
  127848. }
  127849. iChild++;
  127850. };
  127851. if( piFirst ) *piFirst = iChild;
  127852. if( piLast ) *piLast = iChild;
  127853. finish_scan:
  127854. sqlite3_free(zBuffer);
  127855. return rc;
  127856. }
  127857. /*
  127858. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  127859. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  127860. ** contains a term. This function searches the sub-tree headed by the zNode
  127861. ** node for the range of leaf nodes that may contain the specified term
  127862. ** or terms for which the specified term is a prefix.
  127863. **
  127864. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  127865. ** left-most leaf node in the tree that may contain the specified term.
  127866. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  127867. ** right-most leaf node that may contain a term for which the specified
  127868. ** term is a prefix.
  127869. **
  127870. ** It is possible that the range of returned leaf nodes does not contain
  127871. ** the specified term or any terms for which it is a prefix. However, if the
  127872. ** segment does contain any such terms, they are stored within the identified
  127873. ** range. Because this function only inspects interior segment nodes (and
  127874. ** never loads leaf nodes into memory), it is not possible to be sure.
  127875. **
  127876. ** If an error occurs, an error code other than SQLITE_OK is returned.
  127877. */
  127878. static int fts3SelectLeaf(
  127879. Fts3Table *p, /* Virtual table handle */
  127880. const char *zTerm, /* Term to select leaves for */
  127881. int nTerm, /* Size of term zTerm in bytes */
  127882. const char *zNode, /* Buffer containing segment interior node */
  127883. int nNode, /* Size of buffer at zNode */
  127884. sqlite3_int64 *piLeaf, /* Selected leaf node */
  127885. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  127886. ){
  127887. int rc = SQLITE_OK; /* Return code */
  127888. int iHeight; /* Height of this node in tree */
  127889. assert( piLeaf || piLeaf2 );
  127890. fts3GetVarint32(zNode, &iHeight);
  127891. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  127892. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  127893. if( rc==SQLITE_OK && iHeight>1 ){
  127894. char *zBlob = 0; /* Blob read from %_segments table */
  127895. int nBlob = 0; /* Size of zBlob in bytes */
  127896. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  127897. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  127898. if( rc==SQLITE_OK ){
  127899. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  127900. }
  127901. sqlite3_free(zBlob);
  127902. piLeaf = 0;
  127903. zBlob = 0;
  127904. }
  127905. if( rc==SQLITE_OK ){
  127906. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  127907. }
  127908. if( rc==SQLITE_OK ){
  127909. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  127910. }
  127911. sqlite3_free(zBlob);
  127912. }
  127913. return rc;
  127914. }
  127915. /*
  127916. ** This function is used to create delta-encoded serialized lists of FTS3
  127917. ** varints. Each call to this function appends a single varint to a list.
  127918. */
  127919. static void fts3PutDeltaVarint(
  127920. char **pp, /* IN/OUT: Output pointer */
  127921. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  127922. sqlite3_int64 iVal /* Write this value to the list */
  127923. ){
  127924. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  127925. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  127926. *piPrev = iVal;
  127927. }
  127928. /*
  127929. ** When this function is called, *ppPoslist is assumed to point to the
  127930. ** start of a position-list. After it returns, *ppPoslist points to the
  127931. ** first byte after the position-list.
  127932. **
  127933. ** A position list is list of positions (delta encoded) and columns for
  127934. ** a single document record of a doclist. So, in other words, this
  127935. ** routine advances *ppPoslist so that it points to the next docid in
  127936. ** the doclist, or to the first byte past the end of the doclist.
  127937. **
  127938. ** If pp is not NULL, then the contents of the position list are copied
  127939. ** to *pp. *pp is set to point to the first byte past the last byte copied
  127940. ** before this function returns.
  127941. */
  127942. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  127943. char *pEnd = *ppPoslist;
  127944. char c = 0;
  127945. /* The end of a position list is marked by a zero encoded as an FTS3
  127946. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  127947. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  127948. ** of some other, multi-byte, value.
  127949. **
  127950. ** The following while-loop moves pEnd to point to the first byte that is not
  127951. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  127952. ** pEnd once more so that it points to the byte immediately following the
  127953. ** last byte in the position-list.
  127954. */
  127955. while( *pEnd | c ){
  127956. c = *pEnd++ & 0x80;
  127957. testcase( c!=0 && (*pEnd)==0 );
  127958. }
  127959. pEnd++; /* Advance past the POS_END terminator byte */
  127960. if( pp ){
  127961. int n = (int)(pEnd - *ppPoslist);
  127962. char *p = *pp;
  127963. memcpy(p, *ppPoslist, n);
  127964. p += n;
  127965. *pp = p;
  127966. }
  127967. *ppPoslist = pEnd;
  127968. }
  127969. /*
  127970. ** When this function is called, *ppPoslist is assumed to point to the
  127971. ** start of a column-list. After it returns, *ppPoslist points to the
  127972. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  127973. **
  127974. ** A column-list is list of delta-encoded positions for a single column
  127975. ** within a single document within a doclist.
  127976. **
  127977. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  127978. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  127979. ** the POS_COLUMN or POS_END that terminates the column-list.
  127980. **
  127981. ** If pp is not NULL, then the contents of the column-list are copied
  127982. ** to *pp. *pp is set to point to the first byte past the last byte copied
  127983. ** before this function returns. The POS_COLUMN or POS_END terminator
  127984. ** is not copied into *pp.
  127985. */
  127986. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  127987. char *pEnd = *ppPoslist;
  127988. char c = 0;
  127989. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  127990. ** not part of a multi-byte varint.
  127991. */
  127992. while( 0xFE & (*pEnd | c) ){
  127993. c = *pEnd++ & 0x80;
  127994. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  127995. }
  127996. if( pp ){
  127997. int n = (int)(pEnd - *ppPoslist);
  127998. char *p = *pp;
  127999. memcpy(p, *ppPoslist, n);
  128000. p += n;
  128001. *pp = p;
  128002. }
  128003. *ppPoslist = pEnd;
  128004. }
  128005. /*
  128006. ** Value used to signify the end of an position-list. This is safe because
  128007. ** it is not possible to have a document with 2^31 terms.
  128008. */
  128009. #define POSITION_LIST_END 0x7fffffff
  128010. /*
  128011. ** This function is used to help parse position-lists. When this function is
  128012. ** called, *pp may point to the start of the next varint in the position-list
  128013. ** being parsed, or it may point to 1 byte past the end of the position-list
  128014. ** (in which case **pp will be a terminator bytes POS_END (0) or
  128015. ** (1)).
  128016. **
  128017. ** If *pp points past the end of the current position-list, set *pi to
  128018. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  128019. ** increment the current value of *pi by the value read, and set *pp to
  128020. ** point to the next value before returning.
  128021. **
  128022. ** Before calling this routine *pi must be initialized to the value of
  128023. ** the previous position, or zero if we are reading the first position
  128024. ** in the position-list. Because positions are delta-encoded, the value
  128025. ** of the previous position is needed in order to compute the value of
  128026. ** the next position.
  128027. */
  128028. static void fts3ReadNextPos(
  128029. char **pp, /* IN/OUT: Pointer into position-list buffer */
  128030. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  128031. ){
  128032. if( (**pp)&0xFE ){
  128033. fts3GetDeltaVarint(pp, pi);
  128034. *pi -= 2;
  128035. }else{
  128036. *pi = POSITION_LIST_END;
  128037. }
  128038. }
  128039. /*
  128040. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  128041. ** the value of iCol encoded as a varint to *pp. This will start a new
  128042. ** column list.
  128043. **
  128044. ** Set *pp to point to the byte just after the last byte written before
  128045. ** returning (do not modify it if iCol==0). Return the total number of bytes
  128046. ** written (0 if iCol==0).
  128047. */
  128048. static int fts3PutColNumber(char **pp, int iCol){
  128049. int n = 0; /* Number of bytes written */
  128050. if( iCol ){
  128051. char *p = *pp; /* Output pointer */
  128052. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  128053. *p = 0x01;
  128054. *pp = &p[n];
  128055. }
  128056. return n;
  128057. }
  128058. /*
  128059. ** Compute the union of two position lists. The output written
  128060. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  128061. ** order and with any duplicates removed. All pointers are
  128062. ** updated appropriately. The caller is responsible for insuring
  128063. ** that there is enough space in *pp to hold the complete output.
  128064. */
  128065. static void fts3PoslistMerge(
  128066. char **pp, /* Output buffer */
  128067. char **pp1, /* Left input list */
  128068. char **pp2 /* Right input list */
  128069. ){
  128070. char *p = *pp;
  128071. char *p1 = *pp1;
  128072. char *p2 = *pp2;
  128073. while( *p1 || *p2 ){
  128074. int iCol1; /* The current column index in pp1 */
  128075. int iCol2; /* The current column index in pp2 */
  128076. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  128077. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  128078. else iCol1 = 0;
  128079. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  128080. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  128081. else iCol2 = 0;
  128082. if( iCol1==iCol2 ){
  128083. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  128084. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  128085. sqlite3_int64 iPrev = 0;
  128086. int n = fts3PutColNumber(&p, iCol1);
  128087. p1 += n;
  128088. p2 += n;
  128089. /* At this point, both p1 and p2 point to the start of column-lists
  128090. ** for the same column (the column with index iCol1 and iCol2).
  128091. ** A column-list is a list of non-negative delta-encoded varints, each
  128092. ** incremented by 2 before being stored. Each list is terminated by a
  128093. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  128094. ** and writes the results to buffer p. p is left pointing to the byte
  128095. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  128096. ** written to the output.
  128097. */
  128098. fts3GetDeltaVarint(&p1, &i1);
  128099. fts3GetDeltaVarint(&p2, &i2);
  128100. do {
  128101. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  128102. iPrev -= 2;
  128103. if( i1==i2 ){
  128104. fts3ReadNextPos(&p1, &i1);
  128105. fts3ReadNextPos(&p2, &i2);
  128106. }else if( i1<i2 ){
  128107. fts3ReadNextPos(&p1, &i1);
  128108. }else{
  128109. fts3ReadNextPos(&p2, &i2);
  128110. }
  128111. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  128112. }else if( iCol1<iCol2 ){
  128113. p1 += fts3PutColNumber(&p, iCol1);
  128114. fts3ColumnlistCopy(&p, &p1);
  128115. }else{
  128116. p2 += fts3PutColNumber(&p, iCol2);
  128117. fts3ColumnlistCopy(&p, &p2);
  128118. }
  128119. }
  128120. *p++ = POS_END;
  128121. *pp = p;
  128122. *pp1 = p1 + 1;
  128123. *pp2 = p2 + 1;
  128124. }
  128125. /*
  128126. ** This function is used to merge two position lists into one. When it is
  128127. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  128128. ** the part of a doclist that follows each document id. For example, if a row
  128129. ** contains:
  128130. **
  128131. ** 'a b c'|'x y z'|'a b b a'
  128132. **
  128133. ** Then the position list for this row for token 'b' would consist of:
  128134. **
  128135. ** 0x02 0x01 0x02 0x03 0x03 0x00
  128136. **
  128137. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  128138. ** byte following the 0x00 terminator of their respective position lists.
  128139. **
  128140. ** If isSaveLeft is 0, an entry is added to the output position list for
  128141. ** each position in *pp2 for which there exists one or more positions in
  128142. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  128143. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  128144. ** slots before it.
  128145. **
  128146. ** e.g. nToken==1 searches for adjacent positions.
  128147. */
  128148. static int fts3PoslistPhraseMerge(
  128149. char **pp, /* IN/OUT: Preallocated output buffer */
  128150. int nToken, /* Maximum difference in token positions */
  128151. int isSaveLeft, /* Save the left position */
  128152. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  128153. char **pp1, /* IN/OUT: Left input list */
  128154. char **pp2 /* IN/OUT: Right input list */
  128155. ){
  128156. char *p = *pp;
  128157. char *p1 = *pp1;
  128158. char *p2 = *pp2;
  128159. int iCol1 = 0;
  128160. int iCol2 = 0;
  128161. /* Never set both isSaveLeft and isExact for the same invocation. */
  128162. assert( isSaveLeft==0 || isExact==0 );
  128163. assert( p!=0 && *p1!=0 && *p2!=0 );
  128164. if( *p1==POS_COLUMN ){
  128165. p1++;
  128166. p1 += fts3GetVarint32(p1, &iCol1);
  128167. }
  128168. if( *p2==POS_COLUMN ){
  128169. p2++;
  128170. p2 += fts3GetVarint32(p2, &iCol2);
  128171. }
  128172. while( 1 ){
  128173. if( iCol1==iCol2 ){
  128174. char *pSave = p;
  128175. sqlite3_int64 iPrev = 0;
  128176. sqlite3_int64 iPos1 = 0;
  128177. sqlite3_int64 iPos2 = 0;
  128178. if( iCol1 ){
  128179. *p++ = POS_COLUMN;
  128180. p += sqlite3Fts3PutVarint(p, iCol1);
  128181. }
  128182. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  128183. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  128184. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  128185. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  128186. while( 1 ){
  128187. if( iPos2==iPos1+nToken
  128188. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  128189. ){
  128190. sqlite3_int64 iSave;
  128191. iSave = isSaveLeft ? iPos1 : iPos2;
  128192. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  128193. pSave = 0;
  128194. assert( p );
  128195. }
  128196. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  128197. if( (*p2&0xFE)==0 ) break;
  128198. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  128199. }else{
  128200. if( (*p1&0xFE)==0 ) break;
  128201. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  128202. }
  128203. }
  128204. if( pSave ){
  128205. assert( pp && p );
  128206. p = pSave;
  128207. }
  128208. fts3ColumnlistCopy(0, &p1);
  128209. fts3ColumnlistCopy(0, &p2);
  128210. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  128211. if( 0==*p1 || 0==*p2 ) break;
  128212. p1++;
  128213. p1 += fts3GetVarint32(p1, &iCol1);
  128214. p2++;
  128215. p2 += fts3GetVarint32(p2, &iCol2);
  128216. }
  128217. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  128218. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  128219. ** end of the position list, or the 0x01 that precedes the next
  128220. ** column-number in the position list.
  128221. */
  128222. else if( iCol1<iCol2 ){
  128223. fts3ColumnlistCopy(0, &p1);
  128224. if( 0==*p1 ) break;
  128225. p1++;
  128226. p1 += fts3GetVarint32(p1, &iCol1);
  128227. }else{
  128228. fts3ColumnlistCopy(0, &p2);
  128229. if( 0==*p2 ) break;
  128230. p2++;
  128231. p2 += fts3GetVarint32(p2, &iCol2);
  128232. }
  128233. }
  128234. fts3PoslistCopy(0, &p2);
  128235. fts3PoslistCopy(0, &p1);
  128236. *pp1 = p1;
  128237. *pp2 = p2;
  128238. if( *pp==p ){
  128239. return 0;
  128240. }
  128241. *p++ = 0x00;
  128242. *pp = p;
  128243. return 1;
  128244. }
  128245. /*
  128246. ** Merge two position-lists as required by the NEAR operator. The argument
  128247. ** position lists correspond to the left and right phrases of an expression
  128248. ** like:
  128249. **
  128250. ** "phrase 1" NEAR "phrase number 2"
  128251. **
  128252. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  128253. ** expression and *pp2 to the right. As usual, the indexes in the position
  128254. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  128255. ** in the example above).
  128256. **
  128257. ** The output position list - written to *pp - is a copy of *pp2 with those
  128258. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  128259. */
  128260. static int fts3PoslistNearMerge(
  128261. char **pp, /* Output buffer */
  128262. char *aTmp, /* Temporary buffer space */
  128263. int nRight, /* Maximum difference in token positions */
  128264. int nLeft, /* Maximum difference in token positions */
  128265. char **pp1, /* IN/OUT: Left input list */
  128266. char **pp2 /* IN/OUT: Right input list */
  128267. ){
  128268. char *p1 = *pp1;
  128269. char *p2 = *pp2;
  128270. char *pTmp1 = aTmp;
  128271. char *pTmp2;
  128272. char *aTmp2;
  128273. int res = 1;
  128274. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  128275. aTmp2 = pTmp2 = pTmp1;
  128276. *pp1 = p1;
  128277. *pp2 = p2;
  128278. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  128279. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  128280. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  128281. }else if( pTmp1!=aTmp ){
  128282. fts3PoslistCopy(pp, &aTmp);
  128283. }else if( pTmp2!=aTmp2 ){
  128284. fts3PoslistCopy(pp, &aTmp2);
  128285. }else{
  128286. res = 0;
  128287. }
  128288. return res;
  128289. }
  128290. /*
  128291. ** An instance of this function is used to merge together the (potentially
  128292. ** large number of) doclists for each term that matches a prefix query.
  128293. ** See function fts3TermSelectMerge() for details.
  128294. */
  128295. typedef struct TermSelect TermSelect;
  128296. struct TermSelect {
  128297. char *aaOutput[16]; /* Malloc'd output buffers */
  128298. int anOutput[16]; /* Size each output buffer in bytes */
  128299. };
  128300. /*
  128301. ** This function is used to read a single varint from a buffer. Parameter
  128302. ** pEnd points 1 byte past the end of the buffer. When this function is
  128303. ** called, if *pp points to pEnd or greater, then the end of the buffer
  128304. ** has been reached. In this case *pp is set to 0 and the function returns.
  128305. **
  128306. ** If *pp does not point to or past pEnd, then a single varint is read
  128307. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  128308. **
  128309. ** If bDescIdx is false, the value read is added to *pVal before returning.
  128310. ** If it is true, the value read is subtracted from *pVal before this
  128311. ** function returns.
  128312. */
  128313. static void fts3GetDeltaVarint3(
  128314. char **pp, /* IN/OUT: Point to read varint from */
  128315. char *pEnd, /* End of buffer */
  128316. int bDescIdx, /* True if docids are descending */
  128317. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  128318. ){
  128319. if( *pp>=pEnd ){
  128320. *pp = 0;
  128321. }else{
  128322. sqlite3_int64 iVal;
  128323. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  128324. if( bDescIdx ){
  128325. *pVal -= iVal;
  128326. }else{
  128327. *pVal += iVal;
  128328. }
  128329. }
  128330. }
  128331. /*
  128332. ** This function is used to write a single varint to a buffer. The varint
  128333. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  128334. ** end of the value written.
  128335. **
  128336. ** If *pbFirst is zero when this function is called, the value written to
  128337. ** the buffer is that of parameter iVal.
  128338. **
  128339. ** If *pbFirst is non-zero when this function is called, then the value
  128340. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  128341. ** (if bDescIdx is non-zero).
  128342. **
  128343. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  128344. ** to the value of parameter iVal.
  128345. */
  128346. static void fts3PutDeltaVarint3(
  128347. char **pp, /* IN/OUT: Output pointer */
  128348. int bDescIdx, /* True for descending docids */
  128349. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  128350. int *pbFirst, /* IN/OUT: True after first int written */
  128351. sqlite3_int64 iVal /* Write this value to the list */
  128352. ){
  128353. sqlite3_int64 iWrite;
  128354. if( bDescIdx==0 || *pbFirst==0 ){
  128355. iWrite = iVal - *piPrev;
  128356. }else{
  128357. iWrite = *piPrev - iVal;
  128358. }
  128359. assert( *pbFirst || *piPrev==0 );
  128360. assert( *pbFirst==0 || iWrite>0 );
  128361. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  128362. *piPrev = iVal;
  128363. *pbFirst = 1;
  128364. }
  128365. /*
  128366. ** This macro is used by various functions that merge doclists. The two
  128367. ** arguments are 64-bit docid values. If the value of the stack variable
  128368. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  128369. ** Otherwise, (i2-i1).
  128370. **
  128371. ** Using this makes it easier to write code that can merge doclists that are
  128372. ** sorted in either ascending or descending order.
  128373. */
  128374. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  128375. /*
  128376. ** This function does an "OR" merge of two doclists (output contains all
  128377. ** positions contained in either argument doclist). If the docids in the
  128378. ** input doclists are sorted in ascending order, parameter bDescDoclist
  128379. ** should be false. If they are sorted in ascending order, it should be
  128380. ** passed a non-zero value.
  128381. **
  128382. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  128383. ** containing the output doclist and SQLITE_OK is returned. In this case
  128384. ** *pnOut is set to the number of bytes in the output doclist.
  128385. **
  128386. ** If an error occurs, an SQLite error code is returned. The output values
  128387. ** are undefined in this case.
  128388. */
  128389. static int fts3DoclistOrMerge(
  128390. int bDescDoclist, /* True if arguments are desc */
  128391. char *a1, int n1, /* First doclist */
  128392. char *a2, int n2, /* Second doclist */
  128393. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  128394. ){
  128395. sqlite3_int64 i1 = 0;
  128396. sqlite3_int64 i2 = 0;
  128397. sqlite3_int64 iPrev = 0;
  128398. char *pEnd1 = &a1[n1];
  128399. char *pEnd2 = &a2[n2];
  128400. char *p1 = a1;
  128401. char *p2 = a2;
  128402. char *p;
  128403. char *aOut;
  128404. int bFirstOut = 0;
  128405. *paOut = 0;
  128406. *pnOut = 0;
  128407. /* Allocate space for the output. Both the input and output doclists
  128408. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  128409. ** then the first docid in each list is simply encoded as a varint. For
  128410. ** each subsequent docid, the varint stored is the difference between the
  128411. ** current and previous docid (a positive number - since the list is in
  128412. ** ascending order).
  128413. **
  128414. ** The first docid written to the output is therefore encoded using the
  128415. ** same number of bytes as it is in whichever of the input lists it is
  128416. ** read from. And each subsequent docid read from the same input list
  128417. ** consumes either the same or less bytes as it did in the input (since
  128418. ** the difference between it and the previous value in the output must
  128419. ** be a positive value less than or equal to the delta value read from
  128420. ** the input list). The same argument applies to all but the first docid
  128421. ** read from the 'other' list. And to the contents of all position lists
  128422. ** that will be copied and merged from the input to the output.
  128423. **
  128424. ** However, if the first docid copied to the output is a negative number,
  128425. ** then the encoding of the first docid from the 'other' input list may
  128426. ** be larger in the output than it was in the input (since the delta value
  128427. ** may be a larger positive integer than the actual docid).
  128428. **
  128429. ** The space required to store the output is therefore the sum of the
  128430. ** sizes of the two inputs, plus enough space for exactly one of the input
  128431. ** docids to grow.
  128432. **
  128433. ** A symetric argument may be made if the doclists are in descending
  128434. ** order.
  128435. */
  128436. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  128437. if( !aOut ) return SQLITE_NOMEM;
  128438. p = aOut;
  128439. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  128440. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  128441. while( p1 || p2 ){
  128442. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  128443. if( p2 && p1 && iDiff==0 ){
  128444. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  128445. fts3PoslistMerge(&p, &p1, &p2);
  128446. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  128447. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  128448. }else if( !p2 || (p1 && iDiff<0) ){
  128449. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  128450. fts3PoslistCopy(&p, &p1);
  128451. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  128452. }else{
  128453. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  128454. fts3PoslistCopy(&p, &p2);
  128455. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  128456. }
  128457. }
  128458. *paOut = aOut;
  128459. *pnOut = (int)(p-aOut);
  128460. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  128461. return SQLITE_OK;
  128462. }
  128463. /*
  128464. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  128465. ** the output contains a copy of each position from the right-hand input
  128466. ** doclist for which there is a position in the left-hand input doclist
  128467. ** exactly nDist tokens before it.
  128468. **
  128469. ** If the docids in the input doclists are sorted in ascending order,
  128470. ** parameter bDescDoclist should be false. If they are sorted in ascending
  128471. ** order, it should be passed a non-zero value.
  128472. **
  128473. ** The right-hand input doclist is overwritten by this function.
  128474. */
  128475. static int fts3DoclistPhraseMerge(
  128476. int bDescDoclist, /* True if arguments are desc */
  128477. int nDist, /* Distance from left to right (1=adjacent) */
  128478. char *aLeft, int nLeft, /* Left doclist */
  128479. char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
  128480. ){
  128481. sqlite3_int64 i1 = 0;
  128482. sqlite3_int64 i2 = 0;
  128483. sqlite3_int64 iPrev = 0;
  128484. char *aRight = *paRight;
  128485. char *pEnd1 = &aLeft[nLeft];
  128486. char *pEnd2 = &aRight[*pnRight];
  128487. char *p1 = aLeft;
  128488. char *p2 = aRight;
  128489. char *p;
  128490. int bFirstOut = 0;
  128491. char *aOut;
  128492. assert( nDist>0 );
  128493. if( bDescDoclist ){
  128494. aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
  128495. if( aOut==0 ) return SQLITE_NOMEM;
  128496. }else{
  128497. aOut = aRight;
  128498. }
  128499. p = aOut;
  128500. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  128501. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  128502. while( p1 && p2 ){
  128503. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  128504. if( iDiff==0 ){
  128505. char *pSave = p;
  128506. sqlite3_int64 iPrevSave = iPrev;
  128507. int bFirstOutSave = bFirstOut;
  128508. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  128509. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  128510. p = pSave;
  128511. iPrev = iPrevSave;
  128512. bFirstOut = bFirstOutSave;
  128513. }
  128514. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  128515. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  128516. }else if( iDiff<0 ){
  128517. fts3PoslistCopy(0, &p1);
  128518. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  128519. }else{
  128520. fts3PoslistCopy(0, &p2);
  128521. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  128522. }
  128523. }
  128524. *pnRight = (int)(p - aOut);
  128525. if( bDescDoclist ){
  128526. sqlite3_free(aRight);
  128527. *paRight = aOut;
  128528. }
  128529. return SQLITE_OK;
  128530. }
  128531. /*
  128532. ** Argument pList points to a position list nList bytes in size. This
  128533. ** function checks to see if the position list contains any entries for
  128534. ** a token in position 0 (of any column). If so, it writes argument iDelta
  128535. ** to the output buffer pOut, followed by a position list consisting only
  128536. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  128537. ** The value returned is the number of bytes written to pOut (if any).
  128538. */
  128539. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  128540. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  128541. char *pList, /* Position list (no 0x00 term) */
  128542. int nList, /* Size of pList in bytes */
  128543. char *pOut /* Write output here */
  128544. ){
  128545. int nOut = 0;
  128546. int bWritten = 0; /* True once iDelta has been written */
  128547. char *p = pList;
  128548. char *pEnd = &pList[nList];
  128549. if( *p!=0x01 ){
  128550. if( *p==0x02 ){
  128551. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  128552. pOut[nOut++] = 0x02;
  128553. bWritten = 1;
  128554. }
  128555. fts3ColumnlistCopy(0, &p);
  128556. }
  128557. while( p<pEnd && *p==0x01 ){
  128558. sqlite3_int64 iCol;
  128559. p++;
  128560. p += sqlite3Fts3GetVarint(p, &iCol);
  128561. if( *p==0x02 ){
  128562. if( bWritten==0 ){
  128563. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  128564. bWritten = 1;
  128565. }
  128566. pOut[nOut++] = 0x01;
  128567. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  128568. pOut[nOut++] = 0x02;
  128569. }
  128570. fts3ColumnlistCopy(0, &p);
  128571. }
  128572. if( bWritten ){
  128573. pOut[nOut++] = 0x00;
  128574. }
  128575. return nOut;
  128576. }
  128577. /*
  128578. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  128579. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  128580. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  128581. **
  128582. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  128583. ** the responsibility of the caller to free any doclists left in the
  128584. ** TermSelect.aaOutput[] array.
  128585. */
  128586. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  128587. char *aOut = 0;
  128588. int nOut = 0;
  128589. int i;
  128590. /* Loop through the doclists in the aaOutput[] array. Merge them all
  128591. ** into a single doclist.
  128592. */
  128593. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  128594. if( pTS->aaOutput[i] ){
  128595. if( !aOut ){
  128596. aOut = pTS->aaOutput[i];
  128597. nOut = pTS->anOutput[i];
  128598. pTS->aaOutput[i] = 0;
  128599. }else{
  128600. int nNew;
  128601. char *aNew;
  128602. int rc = fts3DoclistOrMerge(p->bDescIdx,
  128603. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  128604. );
  128605. if( rc!=SQLITE_OK ){
  128606. sqlite3_free(aOut);
  128607. return rc;
  128608. }
  128609. sqlite3_free(pTS->aaOutput[i]);
  128610. sqlite3_free(aOut);
  128611. pTS->aaOutput[i] = 0;
  128612. aOut = aNew;
  128613. nOut = nNew;
  128614. }
  128615. }
  128616. }
  128617. pTS->aaOutput[0] = aOut;
  128618. pTS->anOutput[0] = nOut;
  128619. return SQLITE_OK;
  128620. }
  128621. /*
  128622. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  128623. ** as the first argument. The merge is an "OR" merge (see function
  128624. ** fts3DoclistOrMerge() for details).
  128625. **
  128626. ** This function is called with the doclist for each term that matches
  128627. ** a queried prefix. It merges all these doclists into one, the doclist
  128628. ** for the specified prefix. Since there can be a very large number of
  128629. ** doclists to merge, the merging is done pair-wise using the TermSelect
  128630. ** object.
  128631. **
  128632. ** This function returns SQLITE_OK if the merge is successful, or an
  128633. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  128634. */
  128635. static int fts3TermSelectMerge(
  128636. Fts3Table *p, /* FTS table handle */
  128637. TermSelect *pTS, /* TermSelect object to merge into */
  128638. char *aDoclist, /* Pointer to doclist */
  128639. int nDoclist /* Size of aDoclist in bytes */
  128640. ){
  128641. if( pTS->aaOutput[0]==0 ){
  128642. /* If this is the first term selected, copy the doclist to the output
  128643. ** buffer using memcpy().
  128644. **
  128645. ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
  128646. ** allocation. This is so as to ensure that the buffer is big enough
  128647. ** to hold the current doclist AND'd with any other doclist. If the
  128648. ** doclists are stored in order=ASC order, this padding would not be
  128649. ** required (since the size of [doclistA AND doclistB] is always less
  128650. ** than or equal to the size of [doclistA] in that case). But this is
  128651. ** not true for order=DESC. For example, a doclist containing (1, -1)
  128652. ** may be smaller than (-1), as in the first example the -1 may be stored
  128653. ** as a single-byte delta, whereas in the second it must be stored as a
  128654. ** FTS3_VARINT_MAX byte varint.
  128655. **
  128656. ** Similar padding is added in the fts3DoclistOrMerge() function.
  128657. */
  128658. pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
  128659. pTS->anOutput[0] = nDoclist;
  128660. if( pTS->aaOutput[0] ){
  128661. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  128662. }else{
  128663. return SQLITE_NOMEM;
  128664. }
  128665. }else{
  128666. char *aMerge = aDoclist;
  128667. int nMerge = nDoclist;
  128668. int iOut;
  128669. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  128670. if( pTS->aaOutput[iOut]==0 ){
  128671. assert( iOut>0 );
  128672. pTS->aaOutput[iOut] = aMerge;
  128673. pTS->anOutput[iOut] = nMerge;
  128674. break;
  128675. }else{
  128676. char *aNew;
  128677. int nNew;
  128678. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  128679. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  128680. );
  128681. if( rc!=SQLITE_OK ){
  128682. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  128683. return rc;
  128684. }
  128685. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  128686. sqlite3_free(pTS->aaOutput[iOut]);
  128687. pTS->aaOutput[iOut] = 0;
  128688. aMerge = aNew;
  128689. nMerge = nNew;
  128690. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  128691. pTS->aaOutput[iOut] = aMerge;
  128692. pTS->anOutput[iOut] = nMerge;
  128693. }
  128694. }
  128695. }
  128696. }
  128697. return SQLITE_OK;
  128698. }
  128699. /*
  128700. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  128701. */
  128702. static int fts3SegReaderCursorAppend(
  128703. Fts3MultiSegReader *pCsr,
  128704. Fts3SegReader *pNew
  128705. ){
  128706. if( (pCsr->nSegment%16)==0 ){
  128707. Fts3SegReader **apNew;
  128708. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  128709. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  128710. if( !apNew ){
  128711. sqlite3Fts3SegReaderFree(pNew);
  128712. return SQLITE_NOMEM;
  128713. }
  128714. pCsr->apSegment = apNew;
  128715. }
  128716. pCsr->apSegment[pCsr->nSegment++] = pNew;
  128717. return SQLITE_OK;
  128718. }
  128719. /*
  128720. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  128721. ** 8th argument.
  128722. **
  128723. ** This function returns SQLITE_OK if successful, or an SQLite error code
  128724. ** otherwise.
  128725. */
  128726. static int fts3SegReaderCursor(
  128727. Fts3Table *p, /* FTS3 table handle */
  128728. int iLangid, /* Language id */
  128729. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  128730. int iLevel, /* Level of segments to scan */
  128731. const char *zTerm, /* Term to query for */
  128732. int nTerm, /* Size of zTerm in bytes */
  128733. int isPrefix, /* True for a prefix search */
  128734. int isScan, /* True to scan from zTerm to EOF */
  128735. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  128736. ){
  128737. int rc = SQLITE_OK; /* Error code */
  128738. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  128739. int rc2; /* Result of sqlite3_reset() */
  128740. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  128741. ** for the pending-terms. If this is a scan, then this call must be being
  128742. ** made by an fts4aux module, not an FTS table. In this case calling
  128743. ** Fts3SegReaderPending might segfault, as the data structures used by
  128744. ** fts4aux are not completely populated. So it's easiest to filter these
  128745. ** calls out here. */
  128746. if( iLevel<0 && p->aIndex ){
  128747. Fts3SegReader *pSeg = 0;
  128748. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
  128749. if( rc==SQLITE_OK && pSeg ){
  128750. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  128751. }
  128752. }
  128753. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  128754. if( rc==SQLITE_OK ){
  128755. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  128756. }
  128757. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  128758. Fts3SegReader *pSeg = 0;
  128759. /* Read the values returned by the SELECT into local variables. */
  128760. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  128761. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  128762. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  128763. int nRoot = sqlite3_column_bytes(pStmt, 4);
  128764. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  128765. /* If zTerm is not NULL, and this segment is not stored entirely on its
  128766. ** root node, the range of leaves scanned can be reduced. Do this. */
  128767. if( iStartBlock && zTerm ){
  128768. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  128769. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  128770. if( rc!=SQLITE_OK ) goto finished;
  128771. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  128772. }
  128773. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  128774. (isPrefix==0 && isScan==0),
  128775. iStartBlock, iLeavesEndBlock,
  128776. iEndBlock, zRoot, nRoot, &pSeg
  128777. );
  128778. if( rc!=SQLITE_OK ) goto finished;
  128779. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  128780. }
  128781. }
  128782. finished:
  128783. rc2 = sqlite3_reset(pStmt);
  128784. if( rc==SQLITE_DONE ) rc = rc2;
  128785. return rc;
  128786. }
  128787. /*
  128788. ** Set up a cursor object for iterating through a full-text index or a
  128789. ** single level therein.
  128790. */
  128791. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  128792. Fts3Table *p, /* FTS3 table handle */
  128793. int iLangid, /* Language-id to search */
  128794. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  128795. int iLevel, /* Level of segments to scan */
  128796. const char *zTerm, /* Term to query for */
  128797. int nTerm, /* Size of zTerm in bytes */
  128798. int isPrefix, /* True for a prefix search */
  128799. int isScan, /* True to scan from zTerm to EOF */
  128800. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  128801. ){
  128802. assert( iIndex>=0 && iIndex<p->nIndex );
  128803. assert( iLevel==FTS3_SEGCURSOR_ALL
  128804. || iLevel==FTS3_SEGCURSOR_PENDING
  128805. || iLevel>=0
  128806. );
  128807. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  128808. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  128809. assert( isPrefix==0 || isScan==0 );
  128810. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  128811. return fts3SegReaderCursor(
  128812. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  128813. );
  128814. }
  128815. /*
  128816. ** In addition to its current configuration, have the Fts3MultiSegReader
  128817. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  128818. **
  128819. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  128820. */
  128821. static int fts3SegReaderCursorAddZero(
  128822. Fts3Table *p, /* FTS virtual table handle */
  128823. int iLangid,
  128824. const char *zTerm, /* Term to scan doclist of */
  128825. int nTerm, /* Number of bytes in zTerm */
  128826. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  128827. ){
  128828. return fts3SegReaderCursor(p,
  128829. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  128830. );
  128831. }
  128832. /*
  128833. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  128834. ** if isPrefix is true, to scan the doclist for all terms for which
  128835. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  128836. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  128837. ** an SQLite error code.
  128838. **
  128839. ** It is the responsibility of the caller to free this object by eventually
  128840. ** passing it to fts3SegReaderCursorFree()
  128841. **
  128842. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  128843. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  128844. */
  128845. static int fts3TermSegReaderCursor(
  128846. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  128847. const char *zTerm, /* Term to query for */
  128848. int nTerm, /* Size of zTerm in bytes */
  128849. int isPrefix, /* True for a prefix search */
  128850. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  128851. ){
  128852. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  128853. int rc = SQLITE_NOMEM; /* Return code */
  128854. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  128855. if( pSegcsr ){
  128856. int i;
  128857. int bFound = 0; /* True once an index has been found */
  128858. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  128859. if( isPrefix ){
  128860. for(i=1; bFound==0 && i<p->nIndex; i++){
  128861. if( p->aIndex[i].nPrefix==nTerm ){
  128862. bFound = 1;
  128863. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  128864. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  128865. );
  128866. pSegcsr->bLookup = 1;
  128867. }
  128868. }
  128869. for(i=1; bFound==0 && i<p->nIndex; i++){
  128870. if( p->aIndex[i].nPrefix==nTerm+1 ){
  128871. bFound = 1;
  128872. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  128873. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  128874. );
  128875. if( rc==SQLITE_OK ){
  128876. rc = fts3SegReaderCursorAddZero(
  128877. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  128878. );
  128879. }
  128880. }
  128881. }
  128882. }
  128883. if( bFound==0 ){
  128884. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  128885. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  128886. );
  128887. pSegcsr->bLookup = !isPrefix;
  128888. }
  128889. }
  128890. *ppSegcsr = pSegcsr;
  128891. return rc;
  128892. }
  128893. /*
  128894. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  128895. */
  128896. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  128897. sqlite3Fts3SegReaderFinish(pSegcsr);
  128898. sqlite3_free(pSegcsr);
  128899. }
  128900. /*
  128901. ** This function retrieves the doclist for the specified term (or term
  128902. ** prefix) from the database.
  128903. */
  128904. static int fts3TermSelect(
  128905. Fts3Table *p, /* Virtual table handle */
  128906. Fts3PhraseToken *pTok, /* Token to query for */
  128907. int iColumn, /* Column to query (or -ve for all columns) */
  128908. int *pnOut, /* OUT: Size of buffer at *ppOut */
  128909. char **ppOut /* OUT: Malloced result buffer */
  128910. ){
  128911. int rc; /* Return code */
  128912. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  128913. TermSelect tsc; /* Object for pair-wise doclist merging */
  128914. Fts3SegFilter filter; /* Segment term filter configuration */
  128915. pSegcsr = pTok->pSegcsr;
  128916. memset(&tsc, 0, sizeof(TermSelect));
  128917. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  128918. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  128919. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  128920. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  128921. filter.iCol = iColumn;
  128922. filter.zTerm = pTok->z;
  128923. filter.nTerm = pTok->n;
  128924. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  128925. while( SQLITE_OK==rc
  128926. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  128927. ){
  128928. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  128929. }
  128930. if( rc==SQLITE_OK ){
  128931. rc = fts3TermSelectFinishMerge(p, &tsc);
  128932. }
  128933. if( rc==SQLITE_OK ){
  128934. *ppOut = tsc.aaOutput[0];
  128935. *pnOut = tsc.anOutput[0];
  128936. }else{
  128937. int i;
  128938. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  128939. sqlite3_free(tsc.aaOutput[i]);
  128940. }
  128941. }
  128942. fts3SegReaderCursorFree(pSegcsr);
  128943. pTok->pSegcsr = 0;
  128944. return rc;
  128945. }
  128946. /*
  128947. ** This function counts the total number of docids in the doclist stored
  128948. ** in buffer aList[], size nList bytes.
  128949. **
  128950. ** If the isPoslist argument is true, then it is assumed that the doclist
  128951. ** contains a position-list following each docid. Otherwise, it is assumed
  128952. ** that the doclist is simply a list of docids stored as delta encoded
  128953. ** varints.
  128954. */
  128955. static int fts3DoclistCountDocids(char *aList, int nList){
  128956. int nDoc = 0; /* Return value */
  128957. if( aList ){
  128958. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  128959. char *p = aList; /* Cursor */
  128960. while( p<aEnd ){
  128961. nDoc++;
  128962. while( (*p++)&0x80 ); /* Skip docid varint */
  128963. fts3PoslistCopy(0, &p); /* Skip over position list */
  128964. }
  128965. }
  128966. return nDoc;
  128967. }
  128968. /*
  128969. ** Advance the cursor to the next row in the %_content table that
  128970. ** matches the search criteria. For a MATCH search, this will be
  128971. ** the next row that matches. For a full-table scan, this will be
  128972. ** simply the next row in the %_content table. For a docid lookup,
  128973. ** this routine simply sets the EOF flag.
  128974. **
  128975. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  128976. ** even if we reach end-of-file. The fts3EofMethod() will be called
  128977. ** subsequently to determine whether or not an EOF was hit.
  128978. */
  128979. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  128980. int rc;
  128981. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  128982. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  128983. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  128984. pCsr->isEof = 1;
  128985. rc = sqlite3_reset(pCsr->pStmt);
  128986. }else{
  128987. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  128988. rc = SQLITE_OK;
  128989. }
  128990. }else{
  128991. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  128992. }
  128993. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  128994. return rc;
  128995. }
  128996. /*
  128997. ** The following are copied from sqliteInt.h.
  128998. **
  128999. ** Constants for the largest and smallest possible 64-bit signed integers.
  129000. ** These macros are designed to work correctly on both 32-bit and 64-bit
  129001. ** compilers.
  129002. */
  129003. #ifndef SQLITE_AMALGAMATION
  129004. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  129005. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  129006. #endif
  129007. /*
  129008. ** If the numeric type of argument pVal is "integer", then return it
  129009. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  129010. ** the second parameter, iDefault.
  129011. */
  129012. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  129013. if( pVal ){
  129014. int eType = sqlite3_value_numeric_type(pVal);
  129015. if( eType==SQLITE_INTEGER ){
  129016. return sqlite3_value_int64(pVal);
  129017. }
  129018. }
  129019. return iDefault;
  129020. }
  129021. /*
  129022. ** This is the xFilter interface for the virtual table. See
  129023. ** the virtual table xFilter method documentation for additional
  129024. ** information.
  129025. **
  129026. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  129027. ** the %_content table.
  129028. **
  129029. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  129030. ** in the %_content table.
  129031. **
  129032. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  129033. ** column on the left-hand side of the MATCH operator is column
  129034. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  129035. ** side of the MATCH operator.
  129036. */
  129037. static int fts3FilterMethod(
  129038. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  129039. int idxNum, /* Strategy index */
  129040. const char *idxStr, /* Unused */
  129041. int nVal, /* Number of elements in apVal */
  129042. sqlite3_value **apVal /* Arguments for the indexing scheme */
  129043. ){
  129044. int rc = SQLITE_OK;
  129045. char *zSql; /* SQL statement used to access %_content */
  129046. int eSearch;
  129047. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  129048. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  129049. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  129050. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  129051. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  129052. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  129053. int iIdx;
  129054. UNUSED_PARAMETER(idxStr);
  129055. UNUSED_PARAMETER(nVal);
  129056. eSearch = (idxNum & 0x0000FFFF);
  129057. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  129058. assert( p->pSegments==0 );
  129059. /* Collect arguments into local variables */
  129060. iIdx = 0;
  129061. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  129062. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  129063. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  129064. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  129065. assert( iIdx==nVal );
  129066. /* In case the cursor has been used before, clear it now. */
  129067. sqlite3_finalize(pCsr->pStmt);
  129068. sqlite3_free(pCsr->aDoclist);
  129069. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  129070. sqlite3Fts3ExprFree(pCsr->pExpr);
  129071. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  129072. /* Set the lower and upper bounds on docids to return */
  129073. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  129074. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  129075. if( idxStr ){
  129076. pCsr->bDesc = (idxStr[0]=='D');
  129077. }else{
  129078. pCsr->bDesc = p->bDescIdx;
  129079. }
  129080. pCsr->eSearch = (i16)eSearch;
  129081. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  129082. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  129083. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  129084. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  129085. return SQLITE_NOMEM;
  129086. }
  129087. pCsr->iLangid = 0;
  129088. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  129089. assert( p->base.zErrMsg==0 );
  129090. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  129091. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  129092. &p->base.zErrMsg
  129093. );
  129094. if( rc!=SQLITE_OK ){
  129095. return rc;
  129096. }
  129097. rc = fts3EvalStart(pCsr);
  129098. sqlite3Fts3SegmentsClose(p);
  129099. if( rc!=SQLITE_OK ) return rc;
  129100. pCsr->pNextId = pCsr->aDoclist;
  129101. pCsr->iPrevId = 0;
  129102. }
  129103. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  129104. ** statement loops through all rows of the %_content table. For a
  129105. ** full-text query or docid lookup, the statement retrieves a single
  129106. ** row by docid.
  129107. */
  129108. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  129109. if( pDocidGe || pDocidLe ){
  129110. zSql = sqlite3_mprintf(
  129111. "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
  129112. p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
  129113. (pCsr->bDesc ? "DESC" : "ASC")
  129114. );
  129115. }else{
  129116. zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
  129117. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  129118. );
  129119. }
  129120. if( zSql ){
  129121. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  129122. sqlite3_free(zSql);
  129123. }else{
  129124. rc = SQLITE_NOMEM;
  129125. }
  129126. }else if( eSearch==FTS3_DOCID_SEARCH ){
  129127. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  129128. if( rc==SQLITE_OK ){
  129129. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  129130. }
  129131. }
  129132. if( rc!=SQLITE_OK ) return rc;
  129133. return fts3NextMethod(pCursor);
  129134. }
  129135. /*
  129136. ** This is the xEof method of the virtual table. SQLite calls this
  129137. ** routine to find out if it has reached the end of a result set.
  129138. */
  129139. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  129140. return ((Fts3Cursor *)pCursor)->isEof;
  129141. }
  129142. /*
  129143. ** This is the xRowid method. The SQLite core calls this routine to
  129144. ** retrieve the rowid for the current row of the result set. fts3
  129145. ** exposes %_content.docid as the rowid for the virtual table. The
  129146. ** rowid should be written to *pRowid.
  129147. */
  129148. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  129149. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  129150. *pRowid = pCsr->iPrevId;
  129151. return SQLITE_OK;
  129152. }
  129153. /*
  129154. ** This is the xColumn method, called by SQLite to request a value from
  129155. ** the row that the supplied cursor currently points to.
  129156. **
  129157. ** If:
  129158. **
  129159. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  129160. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  129161. ** (iCol == p->nColumn+1) -> Docid column
  129162. ** (iCol == p->nColumn+2) -> Langid column
  129163. */
  129164. static int fts3ColumnMethod(
  129165. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  129166. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  129167. int iCol /* Index of column to read value from */
  129168. ){
  129169. int rc = SQLITE_OK; /* Return Code */
  129170. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  129171. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  129172. /* The column value supplied by SQLite must be in range. */
  129173. assert( iCol>=0 && iCol<=p->nColumn+2 );
  129174. if( iCol==p->nColumn+1 ){
  129175. /* This call is a request for the "docid" column. Since "docid" is an
  129176. ** alias for "rowid", use the xRowid() method to obtain the value.
  129177. */
  129178. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  129179. }else if( iCol==p->nColumn ){
  129180. /* The extra column whose name is the same as the table.
  129181. ** Return a blob which is a pointer to the cursor. */
  129182. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  129183. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  129184. sqlite3_result_int64(pCtx, pCsr->iLangid);
  129185. }else{
  129186. /* The requested column is either a user column (one that contains
  129187. ** indexed data), or the language-id column. */
  129188. rc = fts3CursorSeek(0, pCsr);
  129189. if( rc==SQLITE_OK ){
  129190. if( iCol==p->nColumn+2 ){
  129191. int iLangid = 0;
  129192. if( p->zLanguageid ){
  129193. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  129194. }
  129195. sqlite3_result_int(pCtx, iLangid);
  129196. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  129197. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  129198. }
  129199. }
  129200. }
  129201. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  129202. return rc;
  129203. }
  129204. /*
  129205. ** This function is the implementation of the xUpdate callback used by
  129206. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  129207. ** inserted, updated or deleted.
  129208. */
  129209. static int fts3UpdateMethod(
  129210. sqlite3_vtab *pVtab, /* Virtual table handle */
  129211. int nArg, /* Size of argument array */
  129212. sqlite3_value **apVal, /* Array of arguments */
  129213. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  129214. ){
  129215. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  129216. }
  129217. /*
  129218. ** Implementation of xSync() method. Flush the contents of the pending-terms
  129219. ** hash-table to the database.
  129220. */
  129221. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  129222. /* Following an incremental-merge operation, assuming that the input
  129223. ** segments are not completely consumed (the usual case), they are updated
  129224. ** in place to remove the entries that have already been merged. This
  129225. ** involves updating the leaf block that contains the smallest unmerged
  129226. ** entry and each block (if any) between the leaf and the root node. So
  129227. ** if the height of the input segment b-trees is N, and input segments
  129228. ** are merged eight at a time, updating the input segments at the end
  129229. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  129230. ** small - often between 0 and 2. So the overhead of the incremental
  129231. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  129232. ** dwarfing the actual productive work accomplished, the incremental merge
  129233. ** is only attempted if it will write at least 64 leaf blocks. Hence
  129234. ** nMinMerge.
  129235. **
  129236. ** Of course, updating the input segments also involves deleting a bunch
  129237. ** of blocks from the segments table. But this is not considered overhead
  129238. ** as it would also be required by a crisis-merge that used the same input
  129239. ** segments.
  129240. */
  129241. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  129242. Fts3Table *p = (Fts3Table*)pVtab;
  129243. int rc = sqlite3Fts3PendingTermsFlush(p);
  129244. if( rc==SQLITE_OK
  129245. && p->nLeafAdd>(nMinMerge/16)
  129246. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  129247. ){
  129248. int mxLevel = 0; /* Maximum relative level value in db */
  129249. int A; /* Incr-merge parameter A */
  129250. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  129251. assert( rc==SQLITE_OK || mxLevel==0 );
  129252. A = p->nLeafAdd * mxLevel;
  129253. A += (A/2);
  129254. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  129255. }
  129256. sqlite3Fts3SegmentsClose(p);
  129257. return rc;
  129258. }
  129259. /*
  129260. ** If it is currently unknown whether or not the FTS table has an %_stat
  129261. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  129262. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  129263. ** if an error occurs.
  129264. */
  129265. static int fts3SetHasStat(Fts3Table *p){
  129266. int rc = SQLITE_OK;
  129267. if( p->bHasStat==2 ){
  129268. const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
  129269. char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
  129270. if( zSql ){
  129271. sqlite3_stmt *pStmt = 0;
  129272. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  129273. if( rc==SQLITE_OK ){
  129274. int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
  129275. rc = sqlite3_finalize(pStmt);
  129276. if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
  129277. }
  129278. sqlite3_free(zSql);
  129279. }else{
  129280. rc = SQLITE_NOMEM;
  129281. }
  129282. }
  129283. return rc;
  129284. }
  129285. /*
  129286. ** Implementation of xBegin() method.
  129287. */
  129288. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  129289. Fts3Table *p = (Fts3Table*)pVtab;
  129290. UNUSED_PARAMETER(pVtab);
  129291. assert( p->pSegments==0 );
  129292. assert( p->nPendingData==0 );
  129293. assert( p->inTransaction!=1 );
  129294. TESTONLY( p->inTransaction = 1 );
  129295. TESTONLY( p->mxSavepoint = -1; );
  129296. p->nLeafAdd = 0;
  129297. return fts3SetHasStat(p);
  129298. }
  129299. /*
  129300. ** Implementation of xCommit() method. This is a no-op. The contents of
  129301. ** the pending-terms hash-table have already been flushed into the database
  129302. ** by fts3SyncMethod().
  129303. */
  129304. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  129305. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  129306. UNUSED_PARAMETER(pVtab);
  129307. assert( p->nPendingData==0 );
  129308. assert( p->inTransaction!=0 );
  129309. assert( p->pSegments==0 );
  129310. TESTONLY( p->inTransaction = 0 );
  129311. TESTONLY( p->mxSavepoint = -1; );
  129312. return SQLITE_OK;
  129313. }
  129314. /*
  129315. ** Implementation of xRollback(). Discard the contents of the pending-terms
  129316. ** hash-table. Any changes made to the database are reverted by SQLite.
  129317. */
  129318. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  129319. Fts3Table *p = (Fts3Table*)pVtab;
  129320. sqlite3Fts3PendingTermsClear(p);
  129321. assert( p->inTransaction!=0 );
  129322. TESTONLY( p->inTransaction = 0 );
  129323. TESTONLY( p->mxSavepoint = -1; );
  129324. return SQLITE_OK;
  129325. }
  129326. /*
  129327. ** When called, *ppPoslist must point to the byte immediately following the
  129328. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  129329. ** moves *ppPoslist so that it instead points to the first byte of the
  129330. ** same position list.
  129331. */
  129332. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  129333. char *p = &(*ppPoslist)[-2];
  129334. char c = 0;
  129335. /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
  129336. while( p>pStart && (c=*p--)==0 );
  129337. /* Search backwards for a varint with value zero (the end of the previous
  129338. ** poslist). This is an 0x00 byte preceded by some byte that does not
  129339. ** have the 0x80 bit set. */
  129340. while( p>pStart && (*p & 0x80) | c ){
  129341. c = *p--;
  129342. }
  129343. assert( p==pStart || c==0 );
  129344. /* At this point p points to that preceding byte without the 0x80 bit
  129345. ** set. So to find the start of the poslist, skip forward 2 bytes then
  129346. ** over a varint.
  129347. **
  129348. ** Normally. The other case is that p==pStart and the poslist to return
  129349. ** is the first in the doclist. In this case do not skip forward 2 bytes.
  129350. ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
  129351. ** is required for cases where the first byte of a doclist and the
  129352. ** doclist is empty. For example, if the first docid is 10, a doclist
  129353. ** that begins with:
  129354. **
  129355. ** 0x0A 0x00 <next docid delta varint>
  129356. */
  129357. if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
  129358. while( *p++&0x80 );
  129359. *ppPoslist = p;
  129360. }
  129361. /*
  129362. ** Helper function used by the implementation of the overloaded snippet(),
  129363. ** offsets() and optimize() SQL functions.
  129364. **
  129365. ** If the value passed as the third argument is a blob of size
  129366. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  129367. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  129368. ** message is written to context pContext and SQLITE_ERROR returned. The
  129369. ** string passed via zFunc is used as part of the error message.
  129370. */
  129371. static int fts3FunctionArg(
  129372. sqlite3_context *pContext, /* SQL function call context */
  129373. const char *zFunc, /* Function name */
  129374. sqlite3_value *pVal, /* argv[0] passed to function */
  129375. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  129376. ){
  129377. Fts3Cursor *pRet;
  129378. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  129379. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  129380. ){
  129381. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  129382. sqlite3_result_error(pContext, zErr, -1);
  129383. sqlite3_free(zErr);
  129384. return SQLITE_ERROR;
  129385. }
  129386. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  129387. *ppCsr = pRet;
  129388. return SQLITE_OK;
  129389. }
  129390. /*
  129391. ** Implementation of the snippet() function for FTS3
  129392. */
  129393. static void fts3SnippetFunc(
  129394. sqlite3_context *pContext, /* SQLite function call context */
  129395. int nVal, /* Size of apVal[] array */
  129396. sqlite3_value **apVal /* Array of arguments */
  129397. ){
  129398. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  129399. const char *zStart = "<b>";
  129400. const char *zEnd = "</b>";
  129401. const char *zEllipsis = "<b>...</b>";
  129402. int iCol = -1;
  129403. int nToken = 15; /* Default number of tokens in snippet */
  129404. /* There must be at least one argument passed to this function (otherwise
  129405. ** the non-overloaded version would have been called instead of this one).
  129406. */
  129407. assert( nVal>=1 );
  129408. if( nVal>6 ){
  129409. sqlite3_result_error(pContext,
  129410. "wrong number of arguments to function snippet()", -1);
  129411. return;
  129412. }
  129413. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  129414. switch( nVal ){
  129415. case 6: nToken = sqlite3_value_int(apVal[5]);
  129416. case 5: iCol = sqlite3_value_int(apVal[4]);
  129417. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  129418. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  129419. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  129420. }
  129421. if( !zEllipsis || !zEnd || !zStart ){
  129422. sqlite3_result_error_nomem(pContext);
  129423. }else if( nToken==0 ){
  129424. sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
  129425. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  129426. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  129427. }
  129428. }
  129429. /*
  129430. ** Implementation of the offsets() function for FTS3
  129431. */
  129432. static void fts3OffsetsFunc(
  129433. sqlite3_context *pContext, /* SQLite function call context */
  129434. int nVal, /* Size of argument array */
  129435. sqlite3_value **apVal /* Array of arguments */
  129436. ){
  129437. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  129438. UNUSED_PARAMETER(nVal);
  129439. assert( nVal==1 );
  129440. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  129441. assert( pCsr );
  129442. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  129443. sqlite3Fts3Offsets(pContext, pCsr);
  129444. }
  129445. }
  129446. /*
  129447. ** Implementation of the special optimize() function for FTS3. This
  129448. ** function merges all segments in the database to a single segment.
  129449. ** Example usage is:
  129450. **
  129451. ** SELECT optimize(t) FROM t LIMIT 1;
  129452. **
  129453. ** where 't' is the name of an FTS3 table.
  129454. */
  129455. static void fts3OptimizeFunc(
  129456. sqlite3_context *pContext, /* SQLite function call context */
  129457. int nVal, /* Size of argument array */
  129458. sqlite3_value **apVal /* Array of arguments */
  129459. ){
  129460. int rc; /* Return code */
  129461. Fts3Table *p; /* Virtual table handle */
  129462. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  129463. UNUSED_PARAMETER(nVal);
  129464. assert( nVal==1 );
  129465. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  129466. p = (Fts3Table *)pCursor->base.pVtab;
  129467. assert( p );
  129468. rc = sqlite3Fts3Optimize(p);
  129469. switch( rc ){
  129470. case SQLITE_OK:
  129471. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  129472. break;
  129473. case SQLITE_DONE:
  129474. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  129475. break;
  129476. default:
  129477. sqlite3_result_error_code(pContext, rc);
  129478. break;
  129479. }
  129480. }
  129481. /*
  129482. ** Implementation of the matchinfo() function for FTS3
  129483. */
  129484. static void fts3MatchinfoFunc(
  129485. sqlite3_context *pContext, /* SQLite function call context */
  129486. int nVal, /* Size of argument array */
  129487. sqlite3_value **apVal /* Array of arguments */
  129488. ){
  129489. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  129490. assert( nVal==1 || nVal==2 );
  129491. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  129492. const char *zArg = 0;
  129493. if( nVal>1 ){
  129494. zArg = (const char *)sqlite3_value_text(apVal[1]);
  129495. }
  129496. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  129497. }
  129498. }
  129499. /*
  129500. ** This routine implements the xFindFunction method for the FTS3
  129501. ** virtual table.
  129502. */
  129503. static int fts3FindFunctionMethod(
  129504. sqlite3_vtab *pVtab, /* Virtual table handle */
  129505. int nArg, /* Number of SQL function arguments */
  129506. const char *zName, /* Name of SQL function */
  129507. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  129508. void **ppArg /* Unused */
  129509. ){
  129510. struct Overloaded {
  129511. const char *zName;
  129512. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  129513. } aOverload[] = {
  129514. { "snippet", fts3SnippetFunc },
  129515. { "offsets", fts3OffsetsFunc },
  129516. { "optimize", fts3OptimizeFunc },
  129517. { "matchinfo", fts3MatchinfoFunc },
  129518. };
  129519. int i; /* Iterator variable */
  129520. UNUSED_PARAMETER(pVtab);
  129521. UNUSED_PARAMETER(nArg);
  129522. UNUSED_PARAMETER(ppArg);
  129523. for(i=0; i<SizeofArray(aOverload); i++){
  129524. if( strcmp(zName, aOverload[i].zName)==0 ){
  129525. *pxFunc = aOverload[i].xFunc;
  129526. return 1;
  129527. }
  129528. }
  129529. /* No function of the specified name was found. Return 0. */
  129530. return 0;
  129531. }
  129532. /*
  129533. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  129534. */
  129535. static int fts3RenameMethod(
  129536. sqlite3_vtab *pVtab, /* Virtual table handle */
  129537. const char *zName /* New name of table */
  129538. ){
  129539. Fts3Table *p = (Fts3Table *)pVtab;
  129540. sqlite3 *db = p->db; /* Database connection */
  129541. int rc; /* Return Code */
  129542. /* At this point it must be known if the %_stat table exists or not.
  129543. ** So bHasStat may not be 2. */
  129544. rc = fts3SetHasStat(p);
  129545. /* As it happens, the pending terms table is always empty here. This is
  129546. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  129547. ** always opens a savepoint transaction. And the xSavepoint() method
  129548. ** flushes the pending terms table. But leave the (no-op) call to
  129549. ** PendingTermsFlush() in in case that changes.
  129550. */
  129551. assert( p->nPendingData==0 );
  129552. if( rc==SQLITE_OK ){
  129553. rc = sqlite3Fts3PendingTermsFlush(p);
  129554. }
  129555. if( p->zContentTbl==0 ){
  129556. fts3DbExec(&rc, db,
  129557. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  129558. p->zDb, p->zName, zName
  129559. );
  129560. }
  129561. if( p->bHasDocsize ){
  129562. fts3DbExec(&rc, db,
  129563. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  129564. p->zDb, p->zName, zName
  129565. );
  129566. }
  129567. if( p->bHasStat ){
  129568. fts3DbExec(&rc, db,
  129569. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  129570. p->zDb, p->zName, zName
  129571. );
  129572. }
  129573. fts3DbExec(&rc, db,
  129574. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  129575. p->zDb, p->zName, zName
  129576. );
  129577. fts3DbExec(&rc, db,
  129578. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  129579. p->zDb, p->zName, zName
  129580. );
  129581. return rc;
  129582. }
  129583. /*
  129584. ** The xSavepoint() method.
  129585. **
  129586. ** Flush the contents of the pending-terms table to disk.
  129587. */
  129588. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  129589. int rc = SQLITE_OK;
  129590. UNUSED_PARAMETER(iSavepoint);
  129591. assert( ((Fts3Table *)pVtab)->inTransaction );
  129592. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  129593. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  129594. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  129595. rc = fts3SyncMethod(pVtab);
  129596. }
  129597. return rc;
  129598. }
  129599. /*
  129600. ** The xRelease() method.
  129601. **
  129602. ** This is a no-op.
  129603. */
  129604. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  129605. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  129606. UNUSED_PARAMETER(iSavepoint);
  129607. UNUSED_PARAMETER(pVtab);
  129608. assert( p->inTransaction );
  129609. assert( p->mxSavepoint >= iSavepoint );
  129610. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  129611. return SQLITE_OK;
  129612. }
  129613. /*
  129614. ** The xRollbackTo() method.
  129615. **
  129616. ** Discard the contents of the pending terms table.
  129617. */
  129618. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  129619. Fts3Table *p = (Fts3Table*)pVtab;
  129620. UNUSED_PARAMETER(iSavepoint);
  129621. assert( p->inTransaction );
  129622. assert( p->mxSavepoint >= iSavepoint );
  129623. TESTONLY( p->mxSavepoint = iSavepoint );
  129624. sqlite3Fts3PendingTermsClear(p);
  129625. return SQLITE_OK;
  129626. }
  129627. static const sqlite3_module fts3Module = {
  129628. /* iVersion */ 2,
  129629. /* xCreate */ fts3CreateMethod,
  129630. /* xConnect */ fts3ConnectMethod,
  129631. /* xBestIndex */ fts3BestIndexMethod,
  129632. /* xDisconnect */ fts3DisconnectMethod,
  129633. /* xDestroy */ fts3DestroyMethod,
  129634. /* xOpen */ fts3OpenMethod,
  129635. /* xClose */ fts3CloseMethod,
  129636. /* xFilter */ fts3FilterMethod,
  129637. /* xNext */ fts3NextMethod,
  129638. /* xEof */ fts3EofMethod,
  129639. /* xColumn */ fts3ColumnMethod,
  129640. /* xRowid */ fts3RowidMethod,
  129641. /* xUpdate */ fts3UpdateMethod,
  129642. /* xBegin */ fts3BeginMethod,
  129643. /* xSync */ fts3SyncMethod,
  129644. /* xCommit */ fts3CommitMethod,
  129645. /* xRollback */ fts3RollbackMethod,
  129646. /* xFindFunction */ fts3FindFunctionMethod,
  129647. /* xRename */ fts3RenameMethod,
  129648. /* xSavepoint */ fts3SavepointMethod,
  129649. /* xRelease */ fts3ReleaseMethod,
  129650. /* xRollbackTo */ fts3RollbackToMethod,
  129651. };
  129652. /*
  129653. ** This function is registered as the module destructor (called when an
  129654. ** FTS3 enabled database connection is closed). It frees the memory
  129655. ** allocated for the tokenizer hash table.
  129656. */
  129657. static void hashDestroy(void *p){
  129658. Fts3Hash *pHash = (Fts3Hash *)p;
  129659. sqlite3Fts3HashClear(pHash);
  129660. sqlite3_free(pHash);
  129661. }
  129662. /*
  129663. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  129664. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  129665. ** respectively. The following three forward declarations are for functions
  129666. ** declared in these files used to retrieve the respective implementations.
  129667. **
  129668. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  129669. ** to by the argument to point to the "simple" tokenizer implementation.
  129670. ** And so on.
  129671. */
  129672. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  129673. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  129674. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  129675. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  129676. #endif
  129677. #ifdef SQLITE_ENABLE_ICU
  129678. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  129679. #endif
  129680. /*
  129681. ** Initialize the fts3 extension. If this extension is built as part
  129682. ** of the sqlite library, then this function is called directly by
  129683. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  129684. ** function is called by the sqlite3_extension_init() entry point.
  129685. */
  129686. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  129687. int rc = SQLITE_OK;
  129688. Fts3Hash *pHash = 0;
  129689. const sqlite3_tokenizer_module *pSimple = 0;
  129690. const sqlite3_tokenizer_module *pPorter = 0;
  129691. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  129692. const sqlite3_tokenizer_module *pUnicode = 0;
  129693. #endif
  129694. #ifdef SQLITE_ENABLE_ICU
  129695. const sqlite3_tokenizer_module *pIcu = 0;
  129696. sqlite3Fts3IcuTokenizerModule(&pIcu);
  129697. #endif
  129698. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  129699. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  129700. #endif
  129701. #ifdef SQLITE_TEST
  129702. rc = sqlite3Fts3InitTerm(db);
  129703. if( rc!=SQLITE_OK ) return rc;
  129704. #endif
  129705. rc = sqlite3Fts3InitAux(db);
  129706. if( rc!=SQLITE_OK ) return rc;
  129707. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  129708. sqlite3Fts3PorterTokenizerModule(&pPorter);
  129709. /* Allocate and initialize the hash-table used to store tokenizers. */
  129710. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  129711. if( !pHash ){
  129712. rc = SQLITE_NOMEM;
  129713. }else{
  129714. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  129715. }
  129716. /* Load the built-in tokenizers into the hash table */
  129717. if( rc==SQLITE_OK ){
  129718. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  129719. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  129720. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  129721. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  129722. #endif
  129723. #ifdef SQLITE_ENABLE_ICU
  129724. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  129725. #endif
  129726. ){
  129727. rc = SQLITE_NOMEM;
  129728. }
  129729. }
  129730. #ifdef SQLITE_TEST
  129731. if( rc==SQLITE_OK ){
  129732. rc = sqlite3Fts3ExprInitTestInterface(db);
  129733. }
  129734. #endif
  129735. /* Create the virtual table wrapper around the hash-table and overload
  129736. ** the two scalar functions. If this is successful, register the
  129737. ** module with sqlite.
  129738. */
  129739. if( SQLITE_OK==rc
  129740. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  129741. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  129742. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  129743. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  129744. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  129745. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  129746. ){
  129747. rc = sqlite3_create_module_v2(
  129748. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  129749. );
  129750. if( rc==SQLITE_OK ){
  129751. rc = sqlite3_create_module_v2(
  129752. db, "fts4", &fts3Module, (void *)pHash, 0
  129753. );
  129754. }
  129755. if( rc==SQLITE_OK ){
  129756. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  129757. }
  129758. return rc;
  129759. }
  129760. /* An error has occurred. Delete the hash table and return the error code. */
  129761. assert( rc!=SQLITE_OK );
  129762. if( pHash ){
  129763. sqlite3Fts3HashClear(pHash);
  129764. sqlite3_free(pHash);
  129765. }
  129766. return rc;
  129767. }
  129768. /*
  129769. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  129770. ** by pExpr.
  129771. **
  129772. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  129773. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  129774. ** Fts3SegReader objects internally to provide an interface to seek or scan
  129775. ** within the union of all segments of a b-tree. Hence the name.
  129776. **
  129777. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  129778. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  129779. ** there exists prefix b-tree of the right length) then it may be traversed
  129780. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  129781. ** doclist and then traversed.
  129782. */
  129783. static void fts3EvalAllocateReaders(
  129784. Fts3Cursor *pCsr, /* FTS cursor handle */
  129785. Fts3Expr *pExpr, /* Allocate readers for this expression */
  129786. int *pnToken, /* OUT: Total number of tokens in phrase. */
  129787. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  129788. int *pRc /* IN/OUT: Error code */
  129789. ){
  129790. if( pExpr && SQLITE_OK==*pRc ){
  129791. if( pExpr->eType==FTSQUERY_PHRASE ){
  129792. int i;
  129793. int nToken = pExpr->pPhrase->nToken;
  129794. *pnToken += nToken;
  129795. for(i=0; i<nToken; i++){
  129796. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  129797. int rc = fts3TermSegReaderCursor(pCsr,
  129798. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  129799. );
  129800. if( rc!=SQLITE_OK ){
  129801. *pRc = rc;
  129802. return;
  129803. }
  129804. }
  129805. assert( pExpr->pPhrase->iDoclistToken==0 );
  129806. pExpr->pPhrase->iDoclistToken = -1;
  129807. }else{
  129808. *pnOr += (pExpr->eType==FTSQUERY_OR);
  129809. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  129810. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  129811. }
  129812. }
  129813. }
  129814. /*
  129815. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  129816. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  129817. **
  129818. ** This function assumes that pList points to a buffer allocated using
  129819. ** sqlite3_malloc(). This function takes responsibility for eventually
  129820. ** freeing the buffer.
  129821. **
  129822. ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
  129823. */
  129824. static int fts3EvalPhraseMergeToken(
  129825. Fts3Table *pTab, /* FTS Table pointer */
  129826. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  129827. int iToken, /* Token pList/nList corresponds to */
  129828. char *pList, /* Pointer to doclist */
  129829. int nList /* Number of bytes in pList */
  129830. ){
  129831. int rc = SQLITE_OK;
  129832. assert( iToken!=p->iDoclistToken );
  129833. if( pList==0 ){
  129834. sqlite3_free(p->doclist.aAll);
  129835. p->doclist.aAll = 0;
  129836. p->doclist.nAll = 0;
  129837. }
  129838. else if( p->iDoclistToken<0 ){
  129839. p->doclist.aAll = pList;
  129840. p->doclist.nAll = nList;
  129841. }
  129842. else if( p->doclist.aAll==0 ){
  129843. sqlite3_free(pList);
  129844. }
  129845. else {
  129846. char *pLeft;
  129847. char *pRight;
  129848. int nLeft;
  129849. int nRight;
  129850. int nDiff;
  129851. if( p->iDoclistToken<iToken ){
  129852. pLeft = p->doclist.aAll;
  129853. nLeft = p->doclist.nAll;
  129854. pRight = pList;
  129855. nRight = nList;
  129856. nDiff = iToken - p->iDoclistToken;
  129857. }else{
  129858. pRight = p->doclist.aAll;
  129859. nRight = p->doclist.nAll;
  129860. pLeft = pList;
  129861. nLeft = nList;
  129862. nDiff = p->iDoclistToken - iToken;
  129863. }
  129864. rc = fts3DoclistPhraseMerge(
  129865. pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
  129866. );
  129867. sqlite3_free(pLeft);
  129868. p->doclist.aAll = pRight;
  129869. p->doclist.nAll = nRight;
  129870. }
  129871. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  129872. return rc;
  129873. }
  129874. /*
  129875. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  129876. ** does not take deferred tokens into account.
  129877. **
  129878. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  129879. */
  129880. static int fts3EvalPhraseLoad(
  129881. Fts3Cursor *pCsr, /* FTS Cursor handle */
  129882. Fts3Phrase *p /* Phrase object */
  129883. ){
  129884. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  129885. int iToken;
  129886. int rc = SQLITE_OK;
  129887. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  129888. Fts3PhraseToken *pToken = &p->aToken[iToken];
  129889. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  129890. if( pToken->pSegcsr ){
  129891. int nThis = 0;
  129892. char *pThis = 0;
  129893. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  129894. if( rc==SQLITE_OK ){
  129895. rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  129896. }
  129897. }
  129898. assert( pToken->pSegcsr==0 );
  129899. }
  129900. return rc;
  129901. }
  129902. /*
  129903. ** This function is called on each phrase after the position lists for
  129904. ** any deferred tokens have been loaded into memory. It updates the phrases
  129905. ** current position list to include only those positions that are really
  129906. ** instances of the phrase (after considering deferred tokens). If this
  129907. ** means that the phrase does not appear in the current row, doclist.pList
  129908. ** and doclist.nList are both zeroed.
  129909. **
  129910. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  129911. */
  129912. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  129913. int iToken; /* Used to iterate through phrase tokens */
  129914. char *aPoslist = 0; /* Position list for deferred tokens */
  129915. int nPoslist = 0; /* Number of bytes in aPoslist */
  129916. int iPrev = -1; /* Token number of previous deferred token */
  129917. assert( pPhrase->doclist.bFreeList==0 );
  129918. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  129919. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  129920. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  129921. if( pDeferred ){
  129922. char *pList;
  129923. int nList;
  129924. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  129925. if( rc!=SQLITE_OK ) return rc;
  129926. if( pList==0 ){
  129927. sqlite3_free(aPoslist);
  129928. pPhrase->doclist.pList = 0;
  129929. pPhrase->doclist.nList = 0;
  129930. return SQLITE_OK;
  129931. }else if( aPoslist==0 ){
  129932. aPoslist = pList;
  129933. nPoslist = nList;
  129934. }else{
  129935. char *aOut = pList;
  129936. char *p1 = aPoslist;
  129937. char *p2 = aOut;
  129938. assert( iPrev>=0 );
  129939. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  129940. sqlite3_free(aPoslist);
  129941. aPoslist = pList;
  129942. nPoslist = (int)(aOut - aPoslist);
  129943. if( nPoslist==0 ){
  129944. sqlite3_free(aPoslist);
  129945. pPhrase->doclist.pList = 0;
  129946. pPhrase->doclist.nList = 0;
  129947. return SQLITE_OK;
  129948. }
  129949. }
  129950. iPrev = iToken;
  129951. }
  129952. }
  129953. if( iPrev>=0 ){
  129954. int nMaxUndeferred = pPhrase->iDoclistToken;
  129955. if( nMaxUndeferred<0 ){
  129956. pPhrase->doclist.pList = aPoslist;
  129957. pPhrase->doclist.nList = nPoslist;
  129958. pPhrase->doclist.iDocid = pCsr->iPrevId;
  129959. pPhrase->doclist.bFreeList = 1;
  129960. }else{
  129961. int nDistance;
  129962. char *p1;
  129963. char *p2;
  129964. char *aOut;
  129965. if( nMaxUndeferred>iPrev ){
  129966. p1 = aPoslist;
  129967. p2 = pPhrase->doclist.pList;
  129968. nDistance = nMaxUndeferred - iPrev;
  129969. }else{
  129970. p1 = pPhrase->doclist.pList;
  129971. p2 = aPoslist;
  129972. nDistance = iPrev - nMaxUndeferred;
  129973. }
  129974. aOut = (char *)sqlite3_malloc(nPoslist+8);
  129975. if( !aOut ){
  129976. sqlite3_free(aPoslist);
  129977. return SQLITE_NOMEM;
  129978. }
  129979. pPhrase->doclist.pList = aOut;
  129980. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  129981. pPhrase->doclist.bFreeList = 1;
  129982. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  129983. }else{
  129984. sqlite3_free(aOut);
  129985. pPhrase->doclist.pList = 0;
  129986. pPhrase->doclist.nList = 0;
  129987. }
  129988. sqlite3_free(aPoslist);
  129989. }
  129990. }
  129991. return SQLITE_OK;
  129992. }
  129993. /*
  129994. ** Maximum number of tokens a phrase may have to be considered for the
  129995. ** incremental doclists strategy.
  129996. */
  129997. #define MAX_INCR_PHRASE_TOKENS 4
  129998. /*
  129999. ** This function is called for each Fts3Phrase in a full-text query
  130000. ** expression to initialize the mechanism for returning rows. Once this
  130001. ** function has been called successfully on an Fts3Phrase, it may be
  130002. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  130003. **
  130004. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  130005. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  130006. ** memory within this call.
  130007. **
  130008. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  130009. */
  130010. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  130011. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  130012. int rc = SQLITE_OK; /* Error code */
  130013. int i;
  130014. /* Determine if doclists may be loaded from disk incrementally. This is
  130015. ** possible if the bOptOk argument is true, the FTS doclists will be
  130016. ** scanned in forward order, and the phrase consists of
  130017. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  130018. ** tokens or prefix tokens that cannot use a prefix-index. */
  130019. int bHaveIncr = 0;
  130020. int bIncrOk = (bOptOk
  130021. && pCsr->bDesc==pTab->bDescIdx
  130022. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  130023. #ifdef SQLITE_TEST
  130024. && pTab->bNoIncrDoclist==0
  130025. #endif
  130026. );
  130027. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  130028. Fts3PhraseToken *pToken = &p->aToken[i];
  130029. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  130030. bIncrOk = 0;
  130031. }
  130032. if( pToken->pSegcsr ) bHaveIncr = 1;
  130033. }
  130034. if( bIncrOk && bHaveIncr ){
  130035. /* Use the incremental approach. */
  130036. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  130037. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  130038. Fts3PhraseToken *pToken = &p->aToken[i];
  130039. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  130040. if( pSegcsr ){
  130041. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  130042. }
  130043. }
  130044. p->bIncr = 1;
  130045. }else{
  130046. /* Load the full doclist for the phrase into memory. */
  130047. rc = fts3EvalPhraseLoad(pCsr, p);
  130048. p->bIncr = 0;
  130049. }
  130050. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  130051. return rc;
  130052. }
  130053. /*
  130054. ** This function is used to iterate backwards (from the end to start)
  130055. ** through doclists. It is used by this module to iterate through phrase
  130056. ** doclists in reverse and by the fts3_write.c module to iterate through
  130057. ** pending-terms lists when writing to databases with "order=desc".
  130058. **
  130059. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  130060. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  130061. ** function iterates from the end of the doclist to the beginning.
  130062. */
  130063. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  130064. int bDescIdx, /* True if the doclist is desc */
  130065. char *aDoclist, /* Pointer to entire doclist */
  130066. int nDoclist, /* Length of aDoclist in bytes */
  130067. char **ppIter, /* IN/OUT: Iterator pointer */
  130068. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  130069. int *pnList, /* OUT: List length pointer */
  130070. u8 *pbEof /* OUT: End-of-file flag */
  130071. ){
  130072. char *p = *ppIter;
  130073. assert( nDoclist>0 );
  130074. assert( *pbEof==0 );
  130075. assert( p || *piDocid==0 );
  130076. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  130077. if( p==0 ){
  130078. sqlite3_int64 iDocid = 0;
  130079. char *pNext = 0;
  130080. char *pDocid = aDoclist;
  130081. char *pEnd = &aDoclist[nDoclist];
  130082. int iMul = 1;
  130083. while( pDocid<pEnd ){
  130084. sqlite3_int64 iDelta;
  130085. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  130086. iDocid += (iMul * iDelta);
  130087. pNext = pDocid;
  130088. fts3PoslistCopy(0, &pDocid);
  130089. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  130090. iMul = (bDescIdx ? -1 : 1);
  130091. }
  130092. *pnList = (int)(pEnd - pNext);
  130093. *ppIter = pNext;
  130094. *piDocid = iDocid;
  130095. }else{
  130096. int iMul = (bDescIdx ? -1 : 1);
  130097. sqlite3_int64 iDelta;
  130098. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  130099. *piDocid -= (iMul * iDelta);
  130100. if( p==aDoclist ){
  130101. *pbEof = 1;
  130102. }else{
  130103. char *pSave = p;
  130104. fts3ReversePoslist(aDoclist, &p);
  130105. *pnList = (int)(pSave - p);
  130106. }
  130107. *ppIter = p;
  130108. }
  130109. }
  130110. /*
  130111. ** Iterate forwards through a doclist.
  130112. */
  130113. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  130114. int bDescIdx, /* True if the doclist is desc */
  130115. char *aDoclist, /* Pointer to entire doclist */
  130116. int nDoclist, /* Length of aDoclist in bytes */
  130117. char **ppIter, /* IN/OUT: Iterator pointer */
  130118. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  130119. u8 *pbEof /* OUT: End-of-file flag */
  130120. ){
  130121. char *p = *ppIter;
  130122. assert( nDoclist>0 );
  130123. assert( *pbEof==0 );
  130124. assert( p || *piDocid==0 );
  130125. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  130126. if( p==0 ){
  130127. p = aDoclist;
  130128. p += sqlite3Fts3GetVarint(p, piDocid);
  130129. }else{
  130130. fts3PoslistCopy(0, &p);
  130131. while( p<&aDoclist[nDoclist] && *p==0 ) p++;
  130132. if( p>=&aDoclist[nDoclist] ){
  130133. *pbEof = 1;
  130134. }else{
  130135. sqlite3_int64 iVar;
  130136. p += sqlite3Fts3GetVarint(p, &iVar);
  130137. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  130138. }
  130139. }
  130140. *ppIter = p;
  130141. }
  130142. /*
  130143. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  130144. ** to true if EOF is reached.
  130145. */
  130146. static void fts3EvalDlPhraseNext(
  130147. Fts3Table *pTab,
  130148. Fts3Doclist *pDL,
  130149. u8 *pbEof
  130150. ){
  130151. char *pIter; /* Used to iterate through aAll */
  130152. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  130153. if( pDL->pNextDocid ){
  130154. pIter = pDL->pNextDocid;
  130155. }else{
  130156. pIter = pDL->aAll;
  130157. }
  130158. if( pIter>=pEnd ){
  130159. /* We have already reached the end of this doclist. EOF. */
  130160. *pbEof = 1;
  130161. }else{
  130162. sqlite3_int64 iDelta;
  130163. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  130164. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  130165. pDL->iDocid += iDelta;
  130166. }else{
  130167. pDL->iDocid -= iDelta;
  130168. }
  130169. pDL->pList = pIter;
  130170. fts3PoslistCopy(0, &pIter);
  130171. pDL->nList = (int)(pIter - pDL->pList);
  130172. /* pIter now points just past the 0x00 that terminates the position-
  130173. ** list for document pDL->iDocid. However, if this position-list was
  130174. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  130175. ** point to the start of the next docid value. The following line deals
  130176. ** with this case by advancing pIter past the zero-padding added by
  130177. ** fts3EvalNearTrim(). */
  130178. while( pIter<pEnd && *pIter==0 ) pIter++;
  130179. pDL->pNextDocid = pIter;
  130180. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  130181. *pbEof = 0;
  130182. }
  130183. }
  130184. /*
  130185. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  130186. */
  130187. typedef struct TokenDoclist TokenDoclist;
  130188. struct TokenDoclist {
  130189. int bIgnore;
  130190. sqlite3_int64 iDocid;
  130191. char *pList;
  130192. int nList;
  130193. };
  130194. /*
  130195. ** Token pToken is an incrementally loaded token that is part of a
  130196. ** multi-token phrase. Advance it to the next matching document in the
  130197. ** database and populate output variable *p with the details of the new
  130198. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  130199. **
  130200. ** If an error occurs, return an SQLite error code. Otherwise, return
  130201. ** SQLITE_OK.
  130202. */
  130203. static int incrPhraseTokenNext(
  130204. Fts3Table *pTab, /* Virtual table handle */
  130205. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  130206. int iToken, /* Specific token to advance */
  130207. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  130208. u8 *pbEof /* OUT: True if iterator is at EOF */
  130209. ){
  130210. int rc = SQLITE_OK;
  130211. if( pPhrase->iDoclistToken==iToken ){
  130212. assert( p->bIgnore==0 );
  130213. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  130214. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  130215. p->pList = pPhrase->doclist.pList;
  130216. p->nList = pPhrase->doclist.nList;
  130217. p->iDocid = pPhrase->doclist.iDocid;
  130218. }else{
  130219. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  130220. assert( pToken->pDeferred==0 );
  130221. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  130222. if( pToken->pSegcsr ){
  130223. assert( p->bIgnore==0 );
  130224. rc = sqlite3Fts3MsrIncrNext(
  130225. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  130226. );
  130227. if( p->pList==0 ) *pbEof = 1;
  130228. }else{
  130229. p->bIgnore = 1;
  130230. }
  130231. }
  130232. return rc;
  130233. }
  130234. /*
  130235. ** The phrase iterator passed as the second argument:
  130236. **
  130237. ** * features at least one token that uses an incremental doclist, and
  130238. **
  130239. ** * does not contain any deferred tokens.
  130240. **
  130241. ** Advance it to the next matching documnent in the database and populate
  130242. ** the Fts3Doclist.pList and nList fields.
  130243. **
  130244. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  130245. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  130246. ** successfully advanced, *pbEof is set to 0.
  130247. **
  130248. ** If an error occurs, return an SQLite error code. Otherwise, return
  130249. ** SQLITE_OK.
  130250. */
  130251. static int fts3EvalIncrPhraseNext(
  130252. Fts3Cursor *pCsr, /* FTS Cursor handle */
  130253. Fts3Phrase *p, /* Phrase object to advance to next docid */
  130254. u8 *pbEof /* OUT: Set to 1 if EOF */
  130255. ){
  130256. int rc = SQLITE_OK;
  130257. Fts3Doclist *pDL = &p->doclist;
  130258. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  130259. u8 bEof = 0;
  130260. /* This is only called if it is guaranteed that the phrase has at least
  130261. ** one incremental token. In which case the bIncr flag is set. */
  130262. assert( p->bIncr==1 );
  130263. if( p->nToken==1 && p->bIncr ){
  130264. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  130265. &pDL->iDocid, &pDL->pList, &pDL->nList
  130266. );
  130267. if( pDL->pList==0 ) bEof = 1;
  130268. }else{
  130269. int bDescDoclist = pCsr->bDesc;
  130270. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  130271. memset(a, 0, sizeof(a));
  130272. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  130273. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  130274. while( bEof==0 ){
  130275. int bMaxSet = 0;
  130276. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  130277. int i; /* Used to iterate through tokens */
  130278. /* Advance the iterator for each token in the phrase once. */
  130279. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  130280. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  130281. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  130282. iMax = a[i].iDocid;
  130283. bMaxSet = 1;
  130284. }
  130285. }
  130286. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  130287. assert( rc!=SQLITE_OK || bMaxSet );
  130288. /* Keep advancing iterators until they all point to the same document */
  130289. for(i=0; i<p->nToken; i++){
  130290. while( rc==SQLITE_OK && bEof==0
  130291. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  130292. ){
  130293. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  130294. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  130295. iMax = a[i].iDocid;
  130296. i = 0;
  130297. }
  130298. }
  130299. }
  130300. /* Check if the current entries really are a phrase match */
  130301. if( bEof==0 ){
  130302. int nList = 0;
  130303. int nByte = a[p->nToken-1].nList;
  130304. char *aDoclist = sqlite3_malloc(nByte+1);
  130305. if( !aDoclist ) return SQLITE_NOMEM;
  130306. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  130307. for(i=0; i<(p->nToken-1); i++){
  130308. if( a[i].bIgnore==0 ){
  130309. char *pL = a[i].pList;
  130310. char *pR = aDoclist;
  130311. char *pOut = aDoclist;
  130312. int nDist = p->nToken-1-i;
  130313. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  130314. if( res==0 ) break;
  130315. nList = (int)(pOut - aDoclist);
  130316. }
  130317. }
  130318. if( i==(p->nToken-1) ){
  130319. pDL->iDocid = iMax;
  130320. pDL->pList = aDoclist;
  130321. pDL->nList = nList;
  130322. pDL->bFreeList = 1;
  130323. break;
  130324. }
  130325. sqlite3_free(aDoclist);
  130326. }
  130327. }
  130328. }
  130329. *pbEof = bEof;
  130330. return rc;
  130331. }
  130332. /*
  130333. ** Attempt to move the phrase iterator to point to the next matching docid.
  130334. ** If an error occurs, return an SQLite error code. Otherwise, return
  130335. ** SQLITE_OK.
  130336. **
  130337. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  130338. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  130339. ** successfully advanced, *pbEof is set to 0.
  130340. */
  130341. static int fts3EvalPhraseNext(
  130342. Fts3Cursor *pCsr, /* FTS Cursor handle */
  130343. Fts3Phrase *p, /* Phrase object to advance to next docid */
  130344. u8 *pbEof /* OUT: Set to 1 if EOF */
  130345. ){
  130346. int rc = SQLITE_OK;
  130347. Fts3Doclist *pDL = &p->doclist;
  130348. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  130349. if( p->bIncr ){
  130350. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  130351. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  130352. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  130353. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  130354. );
  130355. pDL->pList = pDL->pNextDocid;
  130356. }else{
  130357. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  130358. }
  130359. return rc;
  130360. }
  130361. /*
  130362. **
  130363. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  130364. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  130365. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  130366. ** expressions for which all descendent tokens are deferred.
  130367. **
  130368. ** If parameter bOptOk is zero, then it is guaranteed that the
  130369. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  130370. ** each phrase in the expression (subject to deferred token processing).
  130371. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  130372. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  130373. **
  130374. ** If an error occurs within this function, *pRc is set to an SQLite error
  130375. ** code before returning.
  130376. */
  130377. static void fts3EvalStartReaders(
  130378. Fts3Cursor *pCsr, /* FTS Cursor handle */
  130379. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  130380. int *pRc /* IN/OUT: Error code */
  130381. ){
  130382. if( pExpr && SQLITE_OK==*pRc ){
  130383. if( pExpr->eType==FTSQUERY_PHRASE ){
  130384. int nToken = pExpr->pPhrase->nToken;
  130385. if( nToken ){
  130386. int i;
  130387. for(i=0; i<nToken; i++){
  130388. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  130389. }
  130390. pExpr->bDeferred = (i==nToken);
  130391. }
  130392. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  130393. }else{
  130394. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  130395. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  130396. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  130397. }
  130398. }
  130399. }
  130400. /*
  130401. ** An array of the following structures is assembled as part of the process
  130402. ** of selecting tokens to defer before the query starts executing (as part
  130403. ** of the xFilter() method). There is one element in the array for each
  130404. ** token in the FTS expression.
  130405. **
  130406. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  130407. ** to phrases that are connected only by AND and NEAR operators (not OR or
  130408. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  130409. ** separately. The root of a tokens AND/NEAR cluster is stored in
  130410. ** Fts3TokenAndCost.pRoot.
  130411. */
  130412. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  130413. struct Fts3TokenAndCost {
  130414. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  130415. int iToken; /* Position of token in phrase */
  130416. Fts3PhraseToken *pToken; /* The token itself */
  130417. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  130418. int nOvfl; /* Number of overflow pages to load doclist */
  130419. int iCol; /* The column the token must match */
  130420. };
  130421. /*
  130422. ** This function is used to populate an allocated Fts3TokenAndCost array.
  130423. **
  130424. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  130425. ** Otherwise, if an error occurs during execution, *pRc is set to an
  130426. ** SQLite error code.
  130427. */
  130428. static void fts3EvalTokenCosts(
  130429. Fts3Cursor *pCsr, /* FTS Cursor handle */
  130430. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  130431. Fts3Expr *pExpr, /* Expression to consider */
  130432. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  130433. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  130434. int *pRc /* IN/OUT: Error code */
  130435. ){
  130436. if( *pRc==SQLITE_OK ){
  130437. if( pExpr->eType==FTSQUERY_PHRASE ){
  130438. Fts3Phrase *pPhrase = pExpr->pPhrase;
  130439. int i;
  130440. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  130441. Fts3TokenAndCost *pTC = (*ppTC)++;
  130442. pTC->pPhrase = pPhrase;
  130443. pTC->iToken = i;
  130444. pTC->pRoot = pRoot;
  130445. pTC->pToken = &pPhrase->aToken[i];
  130446. pTC->iCol = pPhrase->iColumn;
  130447. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  130448. }
  130449. }else if( pExpr->eType!=FTSQUERY_NOT ){
  130450. assert( pExpr->eType==FTSQUERY_OR
  130451. || pExpr->eType==FTSQUERY_AND
  130452. || pExpr->eType==FTSQUERY_NEAR
  130453. );
  130454. assert( pExpr->pLeft && pExpr->pRight );
  130455. if( pExpr->eType==FTSQUERY_OR ){
  130456. pRoot = pExpr->pLeft;
  130457. **ppOr = pRoot;
  130458. (*ppOr)++;
  130459. }
  130460. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  130461. if( pExpr->eType==FTSQUERY_OR ){
  130462. pRoot = pExpr->pRight;
  130463. **ppOr = pRoot;
  130464. (*ppOr)++;
  130465. }
  130466. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  130467. }
  130468. }
  130469. }
  130470. /*
  130471. ** Determine the average document (row) size in pages. If successful,
  130472. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  130473. ** an SQLite error code.
  130474. **
  130475. ** The average document size in pages is calculated by first calculating
  130476. ** determining the average size in bytes, B. If B is less than the amount
  130477. ** of data that will fit on a single leaf page of an intkey table in
  130478. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  130479. ** the number of overflow pages consumed by a record B bytes in size.
  130480. */
  130481. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  130482. if( pCsr->nRowAvg==0 ){
  130483. /* The average document size, which is required to calculate the cost
  130484. ** of each doclist, has not yet been determined. Read the required
  130485. ** data from the %_stat table to calculate it.
  130486. **
  130487. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  130488. ** varints, where nCol is the number of columns in the FTS3 table.
  130489. ** The first varint is the number of documents currently stored in
  130490. ** the table. The following nCol varints contain the total amount of
  130491. ** data stored in all rows of each column of the table, from left
  130492. ** to right.
  130493. */
  130494. int rc;
  130495. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  130496. sqlite3_stmt *pStmt;
  130497. sqlite3_int64 nDoc = 0;
  130498. sqlite3_int64 nByte = 0;
  130499. const char *pEnd;
  130500. const char *a;
  130501. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  130502. if( rc!=SQLITE_OK ) return rc;
  130503. a = sqlite3_column_blob(pStmt, 0);
  130504. assert( a );
  130505. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  130506. a += sqlite3Fts3GetVarint(a, &nDoc);
  130507. while( a<pEnd ){
  130508. a += sqlite3Fts3GetVarint(a, &nByte);
  130509. }
  130510. if( nDoc==0 || nByte==0 ){
  130511. sqlite3_reset(pStmt);
  130512. return FTS_CORRUPT_VTAB;
  130513. }
  130514. pCsr->nDoc = nDoc;
  130515. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  130516. assert( pCsr->nRowAvg>0 );
  130517. rc = sqlite3_reset(pStmt);
  130518. if( rc!=SQLITE_OK ) return rc;
  130519. }
  130520. *pnPage = pCsr->nRowAvg;
  130521. return SQLITE_OK;
  130522. }
  130523. /*
  130524. ** This function is called to select the tokens (if any) that will be
  130525. ** deferred. The array aTC[] has already been populated when this is
  130526. ** called.
  130527. **
  130528. ** This function is called once for each AND/NEAR cluster in the
  130529. ** expression. Each invocation determines which tokens to defer within
  130530. ** the cluster with root node pRoot. See comments above the definition
  130531. ** of struct Fts3TokenAndCost for more details.
  130532. **
  130533. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  130534. ** called on each token to defer. Otherwise, an SQLite error code is
  130535. ** returned.
  130536. */
  130537. static int fts3EvalSelectDeferred(
  130538. Fts3Cursor *pCsr, /* FTS Cursor handle */
  130539. Fts3Expr *pRoot, /* Consider tokens with this root node */
  130540. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  130541. int nTC /* Number of entries in aTC[] */
  130542. ){
  130543. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  130544. int nDocSize = 0; /* Number of pages per doc loaded */
  130545. int rc = SQLITE_OK; /* Return code */
  130546. int ii; /* Iterator variable for various purposes */
  130547. int nOvfl = 0; /* Total overflow pages used by doclists */
  130548. int nToken = 0; /* Total number of tokens in cluster */
  130549. int nMinEst = 0; /* The minimum count for any phrase so far. */
  130550. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  130551. /* Tokens are never deferred for FTS tables created using the content=xxx
  130552. ** option. The reason being that it is not guaranteed that the content
  130553. ** table actually contains the same data as the index. To prevent this from
  130554. ** causing any problems, the deferred token optimization is completely
  130555. ** disabled for content=xxx tables. */
  130556. if( pTab->zContentTbl ){
  130557. return SQLITE_OK;
  130558. }
  130559. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  130560. ** associated with the tokens spill onto overflow pages, or if there is
  130561. ** only 1 token, exit early. No tokens to defer in this case. */
  130562. for(ii=0; ii<nTC; ii++){
  130563. if( aTC[ii].pRoot==pRoot ){
  130564. nOvfl += aTC[ii].nOvfl;
  130565. nToken++;
  130566. }
  130567. }
  130568. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  130569. /* Obtain the average docsize (in pages). */
  130570. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  130571. assert( rc!=SQLITE_OK || nDocSize>0 );
  130572. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  130573. ** of the number of overflow pages that will be loaded by the pager layer
  130574. ** to retrieve the entire doclist for the token from the full-text index.
  130575. ** Load the doclists for tokens that are either:
  130576. **
  130577. ** a. The cheapest token in the entire query (i.e. the one visited by the
  130578. ** first iteration of this loop), or
  130579. **
  130580. ** b. Part of a multi-token phrase.
  130581. **
  130582. ** After each token doclist is loaded, merge it with the others from the
  130583. ** same phrase and count the number of documents that the merged doclist
  130584. ** contains. Set variable "nMinEst" to the smallest number of documents in
  130585. ** any phrase doclist for which 1 or more token doclists have been loaded.
  130586. ** Let nOther be the number of other phrases for which it is certain that
  130587. ** one or more tokens will not be deferred.
  130588. **
  130589. ** Then, for each token, defer it if loading the doclist would result in
  130590. ** loading N or more overflow pages into memory, where N is computed as:
  130591. **
  130592. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  130593. */
  130594. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  130595. int iTC; /* Used to iterate through aTC[] array. */
  130596. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  130597. /* Set pTC to point to the cheapest remaining token. */
  130598. for(iTC=0; iTC<nTC; iTC++){
  130599. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  130600. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  130601. ){
  130602. pTC = &aTC[iTC];
  130603. }
  130604. }
  130605. assert( pTC );
  130606. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  130607. /* The number of overflow pages to load for this (and therefore all
  130608. ** subsequent) tokens is greater than the estimated number of pages
  130609. ** that will be loaded if all subsequent tokens are deferred.
  130610. */
  130611. Fts3PhraseToken *pToken = pTC->pToken;
  130612. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  130613. fts3SegReaderCursorFree(pToken->pSegcsr);
  130614. pToken->pSegcsr = 0;
  130615. }else{
  130616. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  130617. ** for-loop. Except, limit the value to 2^24 to prevent it from
  130618. ** overflowing the 32-bit integer it is stored in. */
  130619. if( ii<12 ) nLoad4 = nLoad4*4;
  130620. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  130621. /* Either this is the cheapest token in the entire query, or it is
  130622. ** part of a multi-token phrase. Either way, the entire doclist will
  130623. ** (eventually) be loaded into memory. It may as well be now. */
  130624. Fts3PhraseToken *pToken = pTC->pToken;
  130625. int nList = 0;
  130626. char *pList = 0;
  130627. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  130628. assert( rc==SQLITE_OK || pList==0 );
  130629. if( rc==SQLITE_OK ){
  130630. rc = fts3EvalPhraseMergeToken(
  130631. pTab, pTC->pPhrase, pTC->iToken,pList,nList
  130632. );
  130633. }
  130634. if( rc==SQLITE_OK ){
  130635. int nCount;
  130636. nCount = fts3DoclistCountDocids(
  130637. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  130638. );
  130639. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  130640. }
  130641. }
  130642. }
  130643. pTC->pToken = 0;
  130644. }
  130645. return rc;
  130646. }
  130647. /*
  130648. ** This function is called from within the xFilter method. It initializes
  130649. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  130650. ** the results of a query, the caller does:
  130651. **
  130652. ** fts3EvalStart(pCsr);
  130653. ** while( 1 ){
  130654. ** fts3EvalNext(pCsr);
  130655. ** if( pCsr->bEof ) break;
  130656. ** ... return row pCsr->iPrevId to the caller ...
  130657. ** }
  130658. */
  130659. static int fts3EvalStart(Fts3Cursor *pCsr){
  130660. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  130661. int rc = SQLITE_OK;
  130662. int nToken = 0;
  130663. int nOr = 0;
  130664. /* Allocate a MultiSegReader for each token in the expression. */
  130665. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  130666. /* Determine which, if any, tokens in the expression should be deferred. */
  130667. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  130668. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  130669. Fts3TokenAndCost *aTC;
  130670. Fts3Expr **apOr;
  130671. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  130672. sizeof(Fts3TokenAndCost) * nToken
  130673. + sizeof(Fts3Expr *) * nOr * 2
  130674. );
  130675. apOr = (Fts3Expr **)&aTC[nToken];
  130676. if( !aTC ){
  130677. rc = SQLITE_NOMEM;
  130678. }else{
  130679. int ii;
  130680. Fts3TokenAndCost *pTC = aTC;
  130681. Fts3Expr **ppOr = apOr;
  130682. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  130683. nToken = (int)(pTC-aTC);
  130684. nOr = (int)(ppOr-apOr);
  130685. if( rc==SQLITE_OK ){
  130686. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  130687. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  130688. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  130689. }
  130690. }
  130691. sqlite3_free(aTC);
  130692. }
  130693. }
  130694. #endif
  130695. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  130696. return rc;
  130697. }
  130698. /*
  130699. ** Invalidate the current position list for phrase pPhrase.
  130700. */
  130701. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  130702. if( pPhrase->doclist.bFreeList ){
  130703. sqlite3_free(pPhrase->doclist.pList);
  130704. }
  130705. pPhrase->doclist.pList = 0;
  130706. pPhrase->doclist.nList = 0;
  130707. pPhrase->doclist.bFreeList = 0;
  130708. }
  130709. /*
  130710. ** This function is called to edit the position list associated with
  130711. ** the phrase object passed as the fifth argument according to a NEAR
  130712. ** condition. For example:
  130713. **
  130714. ** abc NEAR/5 "def ghi"
  130715. **
  130716. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  130717. ** the example above). When this function is called, *paPoslist points to
  130718. ** the position list, and *pnToken is the number of phrase tokens in, the
  130719. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  130720. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  130721. ** the position list associated with phrase "abc".
  130722. **
  130723. ** All positions in the pPhrase position list that are not sufficiently
  130724. ** close to a position in the *paPoslist position list are removed. If this
  130725. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  130726. **
  130727. ** Before returning, *paPoslist is set to point to the position lsit
  130728. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  130729. ** pPhrase.
  130730. */
  130731. static int fts3EvalNearTrim(
  130732. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  130733. char *aTmp, /* Temporary space to use */
  130734. char **paPoslist, /* IN/OUT: Position list */
  130735. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  130736. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  130737. ){
  130738. int nParam1 = nNear + pPhrase->nToken;
  130739. int nParam2 = nNear + *pnToken;
  130740. int nNew;
  130741. char *p2;
  130742. char *pOut;
  130743. int res;
  130744. assert( pPhrase->doclist.pList );
  130745. p2 = pOut = pPhrase->doclist.pList;
  130746. res = fts3PoslistNearMerge(
  130747. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  130748. );
  130749. if( res ){
  130750. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  130751. assert( pPhrase->doclist.pList[nNew]=='\0' );
  130752. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  130753. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  130754. pPhrase->doclist.nList = nNew;
  130755. *paPoslist = pPhrase->doclist.pList;
  130756. *pnToken = pPhrase->nToken;
  130757. }
  130758. return res;
  130759. }
  130760. /*
  130761. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  130762. ** Otherwise, it advances the expression passed as the second argument to
  130763. ** point to the next matching row in the database. Expressions iterate through
  130764. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  130765. ** or descending if it is non-zero.
  130766. **
  130767. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  130768. ** successful, the following variables in pExpr are set:
  130769. **
  130770. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  130771. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  130772. **
  130773. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  130774. ** at EOF, then the following variables are populated with the position list
  130775. ** for the phrase for the visited row:
  130776. **
  130777. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  130778. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  130779. **
  130780. ** It says above that this function advances the expression to the next
  130781. ** matching row. This is usually true, but there are the following exceptions:
  130782. **
  130783. ** 1. Deferred tokens are not taken into account. If a phrase consists
  130784. ** entirely of deferred tokens, it is assumed to match every row in
  130785. ** the db. In this case the position-list is not populated at all.
  130786. **
  130787. ** Or, if a phrase contains one or more deferred tokens and one or
  130788. ** more non-deferred tokens, then the expression is advanced to the
  130789. ** next possible match, considering only non-deferred tokens. In other
  130790. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  130791. ** is advanced to the next row that contains an instance of "A * C",
  130792. ** where "*" may match any single token. The position list in this case
  130793. ** is populated as for "A * C" before returning.
  130794. **
  130795. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  130796. ** advanced to point to the next row that matches "x AND y".
  130797. **
  130798. ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
  130799. ** really a match, taking into account deferred tokens and NEAR operators.
  130800. */
  130801. static void fts3EvalNextRow(
  130802. Fts3Cursor *pCsr, /* FTS Cursor handle */
  130803. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  130804. int *pRc /* IN/OUT: Error code */
  130805. ){
  130806. if( *pRc==SQLITE_OK ){
  130807. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  130808. assert( pExpr->bEof==0 );
  130809. pExpr->bStart = 1;
  130810. switch( pExpr->eType ){
  130811. case FTSQUERY_NEAR:
  130812. case FTSQUERY_AND: {
  130813. Fts3Expr *pLeft = pExpr->pLeft;
  130814. Fts3Expr *pRight = pExpr->pRight;
  130815. assert( !pLeft->bDeferred || !pRight->bDeferred );
  130816. if( pLeft->bDeferred ){
  130817. /* LHS is entirely deferred. So we assume it matches every row.
  130818. ** Advance the RHS iterator to find the next row visited. */
  130819. fts3EvalNextRow(pCsr, pRight, pRc);
  130820. pExpr->iDocid = pRight->iDocid;
  130821. pExpr->bEof = pRight->bEof;
  130822. }else if( pRight->bDeferred ){
  130823. /* RHS is entirely deferred. So we assume it matches every row.
  130824. ** Advance the LHS iterator to find the next row visited. */
  130825. fts3EvalNextRow(pCsr, pLeft, pRc);
  130826. pExpr->iDocid = pLeft->iDocid;
  130827. pExpr->bEof = pLeft->bEof;
  130828. }else{
  130829. /* Neither the RHS or LHS are deferred. */
  130830. fts3EvalNextRow(pCsr, pLeft, pRc);
  130831. fts3EvalNextRow(pCsr, pRight, pRc);
  130832. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  130833. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  130834. if( iDiff==0 ) break;
  130835. if( iDiff<0 ){
  130836. fts3EvalNextRow(pCsr, pLeft, pRc);
  130837. }else{
  130838. fts3EvalNextRow(pCsr, pRight, pRc);
  130839. }
  130840. }
  130841. pExpr->iDocid = pLeft->iDocid;
  130842. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  130843. if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
  130844. if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
  130845. Fts3Doclist *pDl = &pRight->pPhrase->doclist;
  130846. while( *pRc==SQLITE_OK && pRight->bEof==0 ){
  130847. memset(pDl->pList, 0, pDl->nList);
  130848. fts3EvalNextRow(pCsr, pRight, pRc);
  130849. }
  130850. }
  130851. if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
  130852. Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
  130853. while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
  130854. memset(pDl->pList, 0, pDl->nList);
  130855. fts3EvalNextRow(pCsr, pLeft, pRc);
  130856. }
  130857. }
  130858. }
  130859. }
  130860. break;
  130861. }
  130862. case FTSQUERY_OR: {
  130863. Fts3Expr *pLeft = pExpr->pLeft;
  130864. Fts3Expr *pRight = pExpr->pRight;
  130865. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  130866. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  130867. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  130868. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  130869. fts3EvalNextRow(pCsr, pLeft, pRc);
  130870. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  130871. fts3EvalNextRow(pCsr, pRight, pRc);
  130872. }else{
  130873. fts3EvalNextRow(pCsr, pLeft, pRc);
  130874. fts3EvalNextRow(pCsr, pRight, pRc);
  130875. }
  130876. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  130877. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  130878. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  130879. pExpr->iDocid = pLeft->iDocid;
  130880. }else{
  130881. pExpr->iDocid = pRight->iDocid;
  130882. }
  130883. break;
  130884. }
  130885. case FTSQUERY_NOT: {
  130886. Fts3Expr *pLeft = pExpr->pLeft;
  130887. Fts3Expr *pRight = pExpr->pRight;
  130888. if( pRight->bStart==0 ){
  130889. fts3EvalNextRow(pCsr, pRight, pRc);
  130890. assert( *pRc!=SQLITE_OK || pRight->bStart );
  130891. }
  130892. fts3EvalNextRow(pCsr, pLeft, pRc);
  130893. if( pLeft->bEof==0 ){
  130894. while( !*pRc
  130895. && !pRight->bEof
  130896. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  130897. ){
  130898. fts3EvalNextRow(pCsr, pRight, pRc);
  130899. }
  130900. }
  130901. pExpr->iDocid = pLeft->iDocid;
  130902. pExpr->bEof = pLeft->bEof;
  130903. break;
  130904. }
  130905. default: {
  130906. Fts3Phrase *pPhrase = pExpr->pPhrase;
  130907. fts3EvalInvalidatePoslist(pPhrase);
  130908. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  130909. pExpr->iDocid = pPhrase->doclist.iDocid;
  130910. break;
  130911. }
  130912. }
  130913. }
  130914. }
  130915. /*
  130916. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  130917. ** cluster, then this function returns 1 immediately.
  130918. **
  130919. ** Otherwise, it checks if the current row really does match the NEAR
  130920. ** expression, using the data currently stored in the position lists
  130921. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  130922. **
  130923. ** If the current row is a match, the position list associated with each
  130924. ** phrase in the NEAR expression is edited in place to contain only those
  130925. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  130926. ** constraints. In this case it returns 1. If the NEAR expression does not
  130927. ** match the current row, 0 is returned. The position lists may or may not
  130928. ** be edited if 0 is returned.
  130929. */
  130930. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  130931. int res = 1;
  130932. /* The following block runs if pExpr is the root of a NEAR query.
  130933. ** For example, the query:
  130934. **
  130935. ** "w" NEAR "x" NEAR "y" NEAR "z"
  130936. **
  130937. ** which is represented in tree form as:
  130938. **
  130939. ** |
  130940. ** +--NEAR--+ <-- root of NEAR query
  130941. ** | |
  130942. ** +--NEAR--+ "z"
  130943. ** | |
  130944. ** +--NEAR--+ "y"
  130945. ** | |
  130946. ** "w" "x"
  130947. **
  130948. ** The right-hand child of a NEAR node is always a phrase. The
  130949. ** left-hand child may be either a phrase or a NEAR node. There are
  130950. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  130951. */
  130952. if( *pRc==SQLITE_OK
  130953. && pExpr->eType==FTSQUERY_NEAR
  130954. && pExpr->bEof==0
  130955. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  130956. ){
  130957. Fts3Expr *p;
  130958. int nTmp = 0; /* Bytes of temp space */
  130959. char *aTmp; /* Temp space for PoslistNearMerge() */
  130960. /* Allocate temporary working space. */
  130961. for(p=pExpr; p->pLeft; p=p->pLeft){
  130962. nTmp += p->pRight->pPhrase->doclist.nList;
  130963. }
  130964. nTmp += p->pPhrase->doclist.nList;
  130965. if( nTmp==0 ){
  130966. res = 0;
  130967. }else{
  130968. aTmp = sqlite3_malloc(nTmp*2);
  130969. if( !aTmp ){
  130970. *pRc = SQLITE_NOMEM;
  130971. res = 0;
  130972. }else{
  130973. char *aPoslist = p->pPhrase->doclist.pList;
  130974. int nToken = p->pPhrase->nToken;
  130975. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  130976. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  130977. int nNear = p->nNear;
  130978. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  130979. }
  130980. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  130981. nToken = pExpr->pRight->pPhrase->nToken;
  130982. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  130983. int nNear;
  130984. Fts3Phrase *pPhrase;
  130985. assert( p->pParent && p->pParent->pLeft==p );
  130986. nNear = p->pParent->nNear;
  130987. pPhrase = (
  130988. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  130989. );
  130990. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  130991. }
  130992. }
  130993. sqlite3_free(aTmp);
  130994. }
  130995. }
  130996. return res;
  130997. }
  130998. /*
  130999. ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
  131000. ** Assuming no error occurs or has occurred, It returns non-zero if the
  131001. ** expression passed as the second argument matches the row that pCsr
  131002. ** currently points to, or zero if it does not.
  131003. **
  131004. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  131005. ** If an error occurs during execution of this function, *pRc is set to
  131006. ** the appropriate SQLite error code. In this case the returned value is
  131007. ** undefined.
  131008. */
  131009. static int fts3EvalTestExpr(
  131010. Fts3Cursor *pCsr, /* FTS cursor handle */
  131011. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  131012. int *pRc /* IN/OUT: Error code */
  131013. ){
  131014. int bHit = 1; /* Return value */
  131015. if( *pRc==SQLITE_OK ){
  131016. switch( pExpr->eType ){
  131017. case FTSQUERY_NEAR:
  131018. case FTSQUERY_AND:
  131019. bHit = (
  131020. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  131021. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  131022. && fts3EvalNearTest(pExpr, pRc)
  131023. );
  131024. /* If the NEAR expression does not match any rows, zero the doclist for
  131025. ** all phrases involved in the NEAR. This is because the snippet(),
  131026. ** offsets() and matchinfo() functions are not supposed to recognize
  131027. ** any instances of phrases that are part of unmatched NEAR queries.
  131028. ** For example if this expression:
  131029. **
  131030. ** ... MATCH 'a OR (b NEAR c)'
  131031. **
  131032. ** is matched against a row containing:
  131033. **
  131034. ** 'a b d e'
  131035. **
  131036. ** then any snippet() should ony highlight the "a" term, not the "b"
  131037. ** (as "b" is part of a non-matching NEAR clause).
  131038. */
  131039. if( bHit==0
  131040. && pExpr->eType==FTSQUERY_NEAR
  131041. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  131042. ){
  131043. Fts3Expr *p;
  131044. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  131045. if( p->pRight->iDocid==pCsr->iPrevId ){
  131046. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  131047. }
  131048. }
  131049. if( p->iDocid==pCsr->iPrevId ){
  131050. fts3EvalInvalidatePoslist(p->pPhrase);
  131051. }
  131052. }
  131053. break;
  131054. case FTSQUERY_OR: {
  131055. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  131056. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  131057. bHit = bHit1 || bHit2;
  131058. break;
  131059. }
  131060. case FTSQUERY_NOT:
  131061. bHit = (
  131062. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  131063. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  131064. );
  131065. break;
  131066. default: {
  131067. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  131068. if( pCsr->pDeferred
  131069. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  131070. ){
  131071. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131072. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  131073. if( pExpr->bDeferred ){
  131074. fts3EvalInvalidatePoslist(pPhrase);
  131075. }
  131076. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  131077. bHit = (pPhrase->doclist.pList!=0);
  131078. pExpr->iDocid = pCsr->iPrevId;
  131079. }else
  131080. #endif
  131081. {
  131082. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  131083. }
  131084. break;
  131085. }
  131086. }
  131087. }
  131088. return bHit;
  131089. }
  131090. /*
  131091. ** This function is called as the second part of each xNext operation when
  131092. ** iterating through the results of a full-text query. At this point the
  131093. ** cursor points to a row that matches the query expression, with the
  131094. ** following caveats:
  131095. **
  131096. ** * Up until this point, "NEAR" operators in the expression have been
  131097. ** treated as "AND".
  131098. **
  131099. ** * Deferred tokens have not yet been considered.
  131100. **
  131101. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  131102. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  131103. ** operators and deferred tokens the current row is still a match for the
  131104. ** expression. It returns 1 if both of the following are true:
  131105. **
  131106. ** 1. *pRc is SQLITE_OK when this function returns, and
  131107. **
  131108. ** 2. After scanning the current FTS table row for the deferred tokens,
  131109. ** it is determined that the row does *not* match the query.
  131110. **
  131111. ** Or, if no error occurs and it seems the current row does match the FTS
  131112. ** query, return 0.
  131113. */
  131114. SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
  131115. int rc = *pRc;
  131116. int bMiss = 0;
  131117. if( rc==SQLITE_OK ){
  131118. /* If there are one or more deferred tokens, load the current row into
  131119. ** memory and scan it to determine the position list for each deferred
  131120. ** token. Then, see if this row is really a match, considering deferred
  131121. ** tokens and NEAR operators (neither of which were taken into account
  131122. ** earlier, by fts3EvalNextRow()).
  131123. */
  131124. if( pCsr->pDeferred ){
  131125. rc = fts3CursorSeek(0, pCsr);
  131126. if( rc==SQLITE_OK ){
  131127. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  131128. }
  131129. }
  131130. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  131131. /* Free the position-lists accumulated for each deferred token above. */
  131132. sqlite3Fts3FreeDeferredDoclists(pCsr);
  131133. *pRc = rc;
  131134. }
  131135. return (rc==SQLITE_OK && bMiss);
  131136. }
  131137. /*
  131138. ** Advance to the next document that matches the FTS expression in
  131139. ** Fts3Cursor.pExpr.
  131140. */
  131141. static int fts3EvalNext(Fts3Cursor *pCsr){
  131142. int rc = SQLITE_OK; /* Return Code */
  131143. Fts3Expr *pExpr = pCsr->pExpr;
  131144. assert( pCsr->isEof==0 );
  131145. if( pExpr==0 ){
  131146. pCsr->isEof = 1;
  131147. }else{
  131148. do {
  131149. if( pCsr->isRequireSeek==0 ){
  131150. sqlite3_reset(pCsr->pStmt);
  131151. }
  131152. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  131153. fts3EvalNextRow(pCsr, pExpr, &rc);
  131154. pCsr->isEof = pExpr->bEof;
  131155. pCsr->isRequireSeek = 1;
  131156. pCsr->isMatchinfoNeeded = 1;
  131157. pCsr->iPrevId = pExpr->iDocid;
  131158. }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
  131159. }
  131160. /* Check if the cursor is past the end of the docid range specified
  131161. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  131162. if( rc==SQLITE_OK && (
  131163. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  131164. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  131165. )){
  131166. pCsr->isEof = 1;
  131167. }
  131168. return rc;
  131169. }
  131170. /*
  131171. ** Restart interation for expression pExpr so that the next call to
  131172. ** fts3EvalNext() visits the first row. Do not allow incremental
  131173. ** loading or merging of phrase doclists for this iteration.
  131174. **
  131175. ** If *pRc is other than SQLITE_OK when this function is called, it is
  131176. ** a no-op. If an error occurs within this function, *pRc is set to an
  131177. ** SQLite error code before returning.
  131178. */
  131179. static void fts3EvalRestart(
  131180. Fts3Cursor *pCsr,
  131181. Fts3Expr *pExpr,
  131182. int *pRc
  131183. ){
  131184. if( pExpr && *pRc==SQLITE_OK ){
  131185. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131186. if( pPhrase ){
  131187. fts3EvalInvalidatePoslist(pPhrase);
  131188. if( pPhrase->bIncr ){
  131189. int i;
  131190. for(i=0; i<pPhrase->nToken; i++){
  131191. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  131192. assert( pToken->pDeferred==0 );
  131193. if( pToken->pSegcsr ){
  131194. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  131195. }
  131196. }
  131197. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  131198. }
  131199. pPhrase->doclist.pNextDocid = 0;
  131200. pPhrase->doclist.iDocid = 0;
  131201. pPhrase->pOrPoslist = 0;
  131202. }
  131203. pExpr->iDocid = 0;
  131204. pExpr->bEof = 0;
  131205. pExpr->bStart = 0;
  131206. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  131207. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  131208. }
  131209. }
  131210. /*
  131211. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  131212. ** expression rooted at pExpr, the cursor iterates through all rows matched
  131213. ** by pExpr, calling this function for each row. This function increments
  131214. ** the values in Fts3Expr.aMI[] according to the position-list currently
  131215. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  131216. ** expression nodes.
  131217. */
  131218. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  131219. if( pExpr ){
  131220. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131221. if( pPhrase && pPhrase->doclist.pList ){
  131222. int iCol = 0;
  131223. char *p = pPhrase->doclist.pList;
  131224. assert( *p );
  131225. while( 1 ){
  131226. u8 c = 0;
  131227. int iCnt = 0;
  131228. while( 0xFE & (*p | c) ){
  131229. if( (c&0x80)==0 ) iCnt++;
  131230. c = *p++ & 0x80;
  131231. }
  131232. /* aMI[iCol*3 + 1] = Number of occurrences
  131233. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  131234. */
  131235. pExpr->aMI[iCol*3 + 1] += iCnt;
  131236. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  131237. if( *p==0x00 ) break;
  131238. p++;
  131239. p += fts3GetVarint32(p, &iCol);
  131240. }
  131241. }
  131242. fts3EvalUpdateCounts(pExpr->pLeft);
  131243. fts3EvalUpdateCounts(pExpr->pRight);
  131244. }
  131245. }
  131246. /*
  131247. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  131248. **
  131249. ** If it is not already allocated and populated, this function allocates and
  131250. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  131251. ** of a NEAR expression, then it also allocates and populates the same array
  131252. ** for all other phrases that are part of the NEAR expression.
  131253. **
  131254. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  131255. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  131256. */
  131257. static int fts3EvalGatherStats(
  131258. Fts3Cursor *pCsr, /* Cursor object */
  131259. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  131260. ){
  131261. int rc = SQLITE_OK; /* Return code */
  131262. assert( pExpr->eType==FTSQUERY_PHRASE );
  131263. if( pExpr->aMI==0 ){
  131264. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131265. Fts3Expr *pRoot; /* Root of NEAR expression */
  131266. Fts3Expr *p; /* Iterator used for several purposes */
  131267. sqlite3_int64 iPrevId = pCsr->iPrevId;
  131268. sqlite3_int64 iDocid;
  131269. u8 bEof;
  131270. /* Find the root of the NEAR expression */
  131271. pRoot = pExpr;
  131272. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  131273. pRoot = pRoot->pParent;
  131274. }
  131275. iDocid = pRoot->iDocid;
  131276. bEof = pRoot->bEof;
  131277. assert( pRoot->bStart );
  131278. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  131279. for(p=pRoot; p; p=p->pLeft){
  131280. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  131281. assert( pE->aMI==0 );
  131282. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  131283. if( !pE->aMI ) return SQLITE_NOMEM;
  131284. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  131285. }
  131286. fts3EvalRestart(pCsr, pRoot, &rc);
  131287. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  131288. do {
  131289. /* Ensure the %_content statement is reset. */
  131290. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  131291. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  131292. /* Advance to the next document */
  131293. fts3EvalNextRow(pCsr, pRoot, &rc);
  131294. pCsr->isEof = pRoot->bEof;
  131295. pCsr->isRequireSeek = 1;
  131296. pCsr->isMatchinfoNeeded = 1;
  131297. pCsr->iPrevId = pRoot->iDocid;
  131298. }while( pCsr->isEof==0
  131299. && pRoot->eType==FTSQUERY_NEAR
  131300. && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
  131301. );
  131302. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  131303. fts3EvalUpdateCounts(pRoot);
  131304. }
  131305. }
  131306. pCsr->isEof = 0;
  131307. pCsr->iPrevId = iPrevId;
  131308. if( bEof ){
  131309. pRoot->bEof = bEof;
  131310. }else{
  131311. /* Caution: pRoot may iterate through docids in ascending or descending
  131312. ** order. For this reason, even though it seems more defensive, the
  131313. ** do loop can not be written:
  131314. **
  131315. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  131316. */
  131317. fts3EvalRestart(pCsr, pRoot, &rc);
  131318. do {
  131319. fts3EvalNextRow(pCsr, pRoot, &rc);
  131320. assert( pRoot->bEof==0 );
  131321. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  131322. }
  131323. }
  131324. return rc;
  131325. }
  131326. /*
  131327. ** This function is used by the matchinfo() module to query a phrase
  131328. ** expression node for the following information:
  131329. **
  131330. ** 1. The total number of occurrences of the phrase in each column of
  131331. ** the FTS table (considering all rows), and
  131332. **
  131333. ** 2. For each column, the number of rows in the table for which the
  131334. ** column contains at least one instance of the phrase.
  131335. **
  131336. ** If no error occurs, SQLITE_OK is returned and the values for each column
  131337. ** written into the array aiOut as follows:
  131338. **
  131339. ** aiOut[iCol*3 + 1] = Number of occurrences
  131340. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  131341. **
  131342. ** Caveats:
  131343. **
  131344. ** * If a phrase consists entirely of deferred tokens, then all output
  131345. ** values are set to the number of documents in the table. In other
  131346. ** words we assume that very common tokens occur exactly once in each
  131347. ** column of each row of the table.
  131348. **
  131349. ** * If a phrase contains some deferred tokens (and some non-deferred
  131350. ** tokens), count the potential occurrence identified by considering
  131351. ** the non-deferred tokens instead of actual phrase occurrences.
  131352. **
  131353. ** * If the phrase is part of a NEAR expression, then only phrase instances
  131354. ** that meet the NEAR constraint are included in the counts.
  131355. */
  131356. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  131357. Fts3Cursor *pCsr, /* FTS cursor handle */
  131358. Fts3Expr *pExpr, /* Phrase expression */
  131359. u32 *aiOut /* Array to write results into (see above) */
  131360. ){
  131361. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131362. int rc = SQLITE_OK;
  131363. int iCol;
  131364. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  131365. assert( pCsr->nDoc>0 );
  131366. for(iCol=0; iCol<pTab->nColumn; iCol++){
  131367. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  131368. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  131369. }
  131370. }else{
  131371. rc = fts3EvalGatherStats(pCsr, pExpr);
  131372. if( rc==SQLITE_OK ){
  131373. assert( pExpr->aMI );
  131374. for(iCol=0; iCol<pTab->nColumn; iCol++){
  131375. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  131376. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  131377. }
  131378. }
  131379. }
  131380. return rc;
  131381. }
  131382. /*
  131383. ** The expression pExpr passed as the second argument to this function
  131384. ** must be of type FTSQUERY_PHRASE.
  131385. **
  131386. ** The returned value is either NULL or a pointer to a buffer containing
  131387. ** a position-list indicating the occurrences of the phrase in column iCol
  131388. ** of the current row.
  131389. **
  131390. ** More specifically, the returned buffer contains 1 varint for each
  131391. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  131392. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  131393. ** if the requested column contains "a b X c d X X" and the position-list
  131394. ** for 'X' is requested, the buffer returned may contain:
  131395. **
  131396. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  131397. **
  131398. ** This function works regardless of whether or not the phrase is deferred,
  131399. ** incremental, or neither.
  131400. */
  131401. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  131402. Fts3Cursor *pCsr, /* FTS3 cursor object */
  131403. Fts3Expr *pExpr, /* Phrase to return doclist for */
  131404. int iCol, /* Column to return position list for */
  131405. char **ppOut /* OUT: Pointer to position list */
  131406. ){
  131407. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131408. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131409. char *pIter;
  131410. int iThis;
  131411. sqlite3_int64 iDocid;
  131412. /* If this phrase is applies specifically to some column other than
  131413. ** column iCol, return a NULL pointer. */
  131414. *ppOut = 0;
  131415. assert( iCol>=0 && iCol<pTab->nColumn );
  131416. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  131417. return SQLITE_OK;
  131418. }
  131419. iDocid = pExpr->iDocid;
  131420. pIter = pPhrase->doclist.pList;
  131421. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  131422. int rc = SQLITE_OK;
  131423. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  131424. int bOr = 0;
  131425. u8 bTreeEof = 0;
  131426. Fts3Expr *p; /* Used to iterate from pExpr to root */
  131427. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  131428. int bMatch;
  131429. /* Check if this phrase descends from an OR expression node. If not,
  131430. ** return NULL. Otherwise, the entry that corresponds to docid
  131431. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  131432. ** tree that the node is part of has been marked as EOF, but the node
  131433. ** itself is not EOF, then it may point to an earlier entry. */
  131434. pNear = pExpr;
  131435. for(p=pExpr->pParent; p; p=p->pParent){
  131436. if( p->eType==FTSQUERY_OR ) bOr = 1;
  131437. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  131438. if( p->bEof ) bTreeEof = 1;
  131439. }
  131440. if( bOr==0 ) return SQLITE_OK;
  131441. /* This is the descendent of an OR node. In this case we cannot use
  131442. ** an incremental phrase. Load the entire doclist for the phrase
  131443. ** into memory in this case. */
  131444. if( pPhrase->bIncr ){
  131445. int bEofSave = pNear->bEof;
  131446. fts3EvalRestart(pCsr, pNear, &rc);
  131447. while( rc==SQLITE_OK && !pNear->bEof ){
  131448. fts3EvalNextRow(pCsr, pNear, &rc);
  131449. if( bEofSave==0 && pNear->iDocid==iDocid ) break;
  131450. }
  131451. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  131452. }
  131453. if( bTreeEof ){
  131454. while( rc==SQLITE_OK && !pNear->bEof ){
  131455. fts3EvalNextRow(pCsr, pNear, &rc);
  131456. }
  131457. }
  131458. if( rc!=SQLITE_OK ) return rc;
  131459. bMatch = 1;
  131460. for(p=pNear; p; p=p->pLeft){
  131461. u8 bEof = 0;
  131462. Fts3Expr *pTest = p;
  131463. Fts3Phrase *pPh;
  131464. assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
  131465. if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
  131466. assert( pTest->eType==FTSQUERY_PHRASE );
  131467. pPh = pTest->pPhrase;
  131468. pIter = pPh->pOrPoslist;
  131469. iDocid = pPh->iOrDocid;
  131470. if( pCsr->bDesc==bDescDoclist ){
  131471. bEof = !pPh->doclist.nAll ||
  131472. (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
  131473. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  131474. sqlite3Fts3DoclistNext(
  131475. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  131476. &pIter, &iDocid, &bEof
  131477. );
  131478. }
  131479. }else{
  131480. bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
  131481. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  131482. int dummy;
  131483. sqlite3Fts3DoclistPrev(
  131484. bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
  131485. &pIter, &iDocid, &dummy, &bEof
  131486. );
  131487. }
  131488. }
  131489. pPh->pOrPoslist = pIter;
  131490. pPh->iOrDocid = iDocid;
  131491. if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
  131492. }
  131493. if( bMatch ){
  131494. pIter = pPhrase->pOrPoslist;
  131495. }else{
  131496. pIter = 0;
  131497. }
  131498. }
  131499. if( pIter==0 ) return SQLITE_OK;
  131500. if( *pIter==0x01 ){
  131501. pIter++;
  131502. pIter += fts3GetVarint32(pIter, &iThis);
  131503. }else{
  131504. iThis = 0;
  131505. }
  131506. while( iThis<iCol ){
  131507. fts3ColumnlistCopy(0, &pIter);
  131508. if( *pIter==0x00 ) return SQLITE_OK;
  131509. pIter++;
  131510. pIter += fts3GetVarint32(pIter, &iThis);
  131511. }
  131512. if( *pIter==0x00 ){
  131513. pIter = 0;
  131514. }
  131515. *ppOut = ((iCol==iThis)?pIter:0);
  131516. return SQLITE_OK;
  131517. }
  131518. /*
  131519. ** Free all components of the Fts3Phrase structure that were allocated by
  131520. ** the eval module. Specifically, this means to free:
  131521. **
  131522. ** * the contents of pPhrase->doclist, and
  131523. ** * any Fts3MultiSegReader objects held by phrase tokens.
  131524. */
  131525. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  131526. if( pPhrase ){
  131527. int i;
  131528. sqlite3_free(pPhrase->doclist.aAll);
  131529. fts3EvalInvalidatePoslist(pPhrase);
  131530. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  131531. for(i=0; i<pPhrase->nToken; i++){
  131532. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  131533. pPhrase->aToken[i].pSegcsr = 0;
  131534. }
  131535. }
  131536. }
  131537. /*
  131538. ** Return SQLITE_CORRUPT_VTAB.
  131539. */
  131540. #ifdef SQLITE_DEBUG
  131541. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  131542. return SQLITE_CORRUPT_VTAB;
  131543. }
  131544. #endif
  131545. #if !SQLITE_CORE
  131546. /*
  131547. ** Initialize API pointer table, if required.
  131548. */
  131549. #ifdef _WIN32
  131550. __declspec(dllexport)
  131551. #endif
  131552. SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
  131553. sqlite3 *db,
  131554. char **pzErrMsg,
  131555. const sqlite3_api_routines *pApi
  131556. ){
  131557. SQLITE_EXTENSION_INIT2(pApi)
  131558. return sqlite3Fts3Init(db);
  131559. }
  131560. #endif
  131561. #endif
  131562. /************** End of fts3.c ************************************************/
  131563. /************** Begin file fts3_aux.c ****************************************/
  131564. /*
  131565. ** 2011 Jan 27
  131566. **
  131567. ** The author disclaims copyright to this source code. In place of
  131568. ** a legal notice, here is a blessing:
  131569. **
  131570. ** May you do good and not evil.
  131571. ** May you find forgiveness for yourself and forgive others.
  131572. ** May you share freely, never taking more than you give.
  131573. **
  131574. ******************************************************************************
  131575. **
  131576. */
  131577. /* #include "fts3Int.h" */
  131578. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  131579. /* #include <string.h> */
  131580. /* #include <assert.h> */
  131581. typedef struct Fts3auxTable Fts3auxTable;
  131582. typedef struct Fts3auxCursor Fts3auxCursor;
  131583. struct Fts3auxTable {
  131584. sqlite3_vtab base; /* Base class used by SQLite core */
  131585. Fts3Table *pFts3Tab;
  131586. };
  131587. struct Fts3auxCursor {
  131588. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  131589. Fts3MultiSegReader csr; /* Must be right after "base" */
  131590. Fts3SegFilter filter;
  131591. char *zStop;
  131592. int nStop; /* Byte-length of string zStop */
  131593. int iLangid; /* Language id to query */
  131594. int isEof; /* True if cursor is at EOF */
  131595. sqlite3_int64 iRowid; /* Current rowid */
  131596. int iCol; /* Current value of 'col' column */
  131597. int nStat; /* Size of aStat[] array */
  131598. struct Fts3auxColstats {
  131599. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  131600. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  131601. } *aStat;
  131602. };
  131603. /*
  131604. ** Schema of the terms table.
  131605. */
  131606. #define FTS3_AUX_SCHEMA \
  131607. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  131608. /*
  131609. ** This function does all the work for both the xConnect and xCreate methods.
  131610. ** These tables have no persistent representation of their own, so xConnect
  131611. ** and xCreate are identical operations.
  131612. */
  131613. static int fts3auxConnectMethod(
  131614. sqlite3 *db, /* Database connection */
  131615. void *pUnused, /* Unused */
  131616. int argc, /* Number of elements in argv array */
  131617. const char * const *argv, /* xCreate/xConnect argument array */
  131618. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  131619. char **pzErr /* OUT: sqlite3_malloc'd error message */
  131620. ){
  131621. char const *zDb; /* Name of database (e.g. "main") */
  131622. char const *zFts3; /* Name of fts3 table */
  131623. int nDb; /* Result of strlen(zDb) */
  131624. int nFts3; /* Result of strlen(zFts3) */
  131625. int nByte; /* Bytes of space to allocate here */
  131626. int rc; /* value returned by declare_vtab() */
  131627. Fts3auxTable *p; /* Virtual table object to return */
  131628. UNUSED_PARAMETER(pUnused);
  131629. /* The user should invoke this in one of two forms:
  131630. **
  131631. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  131632. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  131633. */
  131634. if( argc!=4 && argc!=5 ) goto bad_args;
  131635. zDb = argv[1];
  131636. nDb = (int)strlen(zDb);
  131637. if( argc==5 ){
  131638. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  131639. zDb = argv[3];
  131640. nDb = (int)strlen(zDb);
  131641. zFts3 = argv[4];
  131642. }else{
  131643. goto bad_args;
  131644. }
  131645. }else{
  131646. zFts3 = argv[3];
  131647. }
  131648. nFts3 = (int)strlen(zFts3);
  131649. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  131650. if( rc!=SQLITE_OK ) return rc;
  131651. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  131652. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  131653. if( !p ) return SQLITE_NOMEM;
  131654. memset(p, 0, nByte);
  131655. p->pFts3Tab = (Fts3Table *)&p[1];
  131656. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  131657. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  131658. p->pFts3Tab->db = db;
  131659. p->pFts3Tab->nIndex = 1;
  131660. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  131661. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  131662. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  131663. *ppVtab = (sqlite3_vtab *)p;
  131664. return SQLITE_OK;
  131665. bad_args:
  131666. sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
  131667. return SQLITE_ERROR;
  131668. }
  131669. /*
  131670. ** This function does the work for both the xDisconnect and xDestroy methods.
  131671. ** These tables have no persistent representation of their own, so xDisconnect
  131672. ** and xDestroy are identical operations.
  131673. */
  131674. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  131675. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  131676. Fts3Table *pFts3 = p->pFts3Tab;
  131677. int i;
  131678. /* Free any prepared statements held */
  131679. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  131680. sqlite3_finalize(pFts3->aStmt[i]);
  131681. }
  131682. sqlite3_free(pFts3->zSegmentsTbl);
  131683. sqlite3_free(p);
  131684. return SQLITE_OK;
  131685. }
  131686. #define FTS4AUX_EQ_CONSTRAINT 1
  131687. #define FTS4AUX_GE_CONSTRAINT 2
  131688. #define FTS4AUX_LE_CONSTRAINT 4
  131689. /*
  131690. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  131691. */
  131692. static int fts3auxBestIndexMethod(
  131693. sqlite3_vtab *pVTab,
  131694. sqlite3_index_info *pInfo
  131695. ){
  131696. int i;
  131697. int iEq = -1;
  131698. int iGe = -1;
  131699. int iLe = -1;
  131700. int iLangid = -1;
  131701. int iNext = 1; /* Next free argvIndex value */
  131702. UNUSED_PARAMETER(pVTab);
  131703. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  131704. if( pInfo->nOrderBy==1
  131705. && pInfo->aOrderBy[0].iColumn==0
  131706. && pInfo->aOrderBy[0].desc==0
  131707. ){
  131708. pInfo->orderByConsumed = 1;
  131709. }
  131710. /* Search for equality and range constraints on the "term" column.
  131711. ** And equality constraints on the hidden "languageid" column. */
  131712. for(i=0; i<pInfo->nConstraint; i++){
  131713. if( pInfo->aConstraint[i].usable ){
  131714. int op = pInfo->aConstraint[i].op;
  131715. int iCol = pInfo->aConstraint[i].iColumn;
  131716. if( iCol==0 ){
  131717. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  131718. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  131719. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  131720. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  131721. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  131722. }
  131723. if( iCol==4 ){
  131724. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  131725. }
  131726. }
  131727. }
  131728. if( iEq>=0 ){
  131729. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  131730. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  131731. pInfo->estimatedCost = 5;
  131732. }else{
  131733. pInfo->idxNum = 0;
  131734. pInfo->estimatedCost = 20000;
  131735. if( iGe>=0 ){
  131736. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  131737. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  131738. pInfo->estimatedCost /= 2;
  131739. }
  131740. if( iLe>=0 ){
  131741. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  131742. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  131743. pInfo->estimatedCost /= 2;
  131744. }
  131745. }
  131746. if( iLangid>=0 ){
  131747. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  131748. pInfo->estimatedCost--;
  131749. }
  131750. return SQLITE_OK;
  131751. }
  131752. /*
  131753. ** xOpen - Open a cursor.
  131754. */
  131755. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  131756. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  131757. UNUSED_PARAMETER(pVTab);
  131758. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  131759. if( !pCsr ) return SQLITE_NOMEM;
  131760. memset(pCsr, 0, sizeof(Fts3auxCursor));
  131761. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  131762. return SQLITE_OK;
  131763. }
  131764. /*
  131765. ** xClose - Close a cursor.
  131766. */
  131767. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  131768. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  131769. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  131770. sqlite3Fts3SegmentsClose(pFts3);
  131771. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  131772. sqlite3_free((void *)pCsr->filter.zTerm);
  131773. sqlite3_free(pCsr->zStop);
  131774. sqlite3_free(pCsr->aStat);
  131775. sqlite3_free(pCsr);
  131776. return SQLITE_OK;
  131777. }
  131778. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  131779. if( nSize>pCsr->nStat ){
  131780. struct Fts3auxColstats *aNew;
  131781. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  131782. sizeof(struct Fts3auxColstats) * nSize
  131783. );
  131784. if( aNew==0 ) return SQLITE_NOMEM;
  131785. memset(&aNew[pCsr->nStat], 0,
  131786. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  131787. );
  131788. pCsr->aStat = aNew;
  131789. pCsr->nStat = nSize;
  131790. }
  131791. return SQLITE_OK;
  131792. }
  131793. /*
  131794. ** xNext - Advance the cursor to the next row, if any.
  131795. */
  131796. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  131797. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  131798. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  131799. int rc;
  131800. /* Increment our pretend rowid value. */
  131801. pCsr->iRowid++;
  131802. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  131803. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  131804. }
  131805. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  131806. if( rc==SQLITE_ROW ){
  131807. int i = 0;
  131808. int nDoclist = pCsr->csr.nDoclist;
  131809. char *aDoclist = pCsr->csr.aDoclist;
  131810. int iCol;
  131811. int eState = 0;
  131812. if( pCsr->zStop ){
  131813. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  131814. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  131815. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  131816. pCsr->isEof = 1;
  131817. return SQLITE_OK;
  131818. }
  131819. }
  131820. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  131821. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  131822. iCol = 0;
  131823. while( i<nDoclist ){
  131824. sqlite3_int64 v = 0;
  131825. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  131826. switch( eState ){
  131827. /* State 0. In this state the integer just read was a docid. */
  131828. case 0:
  131829. pCsr->aStat[0].nDoc++;
  131830. eState = 1;
  131831. iCol = 0;
  131832. break;
  131833. /* State 1. In this state we are expecting either a 1, indicating
  131834. ** that the following integer will be a column number, or the
  131835. ** start of a position list for column 0.
  131836. **
  131837. ** The only difference between state 1 and state 2 is that if the
  131838. ** integer encountered in state 1 is not 0 or 1, then we need to
  131839. ** increment the column 0 "nDoc" count for this term.
  131840. */
  131841. case 1:
  131842. assert( iCol==0 );
  131843. if( v>1 ){
  131844. pCsr->aStat[1].nDoc++;
  131845. }
  131846. eState = 2;
  131847. /* fall through */
  131848. case 2:
  131849. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  131850. eState = 0;
  131851. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  131852. eState = 3;
  131853. }else{ /* 2 or greater. A position. */
  131854. pCsr->aStat[iCol+1].nOcc++;
  131855. pCsr->aStat[0].nOcc++;
  131856. }
  131857. break;
  131858. /* State 3. The integer just read is a column number. */
  131859. default: assert( eState==3 );
  131860. iCol = (int)v;
  131861. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  131862. pCsr->aStat[iCol+1].nDoc++;
  131863. eState = 2;
  131864. break;
  131865. }
  131866. }
  131867. pCsr->iCol = 0;
  131868. rc = SQLITE_OK;
  131869. }else{
  131870. pCsr->isEof = 1;
  131871. }
  131872. return rc;
  131873. }
  131874. /*
  131875. ** xFilter - Initialize a cursor to point at the start of its data.
  131876. */
  131877. static int fts3auxFilterMethod(
  131878. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  131879. int idxNum, /* Strategy index */
  131880. const char *idxStr, /* Unused */
  131881. int nVal, /* Number of elements in apVal */
  131882. sqlite3_value **apVal /* Arguments for the indexing scheme */
  131883. ){
  131884. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  131885. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  131886. int rc;
  131887. int isScan = 0;
  131888. int iLangVal = 0; /* Language id to query */
  131889. int iEq = -1; /* Index of term=? value in apVal */
  131890. int iGe = -1; /* Index of term>=? value in apVal */
  131891. int iLe = -1; /* Index of term<=? value in apVal */
  131892. int iLangid = -1; /* Index of languageid=? value in apVal */
  131893. int iNext = 0;
  131894. UNUSED_PARAMETER(nVal);
  131895. UNUSED_PARAMETER(idxStr);
  131896. assert( idxStr==0 );
  131897. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  131898. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  131899. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  131900. );
  131901. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  131902. iEq = iNext++;
  131903. }else{
  131904. isScan = 1;
  131905. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  131906. iGe = iNext++;
  131907. }
  131908. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  131909. iLe = iNext++;
  131910. }
  131911. }
  131912. if( iNext<nVal ){
  131913. iLangid = iNext++;
  131914. }
  131915. /* In case this cursor is being reused, close and zero it. */
  131916. testcase(pCsr->filter.zTerm);
  131917. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  131918. sqlite3_free((void *)pCsr->filter.zTerm);
  131919. sqlite3_free(pCsr->aStat);
  131920. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  131921. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  131922. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  131923. if( iEq>=0 || iGe>=0 ){
  131924. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  131925. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  131926. if( zStr ){
  131927. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  131928. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  131929. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  131930. }
  131931. }
  131932. if( iLe>=0 ){
  131933. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  131934. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  131935. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  131936. }
  131937. if( iLangid>=0 ){
  131938. iLangVal = sqlite3_value_int(apVal[iLangid]);
  131939. /* If the user specified a negative value for the languageid, use zero
  131940. ** instead. This works, as the "languageid=?" constraint will also
  131941. ** be tested by the VDBE layer. The test will always be false (since
  131942. ** this module will not return a row with a negative languageid), and
  131943. ** so the overall query will return zero rows. */
  131944. if( iLangVal<0 ) iLangVal = 0;
  131945. }
  131946. pCsr->iLangid = iLangVal;
  131947. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  131948. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  131949. );
  131950. if( rc==SQLITE_OK ){
  131951. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  131952. }
  131953. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  131954. return rc;
  131955. }
  131956. /*
  131957. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  131958. */
  131959. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  131960. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  131961. return pCsr->isEof;
  131962. }
  131963. /*
  131964. ** xColumn - Return a column value.
  131965. */
  131966. static int fts3auxColumnMethod(
  131967. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  131968. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  131969. int iCol /* Index of column to read value from */
  131970. ){
  131971. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  131972. assert( p->isEof==0 );
  131973. switch( iCol ){
  131974. case 0: /* term */
  131975. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  131976. break;
  131977. case 1: /* col */
  131978. if( p->iCol ){
  131979. sqlite3_result_int(pCtx, p->iCol-1);
  131980. }else{
  131981. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  131982. }
  131983. break;
  131984. case 2: /* documents */
  131985. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  131986. break;
  131987. case 3: /* occurrences */
  131988. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  131989. break;
  131990. default: /* languageid */
  131991. assert( iCol==4 );
  131992. sqlite3_result_int(pCtx, p->iLangid);
  131993. break;
  131994. }
  131995. return SQLITE_OK;
  131996. }
  131997. /*
  131998. ** xRowid - Return the current rowid for the cursor.
  131999. */
  132000. static int fts3auxRowidMethod(
  132001. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  132002. sqlite_int64 *pRowid /* OUT: Rowid value */
  132003. ){
  132004. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  132005. *pRowid = pCsr->iRowid;
  132006. return SQLITE_OK;
  132007. }
  132008. /*
  132009. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  132010. ** if successful or an error code if sqlite3_create_module() fails.
  132011. */
  132012. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  132013. static const sqlite3_module fts3aux_module = {
  132014. 0, /* iVersion */
  132015. fts3auxConnectMethod, /* xCreate */
  132016. fts3auxConnectMethod, /* xConnect */
  132017. fts3auxBestIndexMethod, /* xBestIndex */
  132018. fts3auxDisconnectMethod, /* xDisconnect */
  132019. fts3auxDisconnectMethod, /* xDestroy */
  132020. fts3auxOpenMethod, /* xOpen */
  132021. fts3auxCloseMethod, /* xClose */
  132022. fts3auxFilterMethod, /* xFilter */
  132023. fts3auxNextMethod, /* xNext */
  132024. fts3auxEofMethod, /* xEof */
  132025. fts3auxColumnMethod, /* xColumn */
  132026. fts3auxRowidMethod, /* xRowid */
  132027. 0, /* xUpdate */
  132028. 0, /* xBegin */
  132029. 0, /* xSync */
  132030. 0, /* xCommit */
  132031. 0, /* xRollback */
  132032. 0, /* xFindFunction */
  132033. 0, /* xRename */
  132034. 0, /* xSavepoint */
  132035. 0, /* xRelease */
  132036. 0 /* xRollbackTo */
  132037. };
  132038. int rc; /* Return code */
  132039. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  132040. return rc;
  132041. }
  132042. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  132043. /************** End of fts3_aux.c ********************************************/
  132044. /************** Begin file fts3_expr.c ***************************************/
  132045. /*
  132046. ** 2008 Nov 28
  132047. **
  132048. ** The author disclaims copyright to this source code. In place of
  132049. ** a legal notice, here is a blessing:
  132050. **
  132051. ** May you do good and not evil.
  132052. ** May you find forgiveness for yourself and forgive others.
  132053. ** May you share freely, never taking more than you give.
  132054. **
  132055. ******************************************************************************
  132056. **
  132057. ** This module contains code that implements a parser for fts3 query strings
  132058. ** (the right-hand argument to the MATCH operator). Because the supported
  132059. ** syntax is relatively simple, the whole tokenizer/parser system is
  132060. ** hand-coded.
  132061. */
  132062. /* #include "fts3Int.h" */
  132063. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  132064. /*
  132065. ** By default, this module parses the legacy syntax that has been
  132066. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  132067. ** is defined, then it uses the new syntax. The differences between
  132068. ** the new and the old syntaxes are:
  132069. **
  132070. ** a) The new syntax supports parenthesis. The old does not.
  132071. **
  132072. ** b) The new syntax supports the AND and NOT operators. The old does not.
  132073. **
  132074. ** c) The old syntax supports the "-" token qualifier. This is not
  132075. ** supported by the new syntax (it is replaced by the NOT operator).
  132076. **
  132077. ** d) When using the old syntax, the OR operator has a greater precedence
  132078. ** than an implicit AND. When using the new, both implicity and explicit
  132079. ** AND operators have a higher precedence than OR.
  132080. **
  132081. ** If compiled with SQLITE_TEST defined, then this module exports the
  132082. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  132083. ** to zero causes the module to use the old syntax. If it is set to
  132084. ** non-zero the new syntax is activated. This is so both syntaxes can
  132085. ** be tested using a single build of testfixture.
  132086. **
  132087. ** The following describes the syntax supported by the fts3 MATCH
  132088. ** operator in a similar format to that used by the lemon parser
  132089. ** generator. This module does not use actually lemon, it uses a
  132090. ** custom parser.
  132091. **
  132092. ** query ::= andexpr (OR andexpr)*.
  132093. **
  132094. ** andexpr ::= notexpr (AND? notexpr)*.
  132095. **
  132096. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  132097. ** notexpr ::= LP query RP.
  132098. **
  132099. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  132100. **
  132101. ** distance_opt ::= .
  132102. ** distance_opt ::= / INTEGER.
  132103. **
  132104. ** phrase ::= TOKEN.
  132105. ** phrase ::= COLUMN:TOKEN.
  132106. ** phrase ::= "TOKEN TOKEN TOKEN...".
  132107. */
  132108. #ifdef SQLITE_TEST
  132109. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  132110. #else
  132111. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  132112. # define sqlite3_fts3_enable_parentheses 1
  132113. # else
  132114. # define sqlite3_fts3_enable_parentheses 0
  132115. # endif
  132116. #endif
  132117. /*
  132118. ** Default span for NEAR operators.
  132119. */
  132120. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  132121. /* #include <string.h> */
  132122. /* #include <assert.h> */
  132123. /*
  132124. ** isNot:
  132125. ** This variable is used by function getNextNode(). When getNextNode() is
  132126. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  132127. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  132128. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  132129. ** zero.
  132130. */
  132131. typedef struct ParseContext ParseContext;
  132132. struct ParseContext {
  132133. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  132134. int iLangid; /* Language id used with tokenizer */
  132135. const char **azCol; /* Array of column names for fts3 table */
  132136. int bFts4; /* True to allow FTS4-only syntax */
  132137. int nCol; /* Number of entries in azCol[] */
  132138. int iDefaultCol; /* Default column to query */
  132139. int isNot; /* True if getNextNode() sees a unary - */
  132140. sqlite3_context *pCtx; /* Write error message here */
  132141. int nNest; /* Number of nested brackets */
  132142. };
  132143. /*
  132144. ** This function is equivalent to the standard isspace() function.
  132145. **
  132146. ** The standard isspace() can be awkward to use safely, because although it
  132147. ** is defined to accept an argument of type int, its behavior when passed
  132148. ** an integer that falls outside of the range of the unsigned char type
  132149. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  132150. ** is defined to accept an argument of type char, and always returns 0 for
  132151. ** any values that fall outside of the range of the unsigned char type (i.e.
  132152. ** negative values).
  132153. */
  132154. static int fts3isspace(char c){
  132155. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  132156. }
  132157. /*
  132158. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  132159. ** zero the memory before returning a pointer to it. If unsuccessful,
  132160. ** return NULL.
  132161. */
  132162. static void *fts3MallocZero(int nByte){
  132163. void *pRet = sqlite3_malloc(nByte);
  132164. if( pRet ) memset(pRet, 0, nByte);
  132165. return pRet;
  132166. }
  132167. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  132168. sqlite3_tokenizer *pTokenizer,
  132169. int iLangid,
  132170. const char *z,
  132171. int n,
  132172. sqlite3_tokenizer_cursor **ppCsr
  132173. ){
  132174. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  132175. sqlite3_tokenizer_cursor *pCsr = 0;
  132176. int rc;
  132177. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  132178. assert( rc==SQLITE_OK || pCsr==0 );
  132179. if( rc==SQLITE_OK ){
  132180. pCsr->pTokenizer = pTokenizer;
  132181. if( pModule->iVersion>=1 ){
  132182. rc = pModule->xLanguageid(pCsr, iLangid);
  132183. if( rc!=SQLITE_OK ){
  132184. pModule->xClose(pCsr);
  132185. pCsr = 0;
  132186. }
  132187. }
  132188. }
  132189. *ppCsr = pCsr;
  132190. return rc;
  132191. }
  132192. /*
  132193. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  132194. ** call fts3ExprParse(). So this forward declaration is required.
  132195. */
  132196. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  132197. /*
  132198. ** Extract the next token from buffer z (length n) using the tokenizer
  132199. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  132200. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  132201. ** single token and set *ppExpr to point to it. If the end of the buffer is
  132202. ** reached before a token is found, set *ppExpr to zero. It is the
  132203. ** responsibility of the caller to eventually deallocate the allocated
  132204. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  132205. **
  132206. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  132207. ** fails.
  132208. */
  132209. static int getNextToken(
  132210. ParseContext *pParse, /* fts3 query parse context */
  132211. int iCol, /* Value for Fts3Phrase.iColumn */
  132212. const char *z, int n, /* Input string */
  132213. Fts3Expr **ppExpr, /* OUT: expression */
  132214. int *pnConsumed /* OUT: Number of bytes consumed */
  132215. ){
  132216. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  132217. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  132218. int rc;
  132219. sqlite3_tokenizer_cursor *pCursor;
  132220. Fts3Expr *pRet = 0;
  132221. int i = 0;
  132222. /* Set variable i to the maximum number of bytes of input to tokenize. */
  132223. for(i=0; i<n; i++){
  132224. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  132225. if( z[i]=='"' ) break;
  132226. }
  132227. *pnConsumed = i;
  132228. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  132229. if( rc==SQLITE_OK ){
  132230. const char *zToken;
  132231. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  132232. int nByte; /* total space to allocate */
  132233. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  132234. if( rc==SQLITE_OK ){
  132235. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  132236. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  132237. if( !pRet ){
  132238. rc = SQLITE_NOMEM;
  132239. }else{
  132240. pRet->eType = FTSQUERY_PHRASE;
  132241. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  132242. pRet->pPhrase->nToken = 1;
  132243. pRet->pPhrase->iColumn = iCol;
  132244. pRet->pPhrase->aToken[0].n = nToken;
  132245. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  132246. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  132247. if( iEnd<n && z[iEnd]=='*' ){
  132248. pRet->pPhrase->aToken[0].isPrefix = 1;
  132249. iEnd++;
  132250. }
  132251. while( 1 ){
  132252. if( !sqlite3_fts3_enable_parentheses
  132253. && iStart>0 && z[iStart-1]=='-'
  132254. ){
  132255. pParse->isNot = 1;
  132256. iStart--;
  132257. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  132258. pRet->pPhrase->aToken[0].bFirst = 1;
  132259. iStart--;
  132260. }else{
  132261. break;
  132262. }
  132263. }
  132264. }
  132265. *pnConsumed = iEnd;
  132266. }else if( i && rc==SQLITE_DONE ){
  132267. rc = SQLITE_OK;
  132268. }
  132269. pModule->xClose(pCursor);
  132270. }
  132271. *ppExpr = pRet;
  132272. return rc;
  132273. }
  132274. /*
  132275. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  132276. ** then free the old allocation.
  132277. */
  132278. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  132279. void *pRet = sqlite3_realloc(pOrig, nNew);
  132280. if( !pRet ){
  132281. sqlite3_free(pOrig);
  132282. }
  132283. return pRet;
  132284. }
  132285. /*
  132286. ** Buffer zInput, length nInput, contains the contents of a quoted string
  132287. ** that appeared as part of an fts3 query expression. Neither quote character
  132288. ** is included in the buffer. This function attempts to tokenize the entire
  132289. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  132290. ** containing the results.
  132291. **
  132292. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  132293. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  132294. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  132295. ** to 0.
  132296. */
  132297. static int getNextString(
  132298. ParseContext *pParse, /* fts3 query parse context */
  132299. const char *zInput, int nInput, /* Input string */
  132300. Fts3Expr **ppExpr /* OUT: expression */
  132301. ){
  132302. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  132303. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  132304. int rc;
  132305. Fts3Expr *p = 0;
  132306. sqlite3_tokenizer_cursor *pCursor = 0;
  132307. char *zTemp = 0;
  132308. int nTemp = 0;
  132309. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  132310. int nToken = 0;
  132311. /* The final Fts3Expr data structure, including the Fts3Phrase,
  132312. ** Fts3PhraseToken structures token buffers are all stored as a single
  132313. ** allocation so that the expression can be freed with a single call to
  132314. ** sqlite3_free(). Setting this up requires a two pass approach.
  132315. **
  132316. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  132317. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  132318. ** to assemble data in two dynamic buffers:
  132319. **
  132320. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  132321. ** structure, followed by the array of Fts3PhraseToken
  132322. ** structures. This pass only populates the Fts3PhraseToken array.
  132323. **
  132324. ** Buffer zTemp: Contains copies of all tokens.
  132325. **
  132326. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  132327. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  132328. ** structures.
  132329. */
  132330. rc = sqlite3Fts3OpenTokenizer(
  132331. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  132332. if( rc==SQLITE_OK ){
  132333. int ii;
  132334. for(ii=0; rc==SQLITE_OK; ii++){
  132335. const char *zByte;
  132336. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  132337. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  132338. if( rc==SQLITE_OK ){
  132339. Fts3PhraseToken *pToken;
  132340. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  132341. if( !p ) goto no_mem;
  132342. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  132343. if( !zTemp ) goto no_mem;
  132344. assert( nToken==ii );
  132345. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  132346. memset(pToken, 0, sizeof(Fts3PhraseToken));
  132347. memcpy(&zTemp[nTemp], zByte, nByte);
  132348. nTemp += nByte;
  132349. pToken->n = nByte;
  132350. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  132351. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  132352. nToken = ii+1;
  132353. }
  132354. }
  132355. pModule->xClose(pCursor);
  132356. pCursor = 0;
  132357. }
  132358. if( rc==SQLITE_DONE ){
  132359. int jj;
  132360. char *zBuf = 0;
  132361. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  132362. if( !p ) goto no_mem;
  132363. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  132364. p->eType = FTSQUERY_PHRASE;
  132365. p->pPhrase = (Fts3Phrase *)&p[1];
  132366. p->pPhrase->iColumn = pParse->iDefaultCol;
  132367. p->pPhrase->nToken = nToken;
  132368. zBuf = (char *)&p->pPhrase->aToken[nToken];
  132369. if( zTemp ){
  132370. memcpy(zBuf, zTemp, nTemp);
  132371. sqlite3_free(zTemp);
  132372. }else{
  132373. assert( nTemp==0 );
  132374. }
  132375. for(jj=0; jj<p->pPhrase->nToken; jj++){
  132376. p->pPhrase->aToken[jj].z = zBuf;
  132377. zBuf += p->pPhrase->aToken[jj].n;
  132378. }
  132379. rc = SQLITE_OK;
  132380. }
  132381. *ppExpr = p;
  132382. return rc;
  132383. no_mem:
  132384. if( pCursor ){
  132385. pModule->xClose(pCursor);
  132386. }
  132387. sqlite3_free(zTemp);
  132388. sqlite3_free(p);
  132389. *ppExpr = 0;
  132390. return SQLITE_NOMEM;
  132391. }
  132392. /*
  132393. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  132394. ** structure, or set to 0 if the end of the input buffer is reached.
  132395. **
  132396. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  132397. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  132398. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  132399. */
  132400. static int getNextNode(
  132401. ParseContext *pParse, /* fts3 query parse context */
  132402. const char *z, int n, /* Input string */
  132403. Fts3Expr **ppExpr, /* OUT: expression */
  132404. int *pnConsumed /* OUT: Number of bytes consumed */
  132405. ){
  132406. static const struct Fts3Keyword {
  132407. char *z; /* Keyword text */
  132408. unsigned char n; /* Length of the keyword */
  132409. unsigned char parenOnly; /* Only valid in paren mode */
  132410. unsigned char eType; /* Keyword code */
  132411. } aKeyword[] = {
  132412. { "OR" , 2, 0, FTSQUERY_OR },
  132413. { "AND", 3, 1, FTSQUERY_AND },
  132414. { "NOT", 3, 1, FTSQUERY_NOT },
  132415. { "NEAR", 4, 0, FTSQUERY_NEAR }
  132416. };
  132417. int ii;
  132418. int iCol;
  132419. int iColLen;
  132420. int rc;
  132421. Fts3Expr *pRet = 0;
  132422. const char *zInput = z;
  132423. int nInput = n;
  132424. pParse->isNot = 0;
  132425. /* Skip over any whitespace before checking for a keyword, an open or
  132426. ** close bracket, or a quoted string.
  132427. */
  132428. while( nInput>0 && fts3isspace(*zInput) ){
  132429. nInput--;
  132430. zInput++;
  132431. }
  132432. if( nInput==0 ){
  132433. return SQLITE_DONE;
  132434. }
  132435. /* See if we are dealing with a keyword. */
  132436. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  132437. const struct Fts3Keyword *pKey = &aKeyword[ii];
  132438. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  132439. continue;
  132440. }
  132441. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  132442. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  132443. int nKey = pKey->n;
  132444. char cNext;
  132445. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  132446. if( pKey->eType==FTSQUERY_NEAR ){
  132447. assert( nKey==4 );
  132448. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  132449. nNear = 0;
  132450. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  132451. nNear = nNear * 10 + (zInput[nKey] - '0');
  132452. }
  132453. }
  132454. }
  132455. /* At this point this is probably a keyword. But for that to be true,
  132456. ** the next byte must contain either whitespace, an open or close
  132457. ** parenthesis, a quote character, or EOF.
  132458. */
  132459. cNext = zInput[nKey];
  132460. if( fts3isspace(cNext)
  132461. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  132462. ){
  132463. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  132464. if( !pRet ){
  132465. return SQLITE_NOMEM;
  132466. }
  132467. pRet->eType = pKey->eType;
  132468. pRet->nNear = nNear;
  132469. *ppExpr = pRet;
  132470. *pnConsumed = (int)((zInput - z) + nKey);
  132471. return SQLITE_OK;
  132472. }
  132473. /* Turns out that wasn't a keyword after all. This happens if the
  132474. ** user has supplied a token such as "ORacle". Continue.
  132475. */
  132476. }
  132477. }
  132478. /* See if we are dealing with a quoted phrase. If this is the case, then
  132479. ** search for the closing quote and pass the whole string to getNextString()
  132480. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  132481. ** a quote character embedded in a string.
  132482. */
  132483. if( *zInput=='"' ){
  132484. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  132485. *pnConsumed = (int)((zInput - z) + ii + 1);
  132486. if( ii==nInput ){
  132487. return SQLITE_ERROR;
  132488. }
  132489. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  132490. }
  132491. if( sqlite3_fts3_enable_parentheses ){
  132492. if( *zInput=='(' ){
  132493. int nConsumed = 0;
  132494. pParse->nNest++;
  132495. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  132496. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  132497. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  132498. return rc;
  132499. }else if( *zInput==')' ){
  132500. pParse->nNest--;
  132501. *pnConsumed = (int)((zInput - z) + 1);
  132502. *ppExpr = 0;
  132503. return SQLITE_DONE;
  132504. }
  132505. }
  132506. /* If control flows to this point, this must be a regular token, or
  132507. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  132508. ** interface. Before doing so, figure out if there is an explicit
  132509. ** column specifier for the token.
  132510. **
  132511. ** TODO: Strangely, it is not possible to associate a column specifier
  132512. ** with a quoted phrase, only with a single token. Not sure if this was
  132513. ** an implementation artifact or an intentional decision when fts3 was
  132514. ** first implemented. Whichever it was, this module duplicates the
  132515. ** limitation.
  132516. */
  132517. iCol = pParse->iDefaultCol;
  132518. iColLen = 0;
  132519. for(ii=0; ii<pParse->nCol; ii++){
  132520. const char *zStr = pParse->azCol[ii];
  132521. int nStr = (int)strlen(zStr);
  132522. if( nInput>nStr && zInput[nStr]==':'
  132523. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  132524. ){
  132525. iCol = ii;
  132526. iColLen = (int)((zInput - z) + nStr + 1);
  132527. break;
  132528. }
  132529. }
  132530. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  132531. *pnConsumed += iColLen;
  132532. return rc;
  132533. }
  132534. /*
  132535. ** The argument is an Fts3Expr structure for a binary operator (any type
  132536. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  132537. ** precedence of the operator. Lower values have a higher precedence (i.e.
  132538. ** group more tightly). For example, in the C language, the == operator
  132539. ** groups more tightly than ||, and would therefore have a higher precedence.
  132540. **
  132541. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  132542. ** is defined), the order of the operators in precedence from highest to
  132543. ** lowest is:
  132544. **
  132545. ** NEAR
  132546. ** NOT
  132547. ** AND (including implicit ANDs)
  132548. ** OR
  132549. **
  132550. ** Note that when using the old query syntax, the OR operator has a higher
  132551. ** precedence than the AND operator.
  132552. */
  132553. static int opPrecedence(Fts3Expr *p){
  132554. assert( p->eType!=FTSQUERY_PHRASE );
  132555. if( sqlite3_fts3_enable_parentheses ){
  132556. return p->eType;
  132557. }else if( p->eType==FTSQUERY_NEAR ){
  132558. return 1;
  132559. }else if( p->eType==FTSQUERY_OR ){
  132560. return 2;
  132561. }
  132562. assert( p->eType==FTSQUERY_AND );
  132563. return 3;
  132564. }
  132565. /*
  132566. ** Argument ppHead contains a pointer to the current head of a query
  132567. ** expression tree being parsed. pPrev is the expression node most recently
  132568. ** inserted into the tree. This function adds pNew, which is always a binary
  132569. ** operator node, into the expression tree based on the relative precedence
  132570. ** of pNew and the existing nodes of the tree. This may result in the head
  132571. ** of the tree changing, in which case *ppHead is set to the new root node.
  132572. */
  132573. static void insertBinaryOperator(
  132574. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  132575. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  132576. Fts3Expr *pNew /* New binary node to insert into expression tree */
  132577. ){
  132578. Fts3Expr *pSplit = pPrev;
  132579. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  132580. pSplit = pSplit->pParent;
  132581. }
  132582. if( pSplit->pParent ){
  132583. assert( pSplit->pParent->pRight==pSplit );
  132584. pSplit->pParent->pRight = pNew;
  132585. pNew->pParent = pSplit->pParent;
  132586. }else{
  132587. *ppHead = pNew;
  132588. }
  132589. pNew->pLeft = pSplit;
  132590. pSplit->pParent = pNew;
  132591. }
  132592. /*
  132593. ** Parse the fts3 query expression found in buffer z, length n. This function
  132594. ** returns either when the end of the buffer is reached or an unmatched
  132595. ** closing bracket - ')' - is encountered.
  132596. **
  132597. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  132598. ** parsed form of the expression and *pnConsumed is set to the number of
  132599. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  132600. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  132601. */
  132602. static int fts3ExprParse(
  132603. ParseContext *pParse, /* fts3 query parse context */
  132604. const char *z, int n, /* Text of MATCH query */
  132605. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  132606. int *pnConsumed /* OUT: Number of bytes consumed */
  132607. ){
  132608. Fts3Expr *pRet = 0;
  132609. Fts3Expr *pPrev = 0;
  132610. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  132611. int nIn = n;
  132612. const char *zIn = z;
  132613. int rc = SQLITE_OK;
  132614. int isRequirePhrase = 1;
  132615. while( rc==SQLITE_OK ){
  132616. Fts3Expr *p = 0;
  132617. int nByte = 0;
  132618. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  132619. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  132620. if( rc==SQLITE_OK ){
  132621. if( p ){
  132622. int isPhrase;
  132623. if( !sqlite3_fts3_enable_parentheses
  132624. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  132625. ){
  132626. /* Create an implicit NOT operator. */
  132627. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  132628. if( !pNot ){
  132629. sqlite3Fts3ExprFree(p);
  132630. rc = SQLITE_NOMEM;
  132631. goto exprparse_out;
  132632. }
  132633. pNot->eType = FTSQUERY_NOT;
  132634. pNot->pRight = p;
  132635. p->pParent = pNot;
  132636. if( pNotBranch ){
  132637. pNot->pLeft = pNotBranch;
  132638. pNotBranch->pParent = pNot;
  132639. }
  132640. pNotBranch = pNot;
  132641. p = pPrev;
  132642. }else{
  132643. int eType = p->eType;
  132644. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  132645. /* The isRequirePhrase variable is set to true if a phrase or
  132646. ** an expression contained in parenthesis is required. If a
  132647. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  132648. ** isRequirePhrase is set, this is a syntax error.
  132649. */
  132650. if( !isPhrase && isRequirePhrase ){
  132651. sqlite3Fts3ExprFree(p);
  132652. rc = SQLITE_ERROR;
  132653. goto exprparse_out;
  132654. }
  132655. if( isPhrase && !isRequirePhrase ){
  132656. /* Insert an implicit AND operator. */
  132657. Fts3Expr *pAnd;
  132658. assert( pRet && pPrev );
  132659. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  132660. if( !pAnd ){
  132661. sqlite3Fts3ExprFree(p);
  132662. rc = SQLITE_NOMEM;
  132663. goto exprparse_out;
  132664. }
  132665. pAnd->eType = FTSQUERY_AND;
  132666. insertBinaryOperator(&pRet, pPrev, pAnd);
  132667. pPrev = pAnd;
  132668. }
  132669. /* This test catches attempts to make either operand of a NEAR
  132670. ** operator something other than a phrase. For example, either of
  132671. ** the following:
  132672. **
  132673. ** (bracketed expression) NEAR phrase
  132674. ** phrase NEAR (bracketed expression)
  132675. **
  132676. ** Return an error in either case.
  132677. */
  132678. if( pPrev && (
  132679. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  132680. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  132681. )){
  132682. sqlite3Fts3ExprFree(p);
  132683. rc = SQLITE_ERROR;
  132684. goto exprparse_out;
  132685. }
  132686. if( isPhrase ){
  132687. if( pRet ){
  132688. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  132689. pPrev->pRight = p;
  132690. p->pParent = pPrev;
  132691. }else{
  132692. pRet = p;
  132693. }
  132694. }else{
  132695. insertBinaryOperator(&pRet, pPrev, p);
  132696. }
  132697. isRequirePhrase = !isPhrase;
  132698. }
  132699. pPrev = p;
  132700. }
  132701. assert( nByte>0 );
  132702. }
  132703. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  132704. nIn -= nByte;
  132705. zIn += nByte;
  132706. }
  132707. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  132708. rc = SQLITE_ERROR;
  132709. }
  132710. if( rc==SQLITE_DONE ){
  132711. rc = SQLITE_OK;
  132712. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  132713. if( !pRet ){
  132714. rc = SQLITE_ERROR;
  132715. }else{
  132716. Fts3Expr *pIter = pNotBranch;
  132717. while( pIter->pLeft ){
  132718. pIter = pIter->pLeft;
  132719. }
  132720. pIter->pLeft = pRet;
  132721. pRet->pParent = pIter;
  132722. pRet = pNotBranch;
  132723. }
  132724. }
  132725. }
  132726. *pnConsumed = n - nIn;
  132727. exprparse_out:
  132728. if( rc!=SQLITE_OK ){
  132729. sqlite3Fts3ExprFree(pRet);
  132730. sqlite3Fts3ExprFree(pNotBranch);
  132731. pRet = 0;
  132732. }
  132733. *ppExpr = pRet;
  132734. return rc;
  132735. }
  132736. /*
  132737. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  132738. ** as the only argument is more than nMaxDepth.
  132739. */
  132740. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  132741. int rc = SQLITE_OK;
  132742. if( p ){
  132743. if( nMaxDepth<0 ){
  132744. rc = SQLITE_TOOBIG;
  132745. }else{
  132746. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  132747. if( rc==SQLITE_OK ){
  132748. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  132749. }
  132750. }
  132751. }
  132752. return rc;
  132753. }
  132754. /*
  132755. ** This function attempts to transform the expression tree at (*pp) to
  132756. ** an equivalent but more balanced form. The tree is modified in place.
  132757. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  132758. ** new root expression node.
  132759. **
  132760. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  132761. **
  132762. ** Otherwise, if an error occurs, an SQLite error code is returned and
  132763. ** expression (*pp) freed.
  132764. */
  132765. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  132766. int rc = SQLITE_OK; /* Return code */
  132767. Fts3Expr *pRoot = *pp; /* Initial root node */
  132768. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  132769. int eType = pRoot->eType; /* Type of node in this tree */
  132770. if( nMaxDepth==0 ){
  132771. rc = SQLITE_ERROR;
  132772. }
  132773. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  132774. Fts3Expr **apLeaf;
  132775. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  132776. if( 0==apLeaf ){
  132777. rc = SQLITE_NOMEM;
  132778. }else{
  132779. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  132780. }
  132781. if( rc==SQLITE_OK ){
  132782. int i;
  132783. Fts3Expr *p;
  132784. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  132785. for(p=pRoot; p->eType==eType; p=p->pLeft){
  132786. assert( p->pParent==0 || p->pParent->pLeft==p );
  132787. assert( p->pLeft && p->pRight );
  132788. }
  132789. /* This loop runs once for each leaf in the tree of eType nodes. */
  132790. while( 1 ){
  132791. int iLvl;
  132792. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  132793. assert( pParent==0 || pParent->pLeft==p );
  132794. p->pParent = 0;
  132795. if( pParent ){
  132796. pParent->pLeft = 0;
  132797. }else{
  132798. pRoot = 0;
  132799. }
  132800. rc = fts3ExprBalance(&p, nMaxDepth-1);
  132801. if( rc!=SQLITE_OK ) break;
  132802. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  132803. if( apLeaf[iLvl]==0 ){
  132804. apLeaf[iLvl] = p;
  132805. p = 0;
  132806. }else{
  132807. assert( pFree );
  132808. pFree->pLeft = apLeaf[iLvl];
  132809. pFree->pRight = p;
  132810. pFree->pLeft->pParent = pFree;
  132811. pFree->pRight->pParent = pFree;
  132812. p = pFree;
  132813. pFree = pFree->pParent;
  132814. p->pParent = 0;
  132815. apLeaf[iLvl] = 0;
  132816. }
  132817. }
  132818. if( p ){
  132819. sqlite3Fts3ExprFree(p);
  132820. rc = SQLITE_TOOBIG;
  132821. break;
  132822. }
  132823. /* If that was the last leaf node, break out of the loop */
  132824. if( pParent==0 ) break;
  132825. /* Set $p to point to the next leaf in the tree of eType nodes */
  132826. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  132827. /* Remove pParent from the original tree. */
  132828. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  132829. pParent->pRight->pParent = pParent->pParent;
  132830. if( pParent->pParent ){
  132831. pParent->pParent->pLeft = pParent->pRight;
  132832. }else{
  132833. assert( pParent==pRoot );
  132834. pRoot = pParent->pRight;
  132835. }
  132836. /* Link pParent into the free node list. It will be used as an
  132837. ** internal node of the new tree. */
  132838. pParent->pParent = pFree;
  132839. pFree = pParent;
  132840. }
  132841. if( rc==SQLITE_OK ){
  132842. p = 0;
  132843. for(i=0; i<nMaxDepth; i++){
  132844. if( apLeaf[i] ){
  132845. if( p==0 ){
  132846. p = apLeaf[i];
  132847. p->pParent = 0;
  132848. }else{
  132849. assert( pFree!=0 );
  132850. pFree->pRight = p;
  132851. pFree->pLeft = apLeaf[i];
  132852. pFree->pLeft->pParent = pFree;
  132853. pFree->pRight->pParent = pFree;
  132854. p = pFree;
  132855. pFree = pFree->pParent;
  132856. p->pParent = 0;
  132857. }
  132858. }
  132859. }
  132860. pRoot = p;
  132861. }else{
  132862. /* An error occurred. Delete the contents of the apLeaf[] array
  132863. ** and pFree list. Everything else is cleaned up by the call to
  132864. ** sqlite3Fts3ExprFree(pRoot) below. */
  132865. Fts3Expr *pDel;
  132866. for(i=0; i<nMaxDepth; i++){
  132867. sqlite3Fts3ExprFree(apLeaf[i]);
  132868. }
  132869. while( (pDel=pFree)!=0 ){
  132870. pFree = pDel->pParent;
  132871. sqlite3_free(pDel);
  132872. }
  132873. }
  132874. assert( pFree==0 );
  132875. sqlite3_free( apLeaf );
  132876. }
  132877. }
  132878. if( rc!=SQLITE_OK ){
  132879. sqlite3Fts3ExprFree(pRoot);
  132880. pRoot = 0;
  132881. }
  132882. *pp = pRoot;
  132883. return rc;
  132884. }
  132885. /*
  132886. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  132887. ** differences:
  132888. **
  132889. ** 1. It does not do expression rebalancing.
  132890. ** 2. It does not check that the expression does not exceed the
  132891. ** maximum allowable depth.
  132892. ** 3. Even if it fails, *ppExpr may still be set to point to an
  132893. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  132894. ** in this case.
  132895. */
  132896. static int fts3ExprParseUnbalanced(
  132897. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  132898. int iLangid, /* Language id for tokenizer */
  132899. char **azCol, /* Array of column names for fts3 table */
  132900. int bFts4, /* True to allow FTS4-only syntax */
  132901. int nCol, /* Number of entries in azCol[] */
  132902. int iDefaultCol, /* Default column to query */
  132903. const char *z, int n, /* Text of MATCH query */
  132904. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  132905. ){
  132906. int nParsed;
  132907. int rc;
  132908. ParseContext sParse;
  132909. memset(&sParse, 0, sizeof(ParseContext));
  132910. sParse.pTokenizer = pTokenizer;
  132911. sParse.iLangid = iLangid;
  132912. sParse.azCol = (const char **)azCol;
  132913. sParse.nCol = nCol;
  132914. sParse.iDefaultCol = iDefaultCol;
  132915. sParse.bFts4 = bFts4;
  132916. if( z==0 ){
  132917. *ppExpr = 0;
  132918. return SQLITE_OK;
  132919. }
  132920. if( n<0 ){
  132921. n = (int)strlen(z);
  132922. }
  132923. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  132924. assert( rc==SQLITE_OK || *ppExpr==0 );
  132925. /* Check for mismatched parenthesis */
  132926. if( rc==SQLITE_OK && sParse.nNest ){
  132927. rc = SQLITE_ERROR;
  132928. }
  132929. return rc;
  132930. }
  132931. /*
  132932. ** Parameters z and n contain a pointer to and length of a buffer containing
  132933. ** an fts3 query expression, respectively. This function attempts to parse the
  132934. ** query expression and create a tree of Fts3Expr structures representing the
  132935. ** parsed expression. If successful, *ppExpr is set to point to the head
  132936. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  132937. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  132938. ** error) is returned and *ppExpr is set to 0.
  132939. **
  132940. ** If parameter n is a negative number, then z is assumed to point to a
  132941. ** nul-terminated string and the length is determined using strlen().
  132942. **
  132943. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  132944. ** use to normalize query tokens while parsing the expression. The azCol[]
  132945. ** array, which is assumed to contain nCol entries, should contain the names
  132946. ** of each column in the target fts3 table, in order from left to right.
  132947. ** Column names must be nul-terminated strings.
  132948. **
  132949. ** The iDefaultCol parameter should be passed the index of the table column
  132950. ** that appears on the left-hand-side of the MATCH operator (the default
  132951. ** column to match against for tokens for which a column name is not explicitly
  132952. ** specified as part of the query string), or -1 if tokens may by default
  132953. ** match any table column.
  132954. */
  132955. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  132956. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  132957. int iLangid, /* Language id for tokenizer */
  132958. char **azCol, /* Array of column names for fts3 table */
  132959. int bFts4, /* True to allow FTS4-only syntax */
  132960. int nCol, /* Number of entries in azCol[] */
  132961. int iDefaultCol, /* Default column to query */
  132962. const char *z, int n, /* Text of MATCH query */
  132963. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  132964. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  132965. ){
  132966. int rc = fts3ExprParseUnbalanced(
  132967. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  132968. );
  132969. /* Rebalance the expression. And check that its depth does not exceed
  132970. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  132971. if( rc==SQLITE_OK && *ppExpr ){
  132972. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  132973. if( rc==SQLITE_OK ){
  132974. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  132975. }
  132976. }
  132977. if( rc!=SQLITE_OK ){
  132978. sqlite3Fts3ExprFree(*ppExpr);
  132979. *ppExpr = 0;
  132980. if( rc==SQLITE_TOOBIG ){
  132981. sqlite3Fts3ErrMsg(pzErr,
  132982. "FTS expression tree is too large (maximum depth %d)",
  132983. SQLITE_FTS3_MAX_EXPR_DEPTH
  132984. );
  132985. rc = SQLITE_ERROR;
  132986. }else if( rc==SQLITE_ERROR ){
  132987. sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
  132988. }
  132989. }
  132990. return rc;
  132991. }
  132992. /*
  132993. ** Free a single node of an expression tree.
  132994. */
  132995. static void fts3FreeExprNode(Fts3Expr *p){
  132996. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  132997. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  132998. sqlite3_free(p->aMI);
  132999. sqlite3_free(p);
  133000. }
  133001. /*
  133002. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  133003. **
  133004. ** This function would be simpler if it recursively called itself. But
  133005. ** that would mean passing a sufficiently large expression to ExprParse()
  133006. ** could cause a stack overflow.
  133007. */
  133008. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  133009. Fts3Expr *p;
  133010. assert( pDel==0 || pDel->pParent==0 );
  133011. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  133012. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  133013. }
  133014. while( p ){
  133015. Fts3Expr *pParent = p->pParent;
  133016. fts3FreeExprNode(p);
  133017. if( pParent && p==pParent->pLeft && pParent->pRight ){
  133018. p = pParent->pRight;
  133019. while( p && (p->pLeft || p->pRight) ){
  133020. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  133021. p = (p->pLeft ? p->pLeft : p->pRight);
  133022. }
  133023. }else{
  133024. p = pParent;
  133025. }
  133026. }
  133027. }
  133028. /****************************************************************************
  133029. *****************************************************************************
  133030. ** Everything after this point is just test code.
  133031. */
  133032. #ifdef SQLITE_TEST
  133033. /* #include <stdio.h> */
  133034. /*
  133035. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  133036. */
  133037. static int queryTestTokenizer(
  133038. sqlite3 *db,
  133039. const char *zName,
  133040. const sqlite3_tokenizer_module **pp
  133041. ){
  133042. int rc;
  133043. sqlite3_stmt *pStmt;
  133044. const char zSql[] = "SELECT fts3_tokenizer(?)";
  133045. *pp = 0;
  133046. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  133047. if( rc!=SQLITE_OK ){
  133048. return rc;
  133049. }
  133050. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  133051. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  133052. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  133053. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  133054. }
  133055. }
  133056. return sqlite3_finalize(pStmt);
  133057. }
  133058. /*
  133059. ** Return a pointer to a buffer containing a text representation of the
  133060. ** expression passed as the first argument. The buffer is obtained from
  133061. ** sqlite3_malloc(). It is the responsibility of the caller to use
  133062. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  133063. ** NULL is returned.
  133064. **
  133065. ** If the second argument is not NULL, then its contents are prepended to
  133066. ** the returned expression text and then freed using sqlite3_free().
  133067. */
  133068. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  133069. if( pExpr==0 ){
  133070. return sqlite3_mprintf("");
  133071. }
  133072. switch( pExpr->eType ){
  133073. case FTSQUERY_PHRASE: {
  133074. Fts3Phrase *pPhrase = pExpr->pPhrase;
  133075. int i;
  133076. zBuf = sqlite3_mprintf(
  133077. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  133078. for(i=0; zBuf && i<pPhrase->nToken; i++){
  133079. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  133080. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  133081. (pPhrase->aToken[i].isPrefix?"+":"")
  133082. );
  133083. }
  133084. return zBuf;
  133085. }
  133086. case FTSQUERY_NEAR:
  133087. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  133088. break;
  133089. case FTSQUERY_NOT:
  133090. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  133091. break;
  133092. case FTSQUERY_AND:
  133093. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  133094. break;
  133095. case FTSQUERY_OR:
  133096. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  133097. break;
  133098. }
  133099. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  133100. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  133101. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  133102. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  133103. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  133104. return zBuf;
  133105. }
  133106. /*
  133107. ** This is the implementation of a scalar SQL function used to test the
  133108. ** expression parser. It should be called as follows:
  133109. **
  133110. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  133111. **
  133112. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  133113. ** to parse the query expression (see README.tokenizers). The second argument
  133114. ** is the query expression to parse. Each subsequent argument is the name
  133115. ** of a column of the fts3 table that the query expression may refer to.
  133116. ** For example:
  133117. **
  133118. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  133119. */
  133120. static void fts3ExprTest(
  133121. sqlite3_context *context,
  133122. int argc,
  133123. sqlite3_value **argv
  133124. ){
  133125. sqlite3_tokenizer_module const *pModule = 0;
  133126. sqlite3_tokenizer *pTokenizer = 0;
  133127. int rc;
  133128. char **azCol = 0;
  133129. const char *zExpr;
  133130. int nExpr;
  133131. int nCol;
  133132. int ii;
  133133. Fts3Expr *pExpr;
  133134. char *zBuf = 0;
  133135. sqlite3 *db = sqlite3_context_db_handle(context);
  133136. if( argc<3 ){
  133137. sqlite3_result_error(context,
  133138. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  133139. );
  133140. return;
  133141. }
  133142. rc = queryTestTokenizer(db,
  133143. (const char *)sqlite3_value_text(argv[0]), &pModule);
  133144. if( rc==SQLITE_NOMEM ){
  133145. sqlite3_result_error_nomem(context);
  133146. goto exprtest_out;
  133147. }else if( !pModule ){
  133148. sqlite3_result_error(context, "No such tokenizer module", -1);
  133149. goto exprtest_out;
  133150. }
  133151. rc = pModule->xCreate(0, 0, &pTokenizer);
  133152. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  133153. if( rc==SQLITE_NOMEM ){
  133154. sqlite3_result_error_nomem(context);
  133155. goto exprtest_out;
  133156. }
  133157. pTokenizer->pModule = pModule;
  133158. zExpr = (const char *)sqlite3_value_text(argv[1]);
  133159. nExpr = sqlite3_value_bytes(argv[1]);
  133160. nCol = argc-2;
  133161. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  133162. if( !azCol ){
  133163. sqlite3_result_error_nomem(context);
  133164. goto exprtest_out;
  133165. }
  133166. for(ii=0; ii<nCol; ii++){
  133167. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  133168. }
  133169. if( sqlite3_user_data(context) ){
  133170. char *zDummy = 0;
  133171. rc = sqlite3Fts3ExprParse(
  133172. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  133173. );
  133174. assert( rc==SQLITE_OK || pExpr==0 );
  133175. sqlite3_free(zDummy);
  133176. }else{
  133177. rc = fts3ExprParseUnbalanced(
  133178. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  133179. );
  133180. }
  133181. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  133182. sqlite3Fts3ExprFree(pExpr);
  133183. sqlite3_result_error(context, "Error parsing expression", -1);
  133184. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  133185. sqlite3_result_error_nomem(context);
  133186. }else{
  133187. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  133188. sqlite3_free(zBuf);
  133189. }
  133190. sqlite3Fts3ExprFree(pExpr);
  133191. exprtest_out:
  133192. if( pModule && pTokenizer ){
  133193. rc = pModule->xDestroy(pTokenizer);
  133194. }
  133195. sqlite3_free(azCol);
  133196. }
  133197. /*
  133198. ** Register the query expression parser test function fts3_exprtest()
  133199. ** with database connection db.
  133200. */
  133201. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  133202. int rc = sqlite3_create_function(
  133203. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  133204. );
  133205. if( rc==SQLITE_OK ){
  133206. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  133207. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  133208. );
  133209. }
  133210. return rc;
  133211. }
  133212. #endif
  133213. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  133214. /************** End of fts3_expr.c *******************************************/
  133215. /************** Begin file fts3_hash.c ***************************************/
  133216. /*
  133217. ** 2001 September 22
  133218. **
  133219. ** The author disclaims copyright to this source code. In place of
  133220. ** a legal notice, here is a blessing:
  133221. **
  133222. ** May you do good and not evil.
  133223. ** May you find forgiveness for yourself and forgive others.
  133224. ** May you share freely, never taking more than you give.
  133225. **
  133226. *************************************************************************
  133227. ** This is the implementation of generic hash-tables used in SQLite.
  133228. ** We've modified it slightly to serve as a standalone hash table
  133229. ** implementation for the full-text indexing module.
  133230. */
  133231. /*
  133232. ** The code in this file is only compiled if:
  133233. **
  133234. ** * The FTS3 module is being built as an extension
  133235. ** (in which case SQLITE_CORE is not defined), or
  133236. **
  133237. ** * The FTS3 module is being built into the core of
  133238. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  133239. */
  133240. /* #include "fts3Int.h" */
  133241. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  133242. /* #include <assert.h> */
  133243. /* #include <stdlib.h> */
  133244. /* #include <string.h> */
  133245. /* #include "fts3_hash.h" */
  133246. /*
  133247. ** Malloc and Free functions
  133248. */
  133249. static void *fts3HashMalloc(int n){
  133250. void *p = sqlite3_malloc(n);
  133251. if( p ){
  133252. memset(p, 0, n);
  133253. }
  133254. return p;
  133255. }
  133256. static void fts3HashFree(void *p){
  133257. sqlite3_free(p);
  133258. }
  133259. /* Turn bulk memory into a hash table object by initializing the
  133260. ** fields of the Hash structure.
  133261. **
  133262. ** "pNew" is a pointer to the hash table that is to be initialized.
  133263. ** keyClass is one of the constants
  133264. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  133265. ** determines what kind of key the hash table will use. "copyKey" is
  133266. ** true if the hash table should make its own private copy of keys and
  133267. ** false if it should just use the supplied pointer.
  133268. */
  133269. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  133270. assert( pNew!=0 );
  133271. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  133272. pNew->keyClass = keyClass;
  133273. pNew->copyKey = copyKey;
  133274. pNew->first = 0;
  133275. pNew->count = 0;
  133276. pNew->htsize = 0;
  133277. pNew->ht = 0;
  133278. }
  133279. /* Remove all entries from a hash table. Reclaim all memory.
  133280. ** Call this routine to delete a hash table or to reset a hash table
  133281. ** to the empty state.
  133282. */
  133283. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  133284. Fts3HashElem *elem; /* For looping over all elements of the table */
  133285. assert( pH!=0 );
  133286. elem = pH->first;
  133287. pH->first = 0;
  133288. fts3HashFree(pH->ht);
  133289. pH->ht = 0;
  133290. pH->htsize = 0;
  133291. while( elem ){
  133292. Fts3HashElem *next_elem = elem->next;
  133293. if( pH->copyKey && elem->pKey ){
  133294. fts3HashFree(elem->pKey);
  133295. }
  133296. fts3HashFree(elem);
  133297. elem = next_elem;
  133298. }
  133299. pH->count = 0;
  133300. }
  133301. /*
  133302. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  133303. */
  133304. static int fts3StrHash(const void *pKey, int nKey){
  133305. const char *z = (const char *)pKey;
  133306. unsigned h = 0;
  133307. if( nKey<=0 ) nKey = (int) strlen(z);
  133308. while( nKey > 0 ){
  133309. h = (h<<3) ^ h ^ *z++;
  133310. nKey--;
  133311. }
  133312. return (int)(h & 0x7fffffff);
  133313. }
  133314. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  133315. if( n1!=n2 ) return 1;
  133316. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  133317. }
  133318. /*
  133319. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  133320. */
  133321. static int fts3BinHash(const void *pKey, int nKey){
  133322. int h = 0;
  133323. const char *z = (const char *)pKey;
  133324. while( nKey-- > 0 ){
  133325. h = (h<<3) ^ h ^ *(z++);
  133326. }
  133327. return h & 0x7fffffff;
  133328. }
  133329. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  133330. if( n1!=n2 ) return 1;
  133331. return memcmp(pKey1,pKey2,n1);
  133332. }
  133333. /*
  133334. ** Return a pointer to the appropriate hash function given the key class.
  133335. **
  133336. ** The C syntax in this function definition may be unfamilar to some
  133337. ** programmers, so we provide the following additional explanation:
  133338. **
  133339. ** The name of the function is "ftsHashFunction". The function takes a
  133340. ** single parameter "keyClass". The return value of ftsHashFunction()
  133341. ** is a pointer to another function. Specifically, the return value
  133342. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  133343. ** with types "const void*" and "int" and returns an "int".
  133344. */
  133345. static int (*ftsHashFunction(int keyClass))(const void*,int){
  133346. if( keyClass==FTS3_HASH_STRING ){
  133347. return &fts3StrHash;
  133348. }else{
  133349. assert( keyClass==FTS3_HASH_BINARY );
  133350. return &fts3BinHash;
  133351. }
  133352. }
  133353. /*
  133354. ** Return a pointer to the appropriate hash function given the key class.
  133355. **
  133356. ** For help in interpreted the obscure C code in the function definition,
  133357. ** see the header comment on the previous function.
  133358. */
  133359. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  133360. if( keyClass==FTS3_HASH_STRING ){
  133361. return &fts3StrCompare;
  133362. }else{
  133363. assert( keyClass==FTS3_HASH_BINARY );
  133364. return &fts3BinCompare;
  133365. }
  133366. }
  133367. /* Link an element into the hash table
  133368. */
  133369. static void fts3HashInsertElement(
  133370. Fts3Hash *pH, /* The complete hash table */
  133371. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  133372. Fts3HashElem *pNew /* The element to be inserted */
  133373. ){
  133374. Fts3HashElem *pHead; /* First element already in pEntry */
  133375. pHead = pEntry->chain;
  133376. if( pHead ){
  133377. pNew->next = pHead;
  133378. pNew->prev = pHead->prev;
  133379. if( pHead->prev ){ pHead->prev->next = pNew; }
  133380. else { pH->first = pNew; }
  133381. pHead->prev = pNew;
  133382. }else{
  133383. pNew->next = pH->first;
  133384. if( pH->first ){ pH->first->prev = pNew; }
  133385. pNew->prev = 0;
  133386. pH->first = pNew;
  133387. }
  133388. pEntry->count++;
  133389. pEntry->chain = pNew;
  133390. }
  133391. /* Resize the hash table so that it cantains "new_size" buckets.
  133392. ** "new_size" must be a power of 2. The hash table might fail
  133393. ** to resize if sqliteMalloc() fails.
  133394. **
  133395. ** Return non-zero if a memory allocation error occurs.
  133396. */
  133397. static int fts3Rehash(Fts3Hash *pH, int new_size){
  133398. struct _fts3ht *new_ht; /* The new hash table */
  133399. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  133400. int (*xHash)(const void*,int); /* The hash function */
  133401. assert( (new_size & (new_size-1))==0 );
  133402. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  133403. if( new_ht==0 ) return 1;
  133404. fts3HashFree(pH->ht);
  133405. pH->ht = new_ht;
  133406. pH->htsize = new_size;
  133407. xHash = ftsHashFunction(pH->keyClass);
  133408. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  133409. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  133410. next_elem = elem->next;
  133411. fts3HashInsertElement(pH, &new_ht[h], elem);
  133412. }
  133413. return 0;
  133414. }
  133415. /* This function (for internal use only) locates an element in an
  133416. ** hash table that matches the given key. The hash for this key has
  133417. ** already been computed and is passed as the 4th parameter.
  133418. */
  133419. static Fts3HashElem *fts3FindElementByHash(
  133420. const Fts3Hash *pH, /* The pH to be searched */
  133421. const void *pKey, /* The key we are searching for */
  133422. int nKey,
  133423. int h /* The hash for this key. */
  133424. ){
  133425. Fts3HashElem *elem; /* Used to loop thru the element list */
  133426. int count; /* Number of elements left to test */
  133427. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  133428. if( pH->ht ){
  133429. struct _fts3ht *pEntry = &pH->ht[h];
  133430. elem = pEntry->chain;
  133431. count = pEntry->count;
  133432. xCompare = ftsCompareFunction(pH->keyClass);
  133433. while( count-- && elem ){
  133434. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  133435. return elem;
  133436. }
  133437. elem = elem->next;
  133438. }
  133439. }
  133440. return 0;
  133441. }
  133442. /* Remove a single entry from the hash table given a pointer to that
  133443. ** element and a hash on the element's key.
  133444. */
  133445. static void fts3RemoveElementByHash(
  133446. Fts3Hash *pH, /* The pH containing "elem" */
  133447. Fts3HashElem* elem, /* The element to be removed from the pH */
  133448. int h /* Hash value for the element */
  133449. ){
  133450. struct _fts3ht *pEntry;
  133451. if( elem->prev ){
  133452. elem->prev->next = elem->next;
  133453. }else{
  133454. pH->first = elem->next;
  133455. }
  133456. if( elem->next ){
  133457. elem->next->prev = elem->prev;
  133458. }
  133459. pEntry = &pH->ht[h];
  133460. if( pEntry->chain==elem ){
  133461. pEntry->chain = elem->next;
  133462. }
  133463. pEntry->count--;
  133464. if( pEntry->count<=0 ){
  133465. pEntry->chain = 0;
  133466. }
  133467. if( pH->copyKey && elem->pKey ){
  133468. fts3HashFree(elem->pKey);
  133469. }
  133470. fts3HashFree( elem );
  133471. pH->count--;
  133472. if( pH->count<=0 ){
  133473. assert( pH->first==0 );
  133474. assert( pH->count==0 );
  133475. fts3HashClear(pH);
  133476. }
  133477. }
  133478. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  133479. const Fts3Hash *pH,
  133480. const void *pKey,
  133481. int nKey
  133482. ){
  133483. int h; /* A hash on key */
  133484. int (*xHash)(const void*,int); /* The hash function */
  133485. if( pH==0 || pH->ht==0 ) return 0;
  133486. xHash = ftsHashFunction(pH->keyClass);
  133487. assert( xHash!=0 );
  133488. h = (*xHash)(pKey,nKey);
  133489. assert( (pH->htsize & (pH->htsize-1))==0 );
  133490. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  133491. }
  133492. /*
  133493. ** Attempt to locate an element of the hash table pH with a key
  133494. ** that matches pKey,nKey. Return the data for this element if it is
  133495. ** found, or NULL if there is no match.
  133496. */
  133497. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  133498. Fts3HashElem *pElem; /* The element that matches key (if any) */
  133499. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  133500. return pElem ? pElem->data : 0;
  133501. }
  133502. /* Insert an element into the hash table pH. The key is pKey,nKey
  133503. ** and the data is "data".
  133504. **
  133505. ** If no element exists with a matching key, then a new
  133506. ** element is created. A copy of the key is made if the copyKey
  133507. ** flag is set. NULL is returned.
  133508. **
  133509. ** If another element already exists with the same key, then the
  133510. ** new data replaces the old data and the old data is returned.
  133511. ** The key is not copied in this instance. If a malloc fails, then
  133512. ** the new data is returned and the hash table is unchanged.
  133513. **
  133514. ** If the "data" parameter to this function is NULL, then the
  133515. ** element corresponding to "key" is removed from the hash table.
  133516. */
  133517. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  133518. Fts3Hash *pH, /* The hash table to insert into */
  133519. const void *pKey, /* The key */
  133520. int nKey, /* Number of bytes in the key */
  133521. void *data /* The data */
  133522. ){
  133523. int hraw; /* Raw hash value of the key */
  133524. int h; /* the hash of the key modulo hash table size */
  133525. Fts3HashElem *elem; /* Used to loop thru the element list */
  133526. Fts3HashElem *new_elem; /* New element added to the pH */
  133527. int (*xHash)(const void*,int); /* The hash function */
  133528. assert( pH!=0 );
  133529. xHash = ftsHashFunction(pH->keyClass);
  133530. assert( xHash!=0 );
  133531. hraw = (*xHash)(pKey, nKey);
  133532. assert( (pH->htsize & (pH->htsize-1))==0 );
  133533. h = hraw & (pH->htsize-1);
  133534. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  133535. if( elem ){
  133536. void *old_data = elem->data;
  133537. if( data==0 ){
  133538. fts3RemoveElementByHash(pH,elem,h);
  133539. }else{
  133540. elem->data = data;
  133541. }
  133542. return old_data;
  133543. }
  133544. if( data==0 ) return 0;
  133545. if( (pH->htsize==0 && fts3Rehash(pH,8))
  133546. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  133547. ){
  133548. pH->count = 0;
  133549. return data;
  133550. }
  133551. assert( pH->htsize>0 );
  133552. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  133553. if( new_elem==0 ) return data;
  133554. if( pH->copyKey && pKey!=0 ){
  133555. new_elem->pKey = fts3HashMalloc( nKey );
  133556. if( new_elem->pKey==0 ){
  133557. fts3HashFree(new_elem);
  133558. return data;
  133559. }
  133560. memcpy((void*)new_elem->pKey, pKey, nKey);
  133561. }else{
  133562. new_elem->pKey = (void*)pKey;
  133563. }
  133564. new_elem->nKey = nKey;
  133565. pH->count++;
  133566. assert( pH->htsize>0 );
  133567. assert( (pH->htsize & (pH->htsize-1))==0 );
  133568. h = hraw & (pH->htsize-1);
  133569. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  133570. new_elem->data = data;
  133571. return 0;
  133572. }
  133573. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  133574. /************** End of fts3_hash.c *******************************************/
  133575. /************** Begin file fts3_porter.c *************************************/
  133576. /*
  133577. ** 2006 September 30
  133578. **
  133579. ** The author disclaims copyright to this source code. In place of
  133580. ** a legal notice, here is a blessing:
  133581. **
  133582. ** May you do good and not evil.
  133583. ** May you find forgiveness for yourself and forgive others.
  133584. ** May you share freely, never taking more than you give.
  133585. **
  133586. *************************************************************************
  133587. ** Implementation of the full-text-search tokenizer that implements
  133588. ** a Porter stemmer.
  133589. */
  133590. /*
  133591. ** The code in this file is only compiled if:
  133592. **
  133593. ** * The FTS3 module is being built as an extension
  133594. ** (in which case SQLITE_CORE is not defined), or
  133595. **
  133596. ** * The FTS3 module is being built into the core of
  133597. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  133598. */
  133599. /* #include "fts3Int.h" */
  133600. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  133601. /* #include <assert.h> */
  133602. /* #include <stdlib.h> */
  133603. /* #include <stdio.h> */
  133604. /* #include <string.h> */
  133605. /* #include "fts3_tokenizer.h" */
  133606. /*
  133607. ** Class derived from sqlite3_tokenizer
  133608. */
  133609. typedef struct porter_tokenizer {
  133610. sqlite3_tokenizer base; /* Base class */
  133611. } porter_tokenizer;
  133612. /*
  133613. ** Class derived from sqlite3_tokenizer_cursor
  133614. */
  133615. typedef struct porter_tokenizer_cursor {
  133616. sqlite3_tokenizer_cursor base;
  133617. const char *zInput; /* input we are tokenizing */
  133618. int nInput; /* size of the input */
  133619. int iOffset; /* current position in zInput */
  133620. int iToken; /* index of next token to be returned */
  133621. char *zToken; /* storage for current token */
  133622. int nAllocated; /* space allocated to zToken buffer */
  133623. } porter_tokenizer_cursor;
  133624. /*
  133625. ** Create a new tokenizer instance.
  133626. */
  133627. static int porterCreate(
  133628. int argc, const char * const *argv,
  133629. sqlite3_tokenizer **ppTokenizer
  133630. ){
  133631. porter_tokenizer *t;
  133632. UNUSED_PARAMETER(argc);
  133633. UNUSED_PARAMETER(argv);
  133634. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  133635. if( t==NULL ) return SQLITE_NOMEM;
  133636. memset(t, 0, sizeof(*t));
  133637. *ppTokenizer = &t->base;
  133638. return SQLITE_OK;
  133639. }
  133640. /*
  133641. ** Destroy a tokenizer
  133642. */
  133643. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  133644. sqlite3_free(pTokenizer);
  133645. return SQLITE_OK;
  133646. }
  133647. /*
  133648. ** Prepare to begin tokenizing a particular string. The input
  133649. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  133650. ** used to incrementally tokenize this string is returned in
  133651. ** *ppCursor.
  133652. */
  133653. static int porterOpen(
  133654. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  133655. const char *zInput, int nInput, /* String to be tokenized */
  133656. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  133657. ){
  133658. porter_tokenizer_cursor *c;
  133659. UNUSED_PARAMETER(pTokenizer);
  133660. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  133661. if( c==NULL ) return SQLITE_NOMEM;
  133662. c->zInput = zInput;
  133663. if( zInput==0 ){
  133664. c->nInput = 0;
  133665. }else if( nInput<0 ){
  133666. c->nInput = (int)strlen(zInput);
  133667. }else{
  133668. c->nInput = nInput;
  133669. }
  133670. c->iOffset = 0; /* start tokenizing at the beginning */
  133671. c->iToken = 0;
  133672. c->zToken = NULL; /* no space allocated, yet. */
  133673. c->nAllocated = 0;
  133674. *ppCursor = &c->base;
  133675. return SQLITE_OK;
  133676. }
  133677. /*
  133678. ** Close a tokenization cursor previously opened by a call to
  133679. ** porterOpen() above.
  133680. */
  133681. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  133682. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  133683. sqlite3_free(c->zToken);
  133684. sqlite3_free(c);
  133685. return SQLITE_OK;
  133686. }
  133687. /*
  133688. ** Vowel or consonant
  133689. */
  133690. static const char cType[] = {
  133691. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  133692. 1, 1, 1, 2, 1
  133693. };
  133694. /*
  133695. ** isConsonant() and isVowel() determine if their first character in
  133696. ** the string they point to is a consonant or a vowel, according
  133697. ** to Porter ruls.
  133698. **
  133699. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  133700. ** 'Y' is a consonant unless it follows another consonant,
  133701. ** in which case it is a vowel.
  133702. **
  133703. ** In these routine, the letters are in reverse order. So the 'y' rule
  133704. ** is that 'y' is a consonant unless it is followed by another
  133705. ** consonent.
  133706. */
  133707. static int isVowel(const char*);
  133708. static int isConsonant(const char *z){
  133709. int j;
  133710. char x = *z;
  133711. if( x==0 ) return 0;
  133712. assert( x>='a' && x<='z' );
  133713. j = cType[x-'a'];
  133714. if( j<2 ) return j;
  133715. return z[1]==0 || isVowel(z + 1);
  133716. }
  133717. static int isVowel(const char *z){
  133718. int j;
  133719. char x = *z;
  133720. if( x==0 ) return 0;
  133721. assert( x>='a' && x<='z' );
  133722. j = cType[x-'a'];
  133723. if( j<2 ) return 1-j;
  133724. return isConsonant(z + 1);
  133725. }
  133726. /*
  133727. ** Let any sequence of one or more vowels be represented by V and let
  133728. ** C be sequence of one or more consonants. Then every word can be
  133729. ** represented as:
  133730. **
  133731. ** [C] (VC){m} [V]
  133732. **
  133733. ** In prose: A word is an optional consonant followed by zero or
  133734. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  133735. ** number of vowel consonant pairs. This routine computes the value
  133736. ** of m for the first i bytes of a word.
  133737. **
  133738. ** Return true if the m-value for z is 1 or more. In other words,
  133739. ** return true if z contains at least one vowel that is followed
  133740. ** by a consonant.
  133741. **
  133742. ** In this routine z[] is in reverse order. So we are really looking
  133743. ** for an instance of a consonant followed by a vowel.
  133744. */
  133745. static int m_gt_0(const char *z){
  133746. while( isVowel(z) ){ z++; }
  133747. if( *z==0 ) return 0;
  133748. while( isConsonant(z) ){ z++; }
  133749. return *z!=0;
  133750. }
  133751. /* Like mgt0 above except we are looking for a value of m which is
  133752. ** exactly 1
  133753. */
  133754. static int m_eq_1(const char *z){
  133755. while( isVowel(z) ){ z++; }
  133756. if( *z==0 ) return 0;
  133757. while( isConsonant(z) ){ z++; }
  133758. if( *z==0 ) return 0;
  133759. while( isVowel(z) ){ z++; }
  133760. if( *z==0 ) return 1;
  133761. while( isConsonant(z) ){ z++; }
  133762. return *z==0;
  133763. }
  133764. /* Like mgt0 above except we are looking for a value of m>1 instead
  133765. ** or m>0
  133766. */
  133767. static int m_gt_1(const char *z){
  133768. while( isVowel(z) ){ z++; }
  133769. if( *z==0 ) return 0;
  133770. while( isConsonant(z) ){ z++; }
  133771. if( *z==0 ) return 0;
  133772. while( isVowel(z) ){ z++; }
  133773. if( *z==0 ) return 0;
  133774. while( isConsonant(z) ){ z++; }
  133775. return *z!=0;
  133776. }
  133777. /*
  133778. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  133779. */
  133780. static int hasVowel(const char *z){
  133781. while( isConsonant(z) ){ z++; }
  133782. return *z!=0;
  133783. }
  133784. /*
  133785. ** Return TRUE if the word ends in a double consonant.
  133786. **
  133787. ** The text is reversed here. So we are really looking at
  133788. ** the first two characters of z[].
  133789. */
  133790. static int doubleConsonant(const char *z){
  133791. return isConsonant(z) && z[0]==z[1];
  133792. }
  133793. /*
  133794. ** Return TRUE if the word ends with three letters which
  133795. ** are consonant-vowel-consonent and where the final consonant
  133796. ** is not 'w', 'x', or 'y'.
  133797. **
  133798. ** The word is reversed here. So we are really checking the
  133799. ** first three letters and the first one cannot be in [wxy].
  133800. */
  133801. static int star_oh(const char *z){
  133802. return
  133803. isConsonant(z) &&
  133804. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  133805. isVowel(z+1) &&
  133806. isConsonant(z+2);
  133807. }
  133808. /*
  133809. ** If the word ends with zFrom and xCond() is true for the stem
  133810. ** of the word that preceeds the zFrom ending, then change the
  133811. ** ending to zTo.
  133812. **
  133813. ** The input word *pz and zFrom are both in reverse order. zTo
  133814. ** is in normal order.
  133815. **
  133816. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  133817. ** match. Not that TRUE is returned even if xCond() fails and
  133818. ** no substitution occurs.
  133819. */
  133820. static int stem(
  133821. char **pz, /* The word being stemmed (Reversed) */
  133822. const char *zFrom, /* If the ending matches this... (Reversed) */
  133823. const char *zTo, /* ... change the ending to this (not reversed) */
  133824. int (*xCond)(const char*) /* Condition that must be true */
  133825. ){
  133826. char *z = *pz;
  133827. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  133828. if( *zFrom!=0 ) return 0;
  133829. if( xCond && !xCond(z) ) return 1;
  133830. while( *zTo ){
  133831. *(--z) = *(zTo++);
  133832. }
  133833. *pz = z;
  133834. return 1;
  133835. }
  133836. /*
  133837. ** This is the fallback stemmer used when the porter stemmer is
  133838. ** inappropriate. The input word is copied into the output with
  133839. ** US-ASCII case folding. If the input word is too long (more
  133840. ** than 20 bytes if it contains no digits or more than 6 bytes if
  133841. ** it contains digits) then word is truncated to 20 or 6 bytes
  133842. ** by taking 10 or 3 bytes from the beginning and end.
  133843. */
  133844. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  133845. int i, mx, j;
  133846. int hasDigit = 0;
  133847. for(i=0; i<nIn; i++){
  133848. char c = zIn[i];
  133849. if( c>='A' && c<='Z' ){
  133850. zOut[i] = c - 'A' + 'a';
  133851. }else{
  133852. if( c>='0' && c<='9' ) hasDigit = 1;
  133853. zOut[i] = c;
  133854. }
  133855. }
  133856. mx = hasDigit ? 3 : 10;
  133857. if( nIn>mx*2 ){
  133858. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  133859. zOut[j] = zOut[i];
  133860. }
  133861. i = j;
  133862. }
  133863. zOut[i] = 0;
  133864. *pnOut = i;
  133865. }
  133866. /*
  133867. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  133868. ** zOut is at least big enough to hold nIn bytes. Write the actual
  133869. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  133870. **
  133871. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  133872. ** are converted to lower case. Upper-case UTF characters are
  133873. ** unchanged.
  133874. **
  133875. ** Words that are longer than about 20 bytes are stemmed by retaining
  133876. ** a few bytes from the beginning and the end of the word. If the
  133877. ** word contains digits, 3 bytes are taken from the beginning and
  133878. ** 3 bytes from the end. For long words without digits, 10 bytes
  133879. ** are taken from each end. US-ASCII case folding still applies.
  133880. **
  133881. ** If the input word contains not digits but does characters not
  133882. ** in [a-zA-Z] then no stemming is attempted and this routine just
  133883. ** copies the input into the input into the output with US-ASCII
  133884. ** case folding.
  133885. **
  133886. ** Stemming never increases the length of the word. So there is
  133887. ** no chance of overflowing the zOut buffer.
  133888. */
  133889. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  133890. int i, j;
  133891. char zReverse[28];
  133892. char *z, *z2;
  133893. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  133894. /* The word is too big or too small for the porter stemmer.
  133895. ** Fallback to the copy stemmer */
  133896. copy_stemmer(zIn, nIn, zOut, pnOut);
  133897. return;
  133898. }
  133899. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  133900. char c = zIn[i];
  133901. if( c>='A' && c<='Z' ){
  133902. zReverse[j] = c + 'a' - 'A';
  133903. }else if( c>='a' && c<='z' ){
  133904. zReverse[j] = c;
  133905. }else{
  133906. /* The use of a character not in [a-zA-Z] means that we fallback
  133907. ** to the copy stemmer */
  133908. copy_stemmer(zIn, nIn, zOut, pnOut);
  133909. return;
  133910. }
  133911. }
  133912. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  133913. z = &zReverse[j+1];
  133914. /* Step 1a */
  133915. if( z[0]=='s' ){
  133916. if(
  133917. !stem(&z, "sess", "ss", 0) &&
  133918. !stem(&z, "sei", "i", 0) &&
  133919. !stem(&z, "ss", "ss", 0)
  133920. ){
  133921. z++;
  133922. }
  133923. }
  133924. /* Step 1b */
  133925. z2 = z;
  133926. if( stem(&z, "dee", "ee", m_gt_0) ){
  133927. /* Do nothing. The work was all in the test */
  133928. }else if(
  133929. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  133930. && z!=z2
  133931. ){
  133932. if( stem(&z, "ta", "ate", 0) ||
  133933. stem(&z, "lb", "ble", 0) ||
  133934. stem(&z, "zi", "ize", 0) ){
  133935. /* Do nothing. The work was all in the test */
  133936. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  133937. z++;
  133938. }else if( m_eq_1(z) && star_oh(z) ){
  133939. *(--z) = 'e';
  133940. }
  133941. }
  133942. /* Step 1c */
  133943. if( z[0]=='y' && hasVowel(z+1) ){
  133944. z[0] = 'i';
  133945. }
  133946. /* Step 2 */
  133947. switch( z[1] ){
  133948. case 'a':
  133949. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  133950. stem(&z, "lanoit", "tion", m_gt_0);
  133951. }
  133952. break;
  133953. case 'c':
  133954. if( !stem(&z, "icne", "ence", m_gt_0) ){
  133955. stem(&z, "icna", "ance", m_gt_0);
  133956. }
  133957. break;
  133958. case 'e':
  133959. stem(&z, "rezi", "ize", m_gt_0);
  133960. break;
  133961. case 'g':
  133962. stem(&z, "igol", "log", m_gt_0);
  133963. break;
  133964. case 'l':
  133965. if( !stem(&z, "ilb", "ble", m_gt_0)
  133966. && !stem(&z, "illa", "al", m_gt_0)
  133967. && !stem(&z, "iltne", "ent", m_gt_0)
  133968. && !stem(&z, "ile", "e", m_gt_0)
  133969. ){
  133970. stem(&z, "ilsuo", "ous", m_gt_0);
  133971. }
  133972. break;
  133973. case 'o':
  133974. if( !stem(&z, "noitazi", "ize", m_gt_0)
  133975. && !stem(&z, "noita", "ate", m_gt_0)
  133976. ){
  133977. stem(&z, "rota", "ate", m_gt_0);
  133978. }
  133979. break;
  133980. case 's':
  133981. if( !stem(&z, "msila", "al", m_gt_0)
  133982. && !stem(&z, "ssenevi", "ive", m_gt_0)
  133983. && !stem(&z, "ssenluf", "ful", m_gt_0)
  133984. ){
  133985. stem(&z, "ssensuo", "ous", m_gt_0);
  133986. }
  133987. break;
  133988. case 't':
  133989. if( !stem(&z, "itila", "al", m_gt_0)
  133990. && !stem(&z, "itivi", "ive", m_gt_0)
  133991. ){
  133992. stem(&z, "itilib", "ble", m_gt_0);
  133993. }
  133994. break;
  133995. }
  133996. /* Step 3 */
  133997. switch( z[0] ){
  133998. case 'e':
  133999. if( !stem(&z, "etaci", "ic", m_gt_0)
  134000. && !stem(&z, "evita", "", m_gt_0)
  134001. ){
  134002. stem(&z, "ezila", "al", m_gt_0);
  134003. }
  134004. break;
  134005. case 'i':
  134006. stem(&z, "itici", "ic", m_gt_0);
  134007. break;
  134008. case 'l':
  134009. if( !stem(&z, "laci", "ic", m_gt_0) ){
  134010. stem(&z, "luf", "", m_gt_0);
  134011. }
  134012. break;
  134013. case 's':
  134014. stem(&z, "ssen", "", m_gt_0);
  134015. break;
  134016. }
  134017. /* Step 4 */
  134018. switch( z[1] ){
  134019. case 'a':
  134020. if( z[0]=='l' && m_gt_1(z+2) ){
  134021. z += 2;
  134022. }
  134023. break;
  134024. case 'c':
  134025. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  134026. z += 4;
  134027. }
  134028. break;
  134029. case 'e':
  134030. if( z[0]=='r' && m_gt_1(z+2) ){
  134031. z += 2;
  134032. }
  134033. break;
  134034. case 'i':
  134035. if( z[0]=='c' && m_gt_1(z+2) ){
  134036. z += 2;
  134037. }
  134038. break;
  134039. case 'l':
  134040. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  134041. z += 4;
  134042. }
  134043. break;
  134044. case 'n':
  134045. if( z[0]=='t' ){
  134046. if( z[2]=='a' ){
  134047. if( m_gt_1(z+3) ){
  134048. z += 3;
  134049. }
  134050. }else if( z[2]=='e' ){
  134051. if( !stem(&z, "tneme", "", m_gt_1)
  134052. && !stem(&z, "tnem", "", m_gt_1)
  134053. ){
  134054. stem(&z, "tne", "", m_gt_1);
  134055. }
  134056. }
  134057. }
  134058. break;
  134059. case 'o':
  134060. if( z[0]=='u' ){
  134061. if( m_gt_1(z+2) ){
  134062. z += 2;
  134063. }
  134064. }else if( z[3]=='s' || z[3]=='t' ){
  134065. stem(&z, "noi", "", m_gt_1);
  134066. }
  134067. break;
  134068. case 's':
  134069. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  134070. z += 3;
  134071. }
  134072. break;
  134073. case 't':
  134074. if( !stem(&z, "eta", "", m_gt_1) ){
  134075. stem(&z, "iti", "", m_gt_1);
  134076. }
  134077. break;
  134078. case 'u':
  134079. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  134080. z += 3;
  134081. }
  134082. break;
  134083. case 'v':
  134084. case 'z':
  134085. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  134086. z += 3;
  134087. }
  134088. break;
  134089. }
  134090. /* Step 5a */
  134091. if( z[0]=='e' ){
  134092. if( m_gt_1(z+1) ){
  134093. z++;
  134094. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  134095. z++;
  134096. }
  134097. }
  134098. /* Step 5b */
  134099. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  134100. z++;
  134101. }
  134102. /* z[] is now the stemmed word in reverse order. Flip it back
  134103. ** around into forward order and return.
  134104. */
  134105. *pnOut = i = (int)strlen(z);
  134106. zOut[i] = 0;
  134107. while( *z ){
  134108. zOut[--i] = *(z++);
  134109. }
  134110. }
  134111. /*
  134112. ** Characters that can be part of a token. We assume any character
  134113. ** whose value is greater than 0x80 (any UTF character) can be
  134114. ** part of a token. In other words, delimiters all must have
  134115. ** values of 0x7f or lower.
  134116. */
  134117. static const char porterIdChar[] = {
  134118. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  134119. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  134120. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  134121. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  134122. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  134123. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  134124. };
  134125. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  134126. /*
  134127. ** Extract the next token from a tokenization cursor. The cursor must
  134128. ** have been opened by a prior call to porterOpen().
  134129. */
  134130. static int porterNext(
  134131. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  134132. const char **pzToken, /* OUT: *pzToken is the token text */
  134133. int *pnBytes, /* OUT: Number of bytes in token */
  134134. int *piStartOffset, /* OUT: Starting offset of token */
  134135. int *piEndOffset, /* OUT: Ending offset of token */
  134136. int *piPosition /* OUT: Position integer of token */
  134137. ){
  134138. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  134139. const char *z = c->zInput;
  134140. while( c->iOffset<c->nInput ){
  134141. int iStartOffset, ch;
  134142. /* Scan past delimiter characters */
  134143. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  134144. c->iOffset++;
  134145. }
  134146. /* Count non-delimiter characters. */
  134147. iStartOffset = c->iOffset;
  134148. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  134149. c->iOffset++;
  134150. }
  134151. if( c->iOffset>iStartOffset ){
  134152. int n = c->iOffset-iStartOffset;
  134153. if( n>c->nAllocated ){
  134154. char *pNew;
  134155. c->nAllocated = n+20;
  134156. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  134157. if( !pNew ) return SQLITE_NOMEM;
  134158. c->zToken = pNew;
  134159. }
  134160. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  134161. *pzToken = c->zToken;
  134162. *piStartOffset = iStartOffset;
  134163. *piEndOffset = c->iOffset;
  134164. *piPosition = c->iToken++;
  134165. return SQLITE_OK;
  134166. }
  134167. }
  134168. return SQLITE_DONE;
  134169. }
  134170. /*
  134171. ** The set of routines that implement the porter-stemmer tokenizer
  134172. */
  134173. static const sqlite3_tokenizer_module porterTokenizerModule = {
  134174. 0,
  134175. porterCreate,
  134176. porterDestroy,
  134177. porterOpen,
  134178. porterClose,
  134179. porterNext,
  134180. 0
  134181. };
  134182. /*
  134183. ** Allocate a new porter tokenizer. Return a pointer to the new
  134184. ** tokenizer in *ppModule
  134185. */
  134186. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  134187. sqlite3_tokenizer_module const**ppModule
  134188. ){
  134189. *ppModule = &porterTokenizerModule;
  134190. }
  134191. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  134192. /************** End of fts3_porter.c *****************************************/
  134193. /************** Begin file fts3_tokenizer.c **********************************/
  134194. /*
  134195. ** 2007 June 22
  134196. **
  134197. ** The author disclaims copyright to this source code. In place of
  134198. ** a legal notice, here is a blessing:
  134199. **
  134200. ** May you do good and not evil.
  134201. ** May you find forgiveness for yourself and forgive others.
  134202. ** May you share freely, never taking more than you give.
  134203. **
  134204. ******************************************************************************
  134205. **
  134206. ** This is part of an SQLite module implementing full-text search.
  134207. ** This particular file implements the generic tokenizer interface.
  134208. */
  134209. /*
  134210. ** The code in this file is only compiled if:
  134211. **
  134212. ** * The FTS3 module is being built as an extension
  134213. ** (in which case SQLITE_CORE is not defined), or
  134214. **
  134215. ** * The FTS3 module is being built into the core of
  134216. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  134217. */
  134218. /* #include "fts3Int.h" */
  134219. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  134220. /* #include <assert.h> */
  134221. /* #include <string.h> */
  134222. /*
  134223. ** Implementation of the SQL scalar function for accessing the underlying
  134224. ** hash table. This function may be called as follows:
  134225. **
  134226. ** SELECT <function-name>(<key-name>);
  134227. ** SELECT <function-name>(<key-name>, <pointer>);
  134228. **
  134229. ** where <function-name> is the name passed as the second argument
  134230. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  134231. **
  134232. ** If the <pointer> argument is specified, it must be a blob value
  134233. ** containing a pointer to be stored as the hash data corresponding
  134234. ** to the string <key-name>. If <pointer> is not specified, then
  134235. ** the string <key-name> must already exist in the has table. Otherwise,
  134236. ** an error is returned.
  134237. **
  134238. ** Whether or not the <pointer> argument is specified, the value returned
  134239. ** is a blob containing the pointer stored as the hash data corresponding
  134240. ** to string <key-name> (after the hash-table is updated, if applicable).
  134241. */
  134242. static void scalarFunc(
  134243. sqlite3_context *context,
  134244. int argc,
  134245. sqlite3_value **argv
  134246. ){
  134247. Fts3Hash *pHash;
  134248. void *pPtr = 0;
  134249. const unsigned char *zName;
  134250. int nName;
  134251. assert( argc==1 || argc==2 );
  134252. pHash = (Fts3Hash *)sqlite3_user_data(context);
  134253. zName = sqlite3_value_text(argv[0]);
  134254. nName = sqlite3_value_bytes(argv[0])+1;
  134255. if( argc==2 ){
  134256. void *pOld;
  134257. int n = sqlite3_value_bytes(argv[1]);
  134258. if( zName==0 || n!=sizeof(pPtr) ){
  134259. sqlite3_result_error(context, "argument type mismatch", -1);
  134260. return;
  134261. }
  134262. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  134263. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  134264. if( pOld==pPtr ){
  134265. sqlite3_result_error(context, "out of memory", -1);
  134266. return;
  134267. }
  134268. }else{
  134269. if( zName ){
  134270. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  134271. }
  134272. if( !pPtr ){
  134273. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  134274. sqlite3_result_error(context, zErr, -1);
  134275. sqlite3_free(zErr);
  134276. return;
  134277. }
  134278. }
  134279. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  134280. }
  134281. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  134282. static const char isFtsIdChar[] = {
  134283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  134284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  134285. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  134286. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  134287. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  134288. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  134289. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  134290. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  134291. };
  134292. return (c&0x80 || isFtsIdChar[(int)(c)]);
  134293. }
  134294. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  134295. const char *z1;
  134296. const char *z2 = 0;
  134297. /* Find the start of the next token. */
  134298. z1 = zStr;
  134299. while( z2==0 ){
  134300. char c = *z1;
  134301. switch( c ){
  134302. case '\0': return 0; /* No more tokens here */
  134303. case '\'':
  134304. case '"':
  134305. case '`': {
  134306. z2 = z1;
  134307. while( *++z2 && (*z2!=c || *++z2==c) );
  134308. break;
  134309. }
  134310. case '[':
  134311. z2 = &z1[1];
  134312. while( *z2 && z2[0]!=']' ) z2++;
  134313. if( *z2 ) z2++;
  134314. break;
  134315. default:
  134316. if( sqlite3Fts3IsIdChar(*z1) ){
  134317. z2 = &z1[1];
  134318. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  134319. }else{
  134320. z1++;
  134321. }
  134322. }
  134323. }
  134324. *pn = (int)(z2-z1);
  134325. return z1;
  134326. }
  134327. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  134328. Fts3Hash *pHash, /* Tokenizer hash table */
  134329. const char *zArg, /* Tokenizer name */
  134330. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  134331. char **pzErr /* OUT: Set to malloced error message */
  134332. ){
  134333. int rc;
  134334. char *z = (char *)zArg;
  134335. int n = 0;
  134336. char *zCopy;
  134337. char *zEnd; /* Pointer to nul-term of zCopy */
  134338. sqlite3_tokenizer_module *m;
  134339. zCopy = sqlite3_mprintf("%s", zArg);
  134340. if( !zCopy ) return SQLITE_NOMEM;
  134341. zEnd = &zCopy[strlen(zCopy)];
  134342. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  134343. if( z==0 ){
  134344. assert( n==0 );
  134345. z = zCopy;
  134346. }
  134347. z[n] = '\0';
  134348. sqlite3Fts3Dequote(z);
  134349. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  134350. if( !m ){
  134351. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
  134352. rc = SQLITE_ERROR;
  134353. }else{
  134354. char const **aArg = 0;
  134355. int iArg = 0;
  134356. z = &z[n+1];
  134357. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  134358. int nNew = sizeof(char *)*(iArg+1);
  134359. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  134360. if( !aNew ){
  134361. sqlite3_free(zCopy);
  134362. sqlite3_free((void *)aArg);
  134363. return SQLITE_NOMEM;
  134364. }
  134365. aArg = aNew;
  134366. aArg[iArg++] = z;
  134367. z[n] = '\0';
  134368. sqlite3Fts3Dequote(z);
  134369. z = &z[n+1];
  134370. }
  134371. rc = m->xCreate(iArg, aArg, ppTok);
  134372. assert( rc!=SQLITE_OK || *ppTok );
  134373. if( rc!=SQLITE_OK ){
  134374. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
  134375. }else{
  134376. (*ppTok)->pModule = m;
  134377. }
  134378. sqlite3_free((void *)aArg);
  134379. }
  134380. sqlite3_free(zCopy);
  134381. return rc;
  134382. }
  134383. #ifdef SQLITE_TEST
  134384. #include <tcl.h>
  134385. /* #include <string.h> */
  134386. /*
  134387. ** Implementation of a special SQL scalar function for testing tokenizers
  134388. ** designed to be used in concert with the Tcl testing framework. This
  134389. ** function must be called with two or more arguments:
  134390. **
  134391. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  134392. **
  134393. ** where <function-name> is the name passed as the second argument
  134394. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  134395. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  134396. **
  134397. ** The return value is a string that may be interpreted as a Tcl
  134398. ** list. For each token in the <input-string>, three elements are
  134399. ** added to the returned list. The first is the token position, the
  134400. ** second is the token text (folded, stemmed, etc.) and the third is the
  134401. ** substring of <input-string> associated with the token. For example,
  134402. ** using the built-in "simple" tokenizer:
  134403. **
  134404. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  134405. **
  134406. ** will return the string:
  134407. **
  134408. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  134409. **
  134410. */
  134411. static void testFunc(
  134412. sqlite3_context *context,
  134413. int argc,
  134414. sqlite3_value **argv
  134415. ){
  134416. Fts3Hash *pHash;
  134417. sqlite3_tokenizer_module *p;
  134418. sqlite3_tokenizer *pTokenizer = 0;
  134419. sqlite3_tokenizer_cursor *pCsr = 0;
  134420. const char *zErr = 0;
  134421. const char *zName;
  134422. int nName;
  134423. const char *zInput;
  134424. int nInput;
  134425. const char *azArg[64];
  134426. const char *zToken;
  134427. int nToken = 0;
  134428. int iStart = 0;
  134429. int iEnd = 0;
  134430. int iPos = 0;
  134431. int i;
  134432. Tcl_Obj *pRet;
  134433. if( argc<2 ){
  134434. sqlite3_result_error(context, "insufficient arguments", -1);
  134435. return;
  134436. }
  134437. nName = sqlite3_value_bytes(argv[0]);
  134438. zName = (const char *)sqlite3_value_text(argv[0]);
  134439. nInput = sqlite3_value_bytes(argv[argc-1]);
  134440. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  134441. pHash = (Fts3Hash *)sqlite3_user_data(context);
  134442. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  134443. if( !p ){
  134444. char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
  134445. sqlite3_result_error(context, zErr2, -1);
  134446. sqlite3_free(zErr2);
  134447. return;
  134448. }
  134449. pRet = Tcl_NewObj();
  134450. Tcl_IncrRefCount(pRet);
  134451. for(i=1; i<argc-1; i++){
  134452. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  134453. }
  134454. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  134455. zErr = "error in xCreate()";
  134456. goto finish;
  134457. }
  134458. pTokenizer->pModule = p;
  134459. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  134460. zErr = "error in xOpen()";
  134461. goto finish;
  134462. }
  134463. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  134464. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  134465. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  134466. zToken = &zInput[iStart];
  134467. nToken = iEnd-iStart;
  134468. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  134469. }
  134470. if( SQLITE_OK!=p->xClose(pCsr) ){
  134471. zErr = "error in xClose()";
  134472. goto finish;
  134473. }
  134474. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  134475. zErr = "error in xDestroy()";
  134476. goto finish;
  134477. }
  134478. finish:
  134479. if( zErr ){
  134480. sqlite3_result_error(context, zErr, -1);
  134481. }else{
  134482. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  134483. }
  134484. Tcl_DecrRefCount(pRet);
  134485. }
  134486. static
  134487. int registerTokenizer(
  134488. sqlite3 *db,
  134489. char *zName,
  134490. const sqlite3_tokenizer_module *p
  134491. ){
  134492. int rc;
  134493. sqlite3_stmt *pStmt;
  134494. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  134495. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  134496. if( rc!=SQLITE_OK ){
  134497. return rc;
  134498. }
  134499. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  134500. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  134501. sqlite3_step(pStmt);
  134502. return sqlite3_finalize(pStmt);
  134503. }
  134504. static
  134505. int queryTokenizer(
  134506. sqlite3 *db,
  134507. char *zName,
  134508. const sqlite3_tokenizer_module **pp
  134509. ){
  134510. int rc;
  134511. sqlite3_stmt *pStmt;
  134512. const char zSql[] = "SELECT fts3_tokenizer(?)";
  134513. *pp = 0;
  134514. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  134515. if( rc!=SQLITE_OK ){
  134516. return rc;
  134517. }
  134518. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  134519. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  134520. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  134521. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  134522. }
  134523. }
  134524. return sqlite3_finalize(pStmt);
  134525. }
  134526. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  134527. /*
  134528. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  134529. ** This function is used for testing only, it is not included in the
  134530. ** build unless SQLITE_TEST is defined.
  134531. **
  134532. ** The purpose of this is to test that the fts3_tokenizer() function
  134533. ** can be used as designed by the C-code in the queryTokenizer and
  134534. ** registerTokenizer() functions above. These two functions are repeated
  134535. ** in the README.tokenizer file as an example, so it is important to
  134536. ** test them.
  134537. **
  134538. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  134539. ** function with no arguments. An assert() will fail if a problem is
  134540. ** detected. i.e.:
  134541. **
  134542. ** SELECT fts3_tokenizer_internal_test();
  134543. **
  134544. */
  134545. static void intTestFunc(
  134546. sqlite3_context *context,
  134547. int argc,
  134548. sqlite3_value **argv
  134549. ){
  134550. int rc;
  134551. const sqlite3_tokenizer_module *p1;
  134552. const sqlite3_tokenizer_module *p2;
  134553. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  134554. UNUSED_PARAMETER(argc);
  134555. UNUSED_PARAMETER(argv);
  134556. /* Test the query function */
  134557. sqlite3Fts3SimpleTokenizerModule(&p1);
  134558. rc = queryTokenizer(db, "simple", &p2);
  134559. assert( rc==SQLITE_OK );
  134560. assert( p1==p2 );
  134561. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  134562. assert( rc==SQLITE_ERROR );
  134563. assert( p2==0 );
  134564. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  134565. /* Test the storage function */
  134566. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  134567. assert( rc==SQLITE_OK );
  134568. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  134569. assert( rc==SQLITE_OK );
  134570. assert( p2==p1 );
  134571. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  134572. }
  134573. #endif
  134574. /*
  134575. ** Set up SQL objects in database db used to access the contents of
  134576. ** the hash table pointed to by argument pHash. The hash table must
  134577. ** been initialized to use string keys, and to take a private copy
  134578. ** of the key when a value is inserted. i.e. by a call similar to:
  134579. **
  134580. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  134581. **
  134582. ** This function adds a scalar function (see header comment above
  134583. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  134584. ** defined at compilation time, a temporary virtual table (see header
  134585. ** comment above struct HashTableVtab) to the database schema. Both
  134586. ** provide read/write access to the contents of *pHash.
  134587. **
  134588. ** The third argument to this function, zName, is used as the name
  134589. ** of both the scalar and, if created, the virtual table.
  134590. */
  134591. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  134592. sqlite3 *db,
  134593. Fts3Hash *pHash,
  134594. const char *zName
  134595. ){
  134596. int rc = SQLITE_OK;
  134597. void *p = (void *)pHash;
  134598. const int any = SQLITE_ANY;
  134599. #ifdef SQLITE_TEST
  134600. char *zTest = 0;
  134601. char *zTest2 = 0;
  134602. void *pdb = (void *)db;
  134603. zTest = sqlite3_mprintf("%s_test", zName);
  134604. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  134605. if( !zTest || !zTest2 ){
  134606. rc = SQLITE_NOMEM;
  134607. }
  134608. #endif
  134609. if( SQLITE_OK==rc ){
  134610. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  134611. }
  134612. if( SQLITE_OK==rc ){
  134613. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  134614. }
  134615. #ifdef SQLITE_TEST
  134616. if( SQLITE_OK==rc ){
  134617. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  134618. }
  134619. if( SQLITE_OK==rc ){
  134620. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  134621. }
  134622. #endif
  134623. #ifdef SQLITE_TEST
  134624. sqlite3_free(zTest);
  134625. sqlite3_free(zTest2);
  134626. #endif
  134627. return rc;
  134628. }
  134629. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  134630. /************** End of fts3_tokenizer.c **************************************/
  134631. /************** Begin file fts3_tokenizer1.c *********************************/
  134632. /*
  134633. ** 2006 Oct 10
  134634. **
  134635. ** The author disclaims copyright to this source code. In place of
  134636. ** a legal notice, here is a blessing:
  134637. **
  134638. ** May you do good and not evil.
  134639. ** May you find forgiveness for yourself and forgive others.
  134640. ** May you share freely, never taking more than you give.
  134641. **
  134642. ******************************************************************************
  134643. **
  134644. ** Implementation of the "simple" full-text-search tokenizer.
  134645. */
  134646. /*
  134647. ** The code in this file is only compiled if:
  134648. **
  134649. ** * The FTS3 module is being built as an extension
  134650. ** (in which case SQLITE_CORE is not defined), or
  134651. **
  134652. ** * The FTS3 module is being built into the core of
  134653. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  134654. */
  134655. /* #include "fts3Int.h" */
  134656. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  134657. /* #include <assert.h> */
  134658. /* #include <stdlib.h> */
  134659. /* #include <stdio.h> */
  134660. /* #include <string.h> */
  134661. /* #include "fts3_tokenizer.h" */
  134662. typedef struct simple_tokenizer {
  134663. sqlite3_tokenizer base;
  134664. char delim[128]; /* flag ASCII delimiters */
  134665. } simple_tokenizer;
  134666. typedef struct simple_tokenizer_cursor {
  134667. sqlite3_tokenizer_cursor base;
  134668. const char *pInput; /* input we are tokenizing */
  134669. int nBytes; /* size of the input */
  134670. int iOffset; /* current position in pInput */
  134671. int iToken; /* index of next token to be returned */
  134672. char *pToken; /* storage for current token */
  134673. int nTokenAllocated; /* space allocated to zToken buffer */
  134674. } simple_tokenizer_cursor;
  134675. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  134676. return c<0x80 && t->delim[c];
  134677. }
  134678. static int fts3_isalnum(int x){
  134679. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  134680. }
  134681. /*
  134682. ** Create a new tokenizer instance.
  134683. */
  134684. static int simpleCreate(
  134685. int argc, const char * const *argv,
  134686. sqlite3_tokenizer **ppTokenizer
  134687. ){
  134688. simple_tokenizer *t;
  134689. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  134690. if( t==NULL ) return SQLITE_NOMEM;
  134691. memset(t, 0, sizeof(*t));
  134692. /* TODO(shess) Delimiters need to remain the same from run to run,
  134693. ** else we need to reindex. One solution would be a meta-table to
  134694. ** track such information in the database, then we'd only want this
  134695. ** information on the initial create.
  134696. */
  134697. if( argc>1 ){
  134698. int i, n = (int)strlen(argv[1]);
  134699. for(i=0; i<n; i++){
  134700. unsigned char ch = argv[1][i];
  134701. /* We explicitly don't support UTF-8 delimiters for now. */
  134702. if( ch>=0x80 ){
  134703. sqlite3_free(t);
  134704. return SQLITE_ERROR;
  134705. }
  134706. t->delim[ch] = 1;
  134707. }
  134708. } else {
  134709. /* Mark non-alphanumeric ASCII characters as delimiters */
  134710. int i;
  134711. for(i=1; i<0x80; i++){
  134712. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  134713. }
  134714. }
  134715. *ppTokenizer = &t->base;
  134716. return SQLITE_OK;
  134717. }
  134718. /*
  134719. ** Destroy a tokenizer
  134720. */
  134721. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  134722. sqlite3_free(pTokenizer);
  134723. return SQLITE_OK;
  134724. }
  134725. /*
  134726. ** Prepare to begin tokenizing a particular string. The input
  134727. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  134728. ** used to incrementally tokenize this string is returned in
  134729. ** *ppCursor.
  134730. */
  134731. static int simpleOpen(
  134732. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  134733. const char *pInput, int nBytes, /* String to be tokenized */
  134734. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  134735. ){
  134736. simple_tokenizer_cursor *c;
  134737. UNUSED_PARAMETER(pTokenizer);
  134738. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  134739. if( c==NULL ) return SQLITE_NOMEM;
  134740. c->pInput = pInput;
  134741. if( pInput==0 ){
  134742. c->nBytes = 0;
  134743. }else if( nBytes<0 ){
  134744. c->nBytes = (int)strlen(pInput);
  134745. }else{
  134746. c->nBytes = nBytes;
  134747. }
  134748. c->iOffset = 0; /* start tokenizing at the beginning */
  134749. c->iToken = 0;
  134750. c->pToken = NULL; /* no space allocated, yet. */
  134751. c->nTokenAllocated = 0;
  134752. *ppCursor = &c->base;
  134753. return SQLITE_OK;
  134754. }
  134755. /*
  134756. ** Close a tokenization cursor previously opened by a call to
  134757. ** simpleOpen() above.
  134758. */
  134759. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  134760. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  134761. sqlite3_free(c->pToken);
  134762. sqlite3_free(c);
  134763. return SQLITE_OK;
  134764. }
  134765. /*
  134766. ** Extract the next token from a tokenization cursor. The cursor must
  134767. ** have been opened by a prior call to simpleOpen().
  134768. */
  134769. static int simpleNext(
  134770. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  134771. const char **ppToken, /* OUT: *ppToken is the token text */
  134772. int *pnBytes, /* OUT: Number of bytes in token */
  134773. int *piStartOffset, /* OUT: Starting offset of token */
  134774. int *piEndOffset, /* OUT: Ending offset of token */
  134775. int *piPosition /* OUT: Position integer of token */
  134776. ){
  134777. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  134778. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  134779. unsigned char *p = (unsigned char *)c->pInput;
  134780. while( c->iOffset<c->nBytes ){
  134781. int iStartOffset;
  134782. /* Scan past delimiter characters */
  134783. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  134784. c->iOffset++;
  134785. }
  134786. /* Count non-delimiter characters. */
  134787. iStartOffset = c->iOffset;
  134788. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  134789. c->iOffset++;
  134790. }
  134791. if( c->iOffset>iStartOffset ){
  134792. int i, n = c->iOffset-iStartOffset;
  134793. if( n>c->nTokenAllocated ){
  134794. char *pNew;
  134795. c->nTokenAllocated = n+20;
  134796. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  134797. if( !pNew ) return SQLITE_NOMEM;
  134798. c->pToken = pNew;
  134799. }
  134800. for(i=0; i<n; i++){
  134801. /* TODO(shess) This needs expansion to handle UTF-8
  134802. ** case-insensitivity.
  134803. */
  134804. unsigned char ch = p[iStartOffset+i];
  134805. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  134806. }
  134807. *ppToken = c->pToken;
  134808. *pnBytes = n;
  134809. *piStartOffset = iStartOffset;
  134810. *piEndOffset = c->iOffset;
  134811. *piPosition = c->iToken++;
  134812. return SQLITE_OK;
  134813. }
  134814. }
  134815. return SQLITE_DONE;
  134816. }
  134817. /*
  134818. ** The set of routines that implement the simple tokenizer
  134819. */
  134820. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  134821. 0,
  134822. simpleCreate,
  134823. simpleDestroy,
  134824. simpleOpen,
  134825. simpleClose,
  134826. simpleNext,
  134827. 0,
  134828. };
  134829. /*
  134830. ** Allocate a new simple tokenizer. Return a pointer to the new
  134831. ** tokenizer in *ppModule
  134832. */
  134833. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  134834. sqlite3_tokenizer_module const**ppModule
  134835. ){
  134836. *ppModule = &simpleTokenizerModule;
  134837. }
  134838. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  134839. /************** End of fts3_tokenizer1.c *************************************/
  134840. /************** Begin file fts3_tokenize_vtab.c ******************************/
  134841. /*
  134842. ** 2013 Apr 22
  134843. **
  134844. ** The author disclaims copyright to this source code. In place of
  134845. ** a legal notice, here is a blessing:
  134846. **
  134847. ** May you do good and not evil.
  134848. ** May you find forgiveness for yourself and forgive others.
  134849. ** May you share freely, never taking more than you give.
  134850. **
  134851. ******************************************************************************
  134852. **
  134853. ** This file contains code for the "fts3tokenize" virtual table module.
  134854. ** An fts3tokenize virtual table is created as follows:
  134855. **
  134856. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  134857. ** <tokenizer-name>, <arg-1>, ...
  134858. ** );
  134859. **
  134860. ** The table created has the following schema:
  134861. **
  134862. ** CREATE TABLE <tbl>(input, token, start, end, position)
  134863. **
  134864. ** When queried, the query must include a WHERE clause of type:
  134865. **
  134866. ** input = <string>
  134867. **
  134868. ** The virtual table module tokenizes this <string>, using the FTS3
  134869. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  134870. ** statement and returns one row for each token in the result. With
  134871. ** fields set as follows:
  134872. **
  134873. ** input: Always set to a copy of <string>
  134874. ** token: A token from the input.
  134875. ** start: Byte offset of the token within the input <string>.
  134876. ** end: Byte offset of the byte immediately following the end of the
  134877. ** token within the input string.
  134878. ** pos: Token offset of token within input.
  134879. **
  134880. */
  134881. /* #include "fts3Int.h" */
  134882. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  134883. /* #include <string.h> */
  134884. /* #include <assert.h> */
  134885. typedef struct Fts3tokTable Fts3tokTable;
  134886. typedef struct Fts3tokCursor Fts3tokCursor;
  134887. /*
  134888. ** Virtual table structure.
  134889. */
  134890. struct Fts3tokTable {
  134891. sqlite3_vtab base; /* Base class used by SQLite core */
  134892. const sqlite3_tokenizer_module *pMod;
  134893. sqlite3_tokenizer *pTok;
  134894. };
  134895. /*
  134896. ** Virtual table cursor structure.
  134897. */
  134898. struct Fts3tokCursor {
  134899. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  134900. char *zInput; /* Input string */
  134901. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  134902. int iRowid; /* Current 'rowid' value */
  134903. const char *zToken; /* Current 'token' value */
  134904. int nToken; /* Size of zToken in bytes */
  134905. int iStart; /* Current 'start' value */
  134906. int iEnd; /* Current 'end' value */
  134907. int iPos; /* Current 'pos' value */
  134908. };
  134909. /*
  134910. ** Query FTS for the tokenizer implementation named zName.
  134911. */
  134912. static int fts3tokQueryTokenizer(
  134913. Fts3Hash *pHash,
  134914. const char *zName,
  134915. const sqlite3_tokenizer_module **pp,
  134916. char **pzErr
  134917. ){
  134918. sqlite3_tokenizer_module *p;
  134919. int nName = (int)strlen(zName);
  134920. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  134921. if( !p ){
  134922. sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
  134923. return SQLITE_ERROR;
  134924. }
  134925. *pp = p;
  134926. return SQLITE_OK;
  134927. }
  134928. /*
  134929. ** The second argument, argv[], is an array of pointers to nul-terminated
  134930. ** strings. This function makes a copy of the array and strings into a
  134931. ** single block of memory. It then dequotes any of the strings that appear
  134932. ** to be quoted.
  134933. **
  134934. ** If successful, output parameter *pazDequote is set to point at the
  134935. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  134936. ** responsible for eventually calling sqlite3_free() to free the array
  134937. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  134938. ** The final value of *pazDequote is undefined in this case.
  134939. */
  134940. static int fts3tokDequoteArray(
  134941. int argc, /* Number of elements in argv[] */
  134942. const char * const *argv, /* Input array */
  134943. char ***pazDequote /* Output array */
  134944. ){
  134945. int rc = SQLITE_OK; /* Return code */
  134946. if( argc==0 ){
  134947. *pazDequote = 0;
  134948. }else{
  134949. int i;
  134950. int nByte = 0;
  134951. char **azDequote;
  134952. for(i=0; i<argc; i++){
  134953. nByte += (int)(strlen(argv[i]) + 1);
  134954. }
  134955. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  134956. if( azDequote==0 ){
  134957. rc = SQLITE_NOMEM;
  134958. }else{
  134959. char *pSpace = (char *)&azDequote[argc];
  134960. for(i=0; i<argc; i++){
  134961. int n = (int)strlen(argv[i]);
  134962. azDequote[i] = pSpace;
  134963. memcpy(pSpace, argv[i], n+1);
  134964. sqlite3Fts3Dequote(pSpace);
  134965. pSpace += (n+1);
  134966. }
  134967. }
  134968. }
  134969. return rc;
  134970. }
  134971. /*
  134972. ** Schema of the tokenizer table.
  134973. */
  134974. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  134975. /*
  134976. ** This function does all the work for both the xConnect and xCreate methods.
  134977. ** These tables have no persistent representation of their own, so xConnect
  134978. ** and xCreate are identical operations.
  134979. **
  134980. ** argv[0]: module name
  134981. ** argv[1]: database name
  134982. ** argv[2]: table name
  134983. ** argv[3]: first argument (tokenizer name)
  134984. */
  134985. static int fts3tokConnectMethod(
  134986. sqlite3 *db, /* Database connection */
  134987. void *pHash, /* Hash table of tokenizers */
  134988. int argc, /* Number of elements in argv array */
  134989. const char * const *argv, /* xCreate/xConnect argument array */
  134990. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  134991. char **pzErr /* OUT: sqlite3_malloc'd error message */
  134992. ){
  134993. Fts3tokTable *pTab = 0;
  134994. const sqlite3_tokenizer_module *pMod = 0;
  134995. sqlite3_tokenizer *pTok = 0;
  134996. int rc;
  134997. char **azDequote = 0;
  134998. int nDequote;
  134999. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  135000. if( rc!=SQLITE_OK ) return rc;
  135001. nDequote = argc-3;
  135002. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  135003. if( rc==SQLITE_OK ){
  135004. const char *zModule;
  135005. if( nDequote<1 ){
  135006. zModule = "simple";
  135007. }else{
  135008. zModule = azDequote[0];
  135009. }
  135010. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  135011. }
  135012. assert( (rc==SQLITE_OK)==(pMod!=0) );
  135013. if( rc==SQLITE_OK ){
  135014. const char * const *azArg = (const char * const *)&azDequote[1];
  135015. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  135016. }
  135017. if( rc==SQLITE_OK ){
  135018. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  135019. if( pTab==0 ){
  135020. rc = SQLITE_NOMEM;
  135021. }
  135022. }
  135023. if( rc==SQLITE_OK ){
  135024. memset(pTab, 0, sizeof(Fts3tokTable));
  135025. pTab->pMod = pMod;
  135026. pTab->pTok = pTok;
  135027. *ppVtab = &pTab->base;
  135028. }else{
  135029. if( pTok ){
  135030. pMod->xDestroy(pTok);
  135031. }
  135032. }
  135033. sqlite3_free(azDequote);
  135034. return rc;
  135035. }
  135036. /*
  135037. ** This function does the work for both the xDisconnect and xDestroy methods.
  135038. ** These tables have no persistent representation of their own, so xDisconnect
  135039. ** and xDestroy are identical operations.
  135040. */
  135041. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  135042. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  135043. pTab->pMod->xDestroy(pTab->pTok);
  135044. sqlite3_free(pTab);
  135045. return SQLITE_OK;
  135046. }
  135047. /*
  135048. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  135049. */
  135050. static int fts3tokBestIndexMethod(
  135051. sqlite3_vtab *pVTab,
  135052. sqlite3_index_info *pInfo
  135053. ){
  135054. int i;
  135055. UNUSED_PARAMETER(pVTab);
  135056. for(i=0; i<pInfo->nConstraint; i++){
  135057. if( pInfo->aConstraint[i].usable
  135058. && pInfo->aConstraint[i].iColumn==0
  135059. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  135060. ){
  135061. pInfo->idxNum = 1;
  135062. pInfo->aConstraintUsage[i].argvIndex = 1;
  135063. pInfo->aConstraintUsage[i].omit = 1;
  135064. pInfo->estimatedCost = 1;
  135065. return SQLITE_OK;
  135066. }
  135067. }
  135068. pInfo->idxNum = 0;
  135069. assert( pInfo->estimatedCost>1000000.0 );
  135070. return SQLITE_OK;
  135071. }
  135072. /*
  135073. ** xOpen - Open a cursor.
  135074. */
  135075. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  135076. Fts3tokCursor *pCsr;
  135077. UNUSED_PARAMETER(pVTab);
  135078. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  135079. if( pCsr==0 ){
  135080. return SQLITE_NOMEM;
  135081. }
  135082. memset(pCsr, 0, sizeof(Fts3tokCursor));
  135083. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  135084. return SQLITE_OK;
  135085. }
  135086. /*
  135087. ** Reset the tokenizer cursor passed as the only argument. As if it had
  135088. ** just been returned by fts3tokOpenMethod().
  135089. */
  135090. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  135091. if( pCsr->pCsr ){
  135092. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  135093. pTab->pMod->xClose(pCsr->pCsr);
  135094. pCsr->pCsr = 0;
  135095. }
  135096. sqlite3_free(pCsr->zInput);
  135097. pCsr->zInput = 0;
  135098. pCsr->zToken = 0;
  135099. pCsr->nToken = 0;
  135100. pCsr->iStart = 0;
  135101. pCsr->iEnd = 0;
  135102. pCsr->iPos = 0;
  135103. pCsr->iRowid = 0;
  135104. }
  135105. /*
  135106. ** xClose - Close a cursor.
  135107. */
  135108. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  135109. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  135110. fts3tokResetCursor(pCsr);
  135111. sqlite3_free(pCsr);
  135112. return SQLITE_OK;
  135113. }
  135114. /*
  135115. ** xNext - Advance the cursor to the next row, if any.
  135116. */
  135117. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  135118. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  135119. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  135120. int rc; /* Return code */
  135121. pCsr->iRowid++;
  135122. rc = pTab->pMod->xNext(pCsr->pCsr,
  135123. &pCsr->zToken, &pCsr->nToken,
  135124. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  135125. );
  135126. if( rc!=SQLITE_OK ){
  135127. fts3tokResetCursor(pCsr);
  135128. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  135129. }
  135130. return rc;
  135131. }
  135132. /*
  135133. ** xFilter - Initialize a cursor to point at the start of its data.
  135134. */
  135135. static int fts3tokFilterMethod(
  135136. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  135137. int idxNum, /* Strategy index */
  135138. const char *idxStr, /* Unused */
  135139. int nVal, /* Number of elements in apVal */
  135140. sqlite3_value **apVal /* Arguments for the indexing scheme */
  135141. ){
  135142. int rc = SQLITE_ERROR;
  135143. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  135144. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  135145. UNUSED_PARAMETER(idxStr);
  135146. UNUSED_PARAMETER(nVal);
  135147. fts3tokResetCursor(pCsr);
  135148. if( idxNum==1 ){
  135149. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  135150. int nByte = sqlite3_value_bytes(apVal[0]);
  135151. pCsr->zInput = sqlite3_malloc(nByte+1);
  135152. if( pCsr->zInput==0 ){
  135153. rc = SQLITE_NOMEM;
  135154. }else{
  135155. memcpy(pCsr->zInput, zByte, nByte);
  135156. pCsr->zInput[nByte] = 0;
  135157. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  135158. if( rc==SQLITE_OK ){
  135159. pCsr->pCsr->pTokenizer = pTab->pTok;
  135160. }
  135161. }
  135162. }
  135163. if( rc!=SQLITE_OK ) return rc;
  135164. return fts3tokNextMethod(pCursor);
  135165. }
  135166. /*
  135167. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  135168. */
  135169. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  135170. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  135171. return (pCsr->zToken==0);
  135172. }
  135173. /*
  135174. ** xColumn - Return a column value.
  135175. */
  135176. static int fts3tokColumnMethod(
  135177. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  135178. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  135179. int iCol /* Index of column to read value from */
  135180. ){
  135181. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  135182. /* CREATE TABLE x(input, token, start, end, position) */
  135183. switch( iCol ){
  135184. case 0:
  135185. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  135186. break;
  135187. case 1:
  135188. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  135189. break;
  135190. case 2:
  135191. sqlite3_result_int(pCtx, pCsr->iStart);
  135192. break;
  135193. case 3:
  135194. sqlite3_result_int(pCtx, pCsr->iEnd);
  135195. break;
  135196. default:
  135197. assert( iCol==4 );
  135198. sqlite3_result_int(pCtx, pCsr->iPos);
  135199. break;
  135200. }
  135201. return SQLITE_OK;
  135202. }
  135203. /*
  135204. ** xRowid - Return the current rowid for the cursor.
  135205. */
  135206. static int fts3tokRowidMethod(
  135207. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  135208. sqlite_int64 *pRowid /* OUT: Rowid value */
  135209. ){
  135210. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  135211. *pRowid = (sqlite3_int64)pCsr->iRowid;
  135212. return SQLITE_OK;
  135213. }
  135214. /*
  135215. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  135216. ** if successful or an error code if sqlite3_create_module() fails.
  135217. */
  135218. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  135219. static const sqlite3_module fts3tok_module = {
  135220. 0, /* iVersion */
  135221. fts3tokConnectMethod, /* xCreate */
  135222. fts3tokConnectMethod, /* xConnect */
  135223. fts3tokBestIndexMethod, /* xBestIndex */
  135224. fts3tokDisconnectMethod, /* xDisconnect */
  135225. fts3tokDisconnectMethod, /* xDestroy */
  135226. fts3tokOpenMethod, /* xOpen */
  135227. fts3tokCloseMethod, /* xClose */
  135228. fts3tokFilterMethod, /* xFilter */
  135229. fts3tokNextMethod, /* xNext */
  135230. fts3tokEofMethod, /* xEof */
  135231. fts3tokColumnMethod, /* xColumn */
  135232. fts3tokRowidMethod, /* xRowid */
  135233. 0, /* xUpdate */
  135234. 0, /* xBegin */
  135235. 0, /* xSync */
  135236. 0, /* xCommit */
  135237. 0, /* xRollback */
  135238. 0, /* xFindFunction */
  135239. 0, /* xRename */
  135240. 0, /* xSavepoint */
  135241. 0, /* xRelease */
  135242. 0 /* xRollbackTo */
  135243. };
  135244. int rc; /* Return code */
  135245. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  135246. return rc;
  135247. }
  135248. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  135249. /************** End of fts3_tokenize_vtab.c **********************************/
  135250. /************** Begin file fts3_write.c **************************************/
  135251. /*
  135252. ** 2009 Oct 23
  135253. **
  135254. ** The author disclaims copyright to this source code. In place of
  135255. ** a legal notice, here is a blessing:
  135256. **
  135257. ** May you do good and not evil.
  135258. ** May you find forgiveness for yourself and forgive others.
  135259. ** May you share freely, never taking more than you give.
  135260. **
  135261. ******************************************************************************
  135262. **
  135263. ** This file is part of the SQLite FTS3 extension module. Specifically,
  135264. ** this file contains code to insert, update and delete rows from FTS3
  135265. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  135266. ** of the sub-routines used to merge segments are also used by the query
  135267. ** code in fts3.c.
  135268. */
  135269. /* #include "fts3Int.h" */
  135270. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  135271. /* #include <string.h> */
  135272. /* #include <assert.h> */
  135273. /* #include <stdlib.h> */
  135274. #define FTS_MAX_APPENDABLE_HEIGHT 16
  135275. /*
  135276. ** When full-text index nodes are loaded from disk, the buffer that they
  135277. ** are loaded into has the following number of bytes of padding at the end
  135278. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  135279. ** of 920 bytes is allocated for it.
  135280. **
  135281. ** This means that if we have a pointer into a buffer containing node data,
  135282. ** it is always safe to read up to two varints from it without risking an
  135283. ** overread, even if the node data is corrupted.
  135284. */
  135285. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  135286. /*
  135287. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  135288. ** memory incrementally instead of all at once. This can be a big performance
  135289. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  135290. ** method before retrieving all query results (as may happen, for example,
  135291. ** if a query has a LIMIT clause).
  135292. **
  135293. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  135294. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  135295. ** The code is written so that the hard lower-limit for each of these values
  135296. ** is 1. Clearly such small values would be inefficient, but can be useful
  135297. ** for testing purposes.
  135298. **
  135299. ** If this module is built with SQLITE_TEST defined, these constants may
  135300. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  135301. ** a Tcl interface to read and write the values.
  135302. */
  135303. #ifdef SQLITE_TEST
  135304. int test_fts3_node_chunksize = (4*1024);
  135305. int test_fts3_node_chunk_threshold = (4*1024)*4;
  135306. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  135307. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  135308. #else
  135309. # define FTS3_NODE_CHUNKSIZE (4*1024)
  135310. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  135311. #endif
  135312. /*
  135313. ** The two values that may be meaningfully bound to the :1 parameter in
  135314. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  135315. */
  135316. #define FTS_STAT_DOCTOTAL 0
  135317. #define FTS_STAT_INCRMERGEHINT 1
  135318. #define FTS_STAT_AUTOINCRMERGE 2
  135319. /*
  135320. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  135321. ** and incremental merge operation that takes place. This is used for
  135322. ** debugging FTS only, it should not usually be turned on in production
  135323. ** systems.
  135324. */
  135325. #ifdef FTS3_LOG_MERGES
  135326. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  135327. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  135328. }
  135329. #else
  135330. #define fts3LogMerge(x, y)
  135331. #endif
  135332. typedef struct PendingList PendingList;
  135333. typedef struct SegmentNode SegmentNode;
  135334. typedef struct SegmentWriter SegmentWriter;
  135335. /*
  135336. ** An instance of the following data structure is used to build doclists
  135337. ** incrementally. See function fts3PendingListAppend() for details.
  135338. */
  135339. struct PendingList {
  135340. int nData;
  135341. char *aData;
  135342. int nSpace;
  135343. sqlite3_int64 iLastDocid;
  135344. sqlite3_int64 iLastCol;
  135345. sqlite3_int64 iLastPos;
  135346. };
  135347. /*
  135348. ** Each cursor has a (possibly empty) linked list of the following objects.
  135349. */
  135350. struct Fts3DeferredToken {
  135351. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  135352. int iCol; /* Column token must occur in */
  135353. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  135354. PendingList *pList; /* Doclist is assembled here */
  135355. };
  135356. /*
  135357. ** An instance of this structure is used to iterate through the terms on
  135358. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  135359. ** this structure are only manipulated by code in this file, opaque handles
  135360. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  135361. ** terms when querying the full-text index. See functions:
  135362. **
  135363. ** sqlite3Fts3SegReaderNew()
  135364. ** sqlite3Fts3SegReaderFree()
  135365. ** sqlite3Fts3SegReaderIterate()
  135366. **
  135367. ** Methods used to manipulate Fts3SegReader structures:
  135368. **
  135369. ** fts3SegReaderNext()
  135370. ** fts3SegReaderFirstDocid()
  135371. ** fts3SegReaderNextDocid()
  135372. */
  135373. struct Fts3SegReader {
  135374. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  135375. u8 bLookup; /* True for a lookup only */
  135376. u8 rootOnly; /* True for a root-only reader */
  135377. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  135378. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  135379. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  135380. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  135381. char *aNode; /* Pointer to node data (or NULL) */
  135382. int nNode; /* Size of buffer at aNode (or 0) */
  135383. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  135384. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  135385. Fts3HashElem **ppNextElem;
  135386. /* Variables set by fts3SegReaderNext(). These may be read directly
  135387. ** by the caller. They are valid from the time SegmentReaderNew() returns
  135388. ** until SegmentReaderNext() returns something other than SQLITE_OK
  135389. ** (i.e. SQLITE_DONE).
  135390. */
  135391. int nTerm; /* Number of bytes in current term */
  135392. char *zTerm; /* Pointer to current term */
  135393. int nTermAlloc; /* Allocated size of zTerm buffer */
  135394. char *aDoclist; /* Pointer to doclist of current entry */
  135395. int nDoclist; /* Size of doclist in current entry */
  135396. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  135397. ** through the current doclist (aDoclist/nDoclist).
  135398. */
  135399. char *pOffsetList;
  135400. int nOffsetList; /* For descending pending seg-readers only */
  135401. sqlite3_int64 iDocid;
  135402. };
  135403. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  135404. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  135405. /*
  135406. ** An instance of this structure is used to create a segment b-tree in the
  135407. ** database. The internal details of this type are only accessed by the
  135408. ** following functions:
  135409. **
  135410. ** fts3SegWriterAdd()
  135411. ** fts3SegWriterFlush()
  135412. ** fts3SegWriterFree()
  135413. */
  135414. struct SegmentWriter {
  135415. SegmentNode *pTree; /* Pointer to interior tree structure */
  135416. sqlite3_int64 iFirst; /* First slot in %_segments written */
  135417. sqlite3_int64 iFree; /* Next free slot in %_segments */
  135418. char *zTerm; /* Pointer to previous term buffer */
  135419. int nTerm; /* Number of bytes in zTerm */
  135420. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  135421. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  135422. int nSize; /* Size of allocation at aData */
  135423. int nData; /* Bytes of data in aData */
  135424. char *aData; /* Pointer to block from malloc() */
  135425. i64 nLeafData; /* Number of bytes of leaf data written */
  135426. };
  135427. /*
  135428. ** Type SegmentNode is used by the following three functions to create
  135429. ** the interior part of the segment b+-tree structures (everything except
  135430. ** the leaf nodes). These functions and type are only ever used by code
  135431. ** within the fts3SegWriterXXX() family of functions described above.
  135432. **
  135433. ** fts3NodeAddTerm()
  135434. ** fts3NodeWrite()
  135435. ** fts3NodeFree()
  135436. **
  135437. ** When a b+tree is written to the database (either as a result of a merge
  135438. ** or the pending-terms table being flushed), leaves are written into the
  135439. ** database file as soon as they are completely populated. The interior of
  135440. ** the tree is assembled in memory and written out only once all leaves have
  135441. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  135442. ** very large, meaning that the interior of the tree consumes relatively
  135443. ** little memory.
  135444. */
  135445. struct SegmentNode {
  135446. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  135447. SegmentNode *pRight; /* Pointer to right-sibling */
  135448. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  135449. int nEntry; /* Number of terms written to node so far */
  135450. char *zTerm; /* Pointer to previous term buffer */
  135451. int nTerm; /* Number of bytes in zTerm */
  135452. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  135453. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  135454. int nData; /* Bytes of valid data so far */
  135455. char *aData; /* Node data */
  135456. };
  135457. /*
  135458. ** Valid values for the second argument to fts3SqlStmt().
  135459. */
  135460. #define SQL_DELETE_CONTENT 0
  135461. #define SQL_IS_EMPTY 1
  135462. #define SQL_DELETE_ALL_CONTENT 2
  135463. #define SQL_DELETE_ALL_SEGMENTS 3
  135464. #define SQL_DELETE_ALL_SEGDIR 4
  135465. #define SQL_DELETE_ALL_DOCSIZE 5
  135466. #define SQL_DELETE_ALL_STAT 6
  135467. #define SQL_SELECT_CONTENT_BY_ROWID 7
  135468. #define SQL_NEXT_SEGMENT_INDEX 8
  135469. #define SQL_INSERT_SEGMENTS 9
  135470. #define SQL_NEXT_SEGMENTS_ID 10
  135471. #define SQL_INSERT_SEGDIR 11
  135472. #define SQL_SELECT_LEVEL 12
  135473. #define SQL_SELECT_LEVEL_RANGE 13
  135474. #define SQL_SELECT_LEVEL_COUNT 14
  135475. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  135476. #define SQL_DELETE_SEGDIR_LEVEL 16
  135477. #define SQL_DELETE_SEGMENTS_RANGE 17
  135478. #define SQL_CONTENT_INSERT 18
  135479. #define SQL_DELETE_DOCSIZE 19
  135480. #define SQL_REPLACE_DOCSIZE 20
  135481. #define SQL_SELECT_DOCSIZE 21
  135482. #define SQL_SELECT_STAT 22
  135483. #define SQL_REPLACE_STAT 23
  135484. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  135485. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  135486. #define SQL_DELETE_SEGDIR_RANGE 26
  135487. #define SQL_SELECT_ALL_LANGID 27
  135488. #define SQL_FIND_MERGE_LEVEL 28
  135489. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  135490. #define SQL_DELETE_SEGDIR_ENTRY 30
  135491. #define SQL_SHIFT_SEGDIR_ENTRY 31
  135492. #define SQL_SELECT_SEGDIR 32
  135493. #define SQL_CHOMP_SEGDIR 33
  135494. #define SQL_SEGMENT_IS_APPENDABLE 34
  135495. #define SQL_SELECT_INDEXES 35
  135496. #define SQL_SELECT_MXLEVEL 36
  135497. #define SQL_SELECT_LEVEL_RANGE2 37
  135498. #define SQL_UPDATE_LEVEL_IDX 38
  135499. #define SQL_UPDATE_LEVEL 39
  135500. /*
  135501. ** This function is used to obtain an SQLite prepared statement handle
  135502. ** for the statement identified by the second argument. If successful,
  135503. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  135504. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  135505. **
  135506. ** If argument apVal is not NULL, then it must point to an array with
  135507. ** at least as many entries as the requested statement has bound
  135508. ** parameters. The values are bound to the statements parameters before
  135509. ** returning.
  135510. */
  135511. static int fts3SqlStmt(
  135512. Fts3Table *p, /* Virtual table handle */
  135513. int eStmt, /* One of the SQL_XXX constants above */
  135514. sqlite3_stmt **pp, /* OUT: Statement handle */
  135515. sqlite3_value **apVal /* Values to bind to statement */
  135516. ){
  135517. const char *azSql[] = {
  135518. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  135519. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  135520. /* 2 */ "DELETE FROM %Q.'%q_content'",
  135521. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  135522. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  135523. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  135524. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  135525. /* 7 */ "SELECT %s WHERE rowid=?",
  135526. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  135527. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  135528. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  135529. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  135530. /* Return segments in order from oldest to newest.*/
  135531. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  135532. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  135533. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  135534. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  135535. "ORDER BY level DESC, idx ASC",
  135536. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  135537. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  135538. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  135539. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  135540. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  135541. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  135542. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  135543. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  135544. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  135545. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  135546. /* 24 */ "",
  135547. /* 25 */ "",
  135548. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  135549. /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
  135550. /* This statement is used to determine which level to read the input from
  135551. ** when performing an incremental merge. It returns the absolute level number
  135552. ** of the oldest level in the db that contains at least ? segments. Or,
  135553. ** if no level in the FTS index contains more than ? segments, the statement
  135554. ** returns zero rows. */
  135555. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  135556. " ORDER BY (level %% 1024) ASC LIMIT 1",
  135557. /* Estimate the upper limit on the number of leaf nodes in a new segment
  135558. ** created by merging the oldest :2 segments from absolute level :1. See
  135559. ** function sqlite3Fts3Incrmerge() for details. */
  135560. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  135561. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  135562. /* SQL_DELETE_SEGDIR_ENTRY
  135563. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  135564. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  135565. /* SQL_SHIFT_SEGDIR_ENTRY
  135566. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  135567. ** to :1. */
  135568. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  135569. /* SQL_SELECT_SEGDIR
  135570. ** Read a single entry from the %_segdir table. The entry from absolute
  135571. ** level :1 with index value :2. */
  135572. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  135573. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  135574. /* SQL_CHOMP_SEGDIR
  135575. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  135576. ** entry located on absolute level :3 with index :4. */
  135577. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  135578. "WHERE level = ? AND idx = ?",
  135579. /* SQL_SEGMENT_IS_APPENDABLE
  135580. ** Return a single row if the segment with end_block=? is appendable. Or
  135581. ** no rows otherwise. */
  135582. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  135583. /* SQL_SELECT_INDEXES
  135584. ** Return the list of valid segment indexes for absolute level ? */
  135585. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  135586. /* SQL_SELECT_MXLEVEL
  135587. ** Return the largest relative level in the FTS index or indexes. */
  135588. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  135589. /* Return segments in order from oldest to newest.*/
  135590. /* 37 */ "SELECT level, idx, end_block "
  135591. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  135592. "ORDER BY level DESC, idx ASC",
  135593. /* Update statements used while promoting segments */
  135594. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  135595. "WHERE level=? AND idx=?",
  135596. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  135597. };
  135598. int rc = SQLITE_OK;
  135599. sqlite3_stmt *pStmt;
  135600. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  135601. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  135602. pStmt = p->aStmt[eStmt];
  135603. if( !pStmt ){
  135604. char *zSql;
  135605. if( eStmt==SQL_CONTENT_INSERT ){
  135606. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  135607. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  135608. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  135609. }else{
  135610. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  135611. }
  135612. if( !zSql ){
  135613. rc = SQLITE_NOMEM;
  135614. }else{
  135615. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  135616. sqlite3_free(zSql);
  135617. assert( rc==SQLITE_OK || pStmt==0 );
  135618. p->aStmt[eStmt] = pStmt;
  135619. }
  135620. }
  135621. if( apVal ){
  135622. int i;
  135623. int nParam = sqlite3_bind_parameter_count(pStmt);
  135624. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  135625. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  135626. }
  135627. }
  135628. *pp = pStmt;
  135629. return rc;
  135630. }
  135631. static int fts3SelectDocsize(
  135632. Fts3Table *pTab, /* FTS3 table handle */
  135633. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  135634. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  135635. ){
  135636. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  135637. int rc; /* Return code */
  135638. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  135639. if( rc==SQLITE_OK ){
  135640. sqlite3_bind_int64(pStmt, 1, iDocid);
  135641. rc = sqlite3_step(pStmt);
  135642. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  135643. rc = sqlite3_reset(pStmt);
  135644. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  135645. pStmt = 0;
  135646. }else{
  135647. rc = SQLITE_OK;
  135648. }
  135649. }
  135650. *ppStmt = pStmt;
  135651. return rc;
  135652. }
  135653. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  135654. Fts3Table *pTab, /* Fts3 table handle */
  135655. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  135656. ){
  135657. sqlite3_stmt *pStmt = 0;
  135658. int rc;
  135659. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  135660. if( rc==SQLITE_OK ){
  135661. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  135662. if( sqlite3_step(pStmt)!=SQLITE_ROW
  135663. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  135664. ){
  135665. rc = sqlite3_reset(pStmt);
  135666. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  135667. pStmt = 0;
  135668. }
  135669. }
  135670. *ppStmt = pStmt;
  135671. return rc;
  135672. }
  135673. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  135674. Fts3Table *pTab, /* Fts3 table handle */
  135675. sqlite3_int64 iDocid, /* Docid to read size data for */
  135676. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  135677. ){
  135678. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  135679. }
  135680. /*
  135681. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  135682. ** array apVal[] to the SQL statement identified by eStmt, the statement
  135683. ** is executed.
  135684. **
  135685. ** Returns SQLITE_OK if the statement is successfully executed, or an
  135686. ** SQLite error code otherwise.
  135687. */
  135688. static void fts3SqlExec(
  135689. int *pRC, /* Result code */
  135690. Fts3Table *p, /* The FTS3 table */
  135691. int eStmt, /* Index of statement to evaluate */
  135692. sqlite3_value **apVal /* Parameters to bind */
  135693. ){
  135694. sqlite3_stmt *pStmt;
  135695. int rc;
  135696. if( *pRC ) return;
  135697. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  135698. if( rc==SQLITE_OK ){
  135699. sqlite3_step(pStmt);
  135700. rc = sqlite3_reset(pStmt);
  135701. }
  135702. *pRC = rc;
  135703. }
  135704. /*
  135705. ** This function ensures that the caller has obtained an exclusive
  135706. ** shared-cache table-lock on the %_segdir table. This is required before
  135707. ** writing data to the fts3 table. If this lock is not acquired first, then
  135708. ** the caller may end up attempting to take this lock as part of committing
  135709. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  135710. ** LOCKED_SHAREDCACHEto a COMMIT command.
  135711. **
  135712. ** It is best to avoid this because if FTS3 returns any error when
  135713. ** committing a transaction, the whole transaction will be rolled back.
  135714. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  135715. ** It can still happen if the user locks the underlying tables directly
  135716. ** instead of accessing them via FTS.
  135717. */
  135718. static int fts3Writelock(Fts3Table *p){
  135719. int rc = SQLITE_OK;
  135720. if( p->nPendingData==0 ){
  135721. sqlite3_stmt *pStmt;
  135722. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  135723. if( rc==SQLITE_OK ){
  135724. sqlite3_bind_null(pStmt, 1);
  135725. sqlite3_step(pStmt);
  135726. rc = sqlite3_reset(pStmt);
  135727. }
  135728. }
  135729. return rc;
  135730. }
  135731. /*
  135732. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  135733. ** Within each language id, a separate index is maintained to store the
  135734. ** document terms, and each configured prefix size (configured the FTS
  135735. ** "prefix=" option). And each index consists of multiple levels ("relative
  135736. ** levels").
  135737. **
  135738. ** All three of these values (the language id, the specific index and the
  135739. ** level within the index) are encoded in 64-bit integer values stored
  135740. ** in the %_segdir table on disk. This function is used to convert three
  135741. ** separate component values into the single 64-bit integer value that
  135742. ** can be used to query the %_segdir table.
  135743. **
  135744. ** Specifically, each language-id/index combination is allocated 1024
  135745. ** 64-bit integer level values ("absolute levels"). The main terms index
  135746. ** for language-id 0 is allocate values 0-1023. The first prefix index
  135747. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  135748. ** Language 1 indexes are allocated immediately following language 0.
  135749. **
  135750. ** So, for a system with nPrefix prefix indexes configured, the block of
  135751. ** absolute levels that corresponds to language-id iLangid and index
  135752. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  135753. */
  135754. static sqlite3_int64 getAbsoluteLevel(
  135755. Fts3Table *p, /* FTS3 table handle */
  135756. int iLangid, /* Language id */
  135757. int iIndex, /* Index in p->aIndex[] */
  135758. int iLevel /* Level of segments */
  135759. ){
  135760. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  135761. assert( iLangid>=0 );
  135762. assert( p->nIndex>0 );
  135763. assert( iIndex>=0 && iIndex<p->nIndex );
  135764. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  135765. return iBase + iLevel;
  135766. }
  135767. /*
  135768. ** Set *ppStmt to a statement handle that may be used to iterate through
  135769. ** all rows in the %_segdir table, from oldest to newest. If successful,
  135770. ** return SQLITE_OK. If an error occurs while preparing the statement,
  135771. ** return an SQLite error code.
  135772. **
  135773. ** There is only ever one instance of this SQL statement compiled for
  135774. ** each FTS3 table.
  135775. **
  135776. ** The statement returns the following columns from the %_segdir table:
  135777. **
  135778. ** 0: idx
  135779. ** 1: start_block
  135780. ** 2: leaves_end_block
  135781. ** 3: end_block
  135782. ** 4: root
  135783. */
  135784. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  135785. Fts3Table *p, /* FTS3 table */
  135786. int iLangid, /* Language being queried */
  135787. int iIndex, /* Index for p->aIndex[] */
  135788. int iLevel, /* Level to select (relative level) */
  135789. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  135790. ){
  135791. int rc;
  135792. sqlite3_stmt *pStmt = 0;
  135793. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  135794. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  135795. assert( iIndex>=0 && iIndex<p->nIndex );
  135796. if( iLevel<0 ){
  135797. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  135798. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  135799. if( rc==SQLITE_OK ){
  135800. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  135801. sqlite3_bind_int64(pStmt, 2,
  135802. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  135803. );
  135804. }
  135805. }else{
  135806. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  135807. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  135808. if( rc==SQLITE_OK ){
  135809. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  135810. }
  135811. }
  135812. *ppStmt = pStmt;
  135813. return rc;
  135814. }
  135815. /*
  135816. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  135817. ** if successful, or an SQLite error code otherwise.
  135818. **
  135819. ** This function also serves to allocate the PendingList structure itself.
  135820. ** For example, to create a new PendingList structure containing two
  135821. ** varints:
  135822. **
  135823. ** PendingList *p = 0;
  135824. ** fts3PendingListAppendVarint(&p, 1);
  135825. ** fts3PendingListAppendVarint(&p, 2);
  135826. */
  135827. static int fts3PendingListAppendVarint(
  135828. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  135829. sqlite3_int64 i /* Value to append to data */
  135830. ){
  135831. PendingList *p = *pp;
  135832. /* Allocate or grow the PendingList as required. */
  135833. if( !p ){
  135834. p = sqlite3_malloc(sizeof(*p) + 100);
  135835. if( !p ){
  135836. return SQLITE_NOMEM;
  135837. }
  135838. p->nSpace = 100;
  135839. p->aData = (char *)&p[1];
  135840. p->nData = 0;
  135841. }
  135842. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  135843. int nNew = p->nSpace * 2;
  135844. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  135845. if( !p ){
  135846. sqlite3_free(*pp);
  135847. *pp = 0;
  135848. return SQLITE_NOMEM;
  135849. }
  135850. p->nSpace = nNew;
  135851. p->aData = (char *)&p[1];
  135852. }
  135853. /* Append the new serialized varint to the end of the list. */
  135854. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  135855. p->aData[p->nData] = '\0';
  135856. *pp = p;
  135857. return SQLITE_OK;
  135858. }
  135859. /*
  135860. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  135861. ** is returned if the structure is sqlite3_realloced as part of adding
  135862. ** the entry. Otherwise, zero.
  135863. **
  135864. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  135865. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  135866. ** it is set to SQLITE_OK.
  135867. */
  135868. static int fts3PendingListAppend(
  135869. PendingList **pp, /* IN/OUT: PendingList structure */
  135870. sqlite3_int64 iDocid, /* Docid for entry to add */
  135871. sqlite3_int64 iCol, /* Column for entry to add */
  135872. sqlite3_int64 iPos, /* Position of term for entry to add */
  135873. int *pRc /* OUT: Return code */
  135874. ){
  135875. PendingList *p = *pp;
  135876. int rc = SQLITE_OK;
  135877. assert( !p || p->iLastDocid<=iDocid );
  135878. if( !p || p->iLastDocid!=iDocid ){
  135879. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  135880. if( p ){
  135881. assert( p->nData<p->nSpace );
  135882. assert( p->aData[p->nData]==0 );
  135883. p->nData++;
  135884. }
  135885. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  135886. goto pendinglistappend_out;
  135887. }
  135888. p->iLastCol = -1;
  135889. p->iLastPos = 0;
  135890. p->iLastDocid = iDocid;
  135891. }
  135892. if( iCol>0 && p->iLastCol!=iCol ){
  135893. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  135894. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  135895. ){
  135896. goto pendinglistappend_out;
  135897. }
  135898. p->iLastCol = iCol;
  135899. p->iLastPos = 0;
  135900. }
  135901. if( iCol>=0 ){
  135902. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  135903. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  135904. if( rc==SQLITE_OK ){
  135905. p->iLastPos = iPos;
  135906. }
  135907. }
  135908. pendinglistappend_out:
  135909. *pRc = rc;
  135910. if( p!=*pp ){
  135911. *pp = p;
  135912. return 1;
  135913. }
  135914. return 0;
  135915. }
  135916. /*
  135917. ** Free a PendingList object allocated by fts3PendingListAppend().
  135918. */
  135919. static void fts3PendingListDelete(PendingList *pList){
  135920. sqlite3_free(pList);
  135921. }
  135922. /*
  135923. ** Add an entry to one of the pending-terms hash tables.
  135924. */
  135925. static int fts3PendingTermsAddOne(
  135926. Fts3Table *p,
  135927. int iCol,
  135928. int iPos,
  135929. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  135930. const char *zToken,
  135931. int nToken
  135932. ){
  135933. PendingList *pList;
  135934. int rc = SQLITE_OK;
  135935. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  135936. if( pList ){
  135937. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  135938. }
  135939. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  135940. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  135941. /* Malloc failed while inserting the new entry. This can only
  135942. ** happen if there was no previous entry for this token.
  135943. */
  135944. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  135945. sqlite3_free(pList);
  135946. rc = SQLITE_NOMEM;
  135947. }
  135948. }
  135949. if( rc==SQLITE_OK ){
  135950. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  135951. }
  135952. return rc;
  135953. }
  135954. /*
  135955. ** Tokenize the nul-terminated string zText and add all tokens to the
  135956. ** pending-terms hash-table. The docid used is that currently stored in
  135957. ** p->iPrevDocid, and the column is specified by argument iCol.
  135958. **
  135959. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  135960. */
  135961. static int fts3PendingTermsAdd(
  135962. Fts3Table *p, /* Table into which text will be inserted */
  135963. int iLangid, /* Language id to use */
  135964. const char *zText, /* Text of document to be inserted */
  135965. int iCol, /* Column into which text is being inserted */
  135966. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  135967. ){
  135968. int rc;
  135969. int iStart = 0;
  135970. int iEnd = 0;
  135971. int iPos = 0;
  135972. int nWord = 0;
  135973. char const *zToken;
  135974. int nToken = 0;
  135975. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  135976. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  135977. sqlite3_tokenizer_cursor *pCsr;
  135978. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  135979. const char**,int*,int*,int*,int*);
  135980. assert( pTokenizer && pModule );
  135981. /* If the user has inserted a NULL value, this function may be called with
  135982. ** zText==0. In this case, add zero token entries to the hash table and
  135983. ** return early. */
  135984. if( zText==0 ){
  135985. *pnWord = 0;
  135986. return SQLITE_OK;
  135987. }
  135988. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  135989. if( rc!=SQLITE_OK ){
  135990. return rc;
  135991. }
  135992. xNext = pModule->xNext;
  135993. while( SQLITE_OK==rc
  135994. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  135995. ){
  135996. int i;
  135997. if( iPos>=nWord ) nWord = iPos+1;
  135998. /* Positions cannot be negative; we use -1 as a terminator internally.
  135999. ** Tokens must have a non-zero length.
  136000. */
  136001. if( iPos<0 || !zToken || nToken<=0 ){
  136002. rc = SQLITE_ERROR;
  136003. break;
  136004. }
  136005. /* Add the term to the terms index */
  136006. rc = fts3PendingTermsAddOne(
  136007. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  136008. );
  136009. /* Add the term to each of the prefix indexes that it is not too
  136010. ** short for. */
  136011. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  136012. struct Fts3Index *pIndex = &p->aIndex[i];
  136013. if( nToken<pIndex->nPrefix ) continue;
  136014. rc = fts3PendingTermsAddOne(
  136015. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  136016. );
  136017. }
  136018. }
  136019. pModule->xClose(pCsr);
  136020. *pnWord += nWord;
  136021. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  136022. }
  136023. /*
  136024. ** Calling this function indicates that subsequent calls to
  136025. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  136026. ** contents of the document with docid iDocid.
  136027. */
  136028. static int fts3PendingTermsDocid(
  136029. Fts3Table *p, /* Full-text table handle */
  136030. int iLangid, /* Language id of row being written */
  136031. sqlite_int64 iDocid /* Docid of row being written */
  136032. ){
  136033. assert( iLangid>=0 );
  136034. /* TODO(shess) Explore whether partially flushing the buffer on
  136035. ** forced-flush would provide better performance. I suspect that if
  136036. ** we ordered the doclists by size and flushed the largest until the
  136037. ** buffer was half empty, that would let the less frequent terms
  136038. ** generate longer doclists.
  136039. */
  136040. if( iDocid<=p->iPrevDocid
  136041. || p->iPrevLangid!=iLangid
  136042. || p->nPendingData>p->nMaxPendingData
  136043. ){
  136044. int rc = sqlite3Fts3PendingTermsFlush(p);
  136045. if( rc!=SQLITE_OK ) return rc;
  136046. }
  136047. p->iPrevDocid = iDocid;
  136048. p->iPrevLangid = iLangid;
  136049. return SQLITE_OK;
  136050. }
  136051. /*
  136052. ** Discard the contents of the pending-terms hash tables.
  136053. */
  136054. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  136055. int i;
  136056. for(i=0; i<p->nIndex; i++){
  136057. Fts3HashElem *pElem;
  136058. Fts3Hash *pHash = &p->aIndex[i].hPending;
  136059. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  136060. PendingList *pList = (PendingList *)fts3HashData(pElem);
  136061. fts3PendingListDelete(pList);
  136062. }
  136063. fts3HashClear(pHash);
  136064. }
  136065. p->nPendingData = 0;
  136066. }
  136067. /*
  136068. ** This function is called by the xUpdate() method as part of an INSERT
  136069. ** operation. It adds entries for each term in the new record to the
  136070. ** pendingTerms hash table.
  136071. **
  136072. ** Argument apVal is the same as the similarly named argument passed to
  136073. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  136074. */
  136075. static int fts3InsertTerms(
  136076. Fts3Table *p,
  136077. int iLangid,
  136078. sqlite3_value **apVal,
  136079. u32 *aSz
  136080. ){
  136081. int i; /* Iterator variable */
  136082. for(i=2; i<p->nColumn+2; i++){
  136083. int iCol = i-2;
  136084. if( p->abNotindexed[iCol]==0 ){
  136085. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  136086. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  136087. if( rc!=SQLITE_OK ){
  136088. return rc;
  136089. }
  136090. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  136091. }
  136092. }
  136093. return SQLITE_OK;
  136094. }
  136095. /*
  136096. ** This function is called by the xUpdate() method for an INSERT operation.
  136097. ** The apVal parameter is passed a copy of the apVal argument passed by
  136098. ** SQLite to the xUpdate() method. i.e:
  136099. **
  136100. ** apVal[0] Not used for INSERT.
  136101. ** apVal[1] rowid
  136102. ** apVal[2] Left-most user-defined column
  136103. ** ...
  136104. ** apVal[p->nColumn+1] Right-most user-defined column
  136105. ** apVal[p->nColumn+2] Hidden column with same name as table
  136106. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  136107. ** apVal[p->nColumn+4] Hidden languageid column
  136108. */
  136109. static int fts3InsertData(
  136110. Fts3Table *p, /* Full-text table */
  136111. sqlite3_value **apVal, /* Array of values to insert */
  136112. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  136113. ){
  136114. int rc; /* Return code */
  136115. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  136116. if( p->zContentTbl ){
  136117. sqlite3_value *pRowid = apVal[p->nColumn+3];
  136118. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  136119. pRowid = apVal[1];
  136120. }
  136121. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  136122. return SQLITE_CONSTRAINT;
  136123. }
  136124. *piDocid = sqlite3_value_int64(pRowid);
  136125. return SQLITE_OK;
  136126. }
  136127. /* Locate the statement handle used to insert data into the %_content
  136128. ** table. The SQL for this statement is:
  136129. **
  136130. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  136131. **
  136132. ** The statement features N '?' variables, where N is the number of user
  136133. ** defined columns in the FTS3 table, plus one for the docid field.
  136134. */
  136135. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  136136. if( rc==SQLITE_OK && p->zLanguageid ){
  136137. rc = sqlite3_bind_int(
  136138. pContentInsert, p->nColumn+2,
  136139. sqlite3_value_int(apVal[p->nColumn+4])
  136140. );
  136141. }
  136142. if( rc!=SQLITE_OK ) return rc;
  136143. /* There is a quirk here. The users INSERT statement may have specified
  136144. ** a value for the "rowid" field, for the "docid" field, or for both.
  136145. ** Which is a problem, since "rowid" and "docid" are aliases for the
  136146. ** same value. For example:
  136147. **
  136148. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  136149. **
  136150. ** In FTS3, this is an error. It is an error to specify non-NULL values
  136151. ** for both docid and some other rowid alias.
  136152. */
  136153. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  136154. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  136155. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  136156. ){
  136157. /* A rowid/docid conflict. */
  136158. return SQLITE_ERROR;
  136159. }
  136160. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  136161. if( rc!=SQLITE_OK ) return rc;
  136162. }
  136163. /* Execute the statement to insert the record. Set *piDocid to the
  136164. ** new docid value.
  136165. */
  136166. sqlite3_step(pContentInsert);
  136167. rc = sqlite3_reset(pContentInsert);
  136168. *piDocid = sqlite3_last_insert_rowid(p->db);
  136169. return rc;
  136170. }
  136171. /*
  136172. ** Remove all data from the FTS3 table. Clear the hash table containing
  136173. ** pending terms.
  136174. */
  136175. static int fts3DeleteAll(Fts3Table *p, int bContent){
  136176. int rc = SQLITE_OK; /* Return code */
  136177. /* Discard the contents of the pending-terms hash table. */
  136178. sqlite3Fts3PendingTermsClear(p);
  136179. /* Delete everything from the shadow tables. Except, leave %_content as
  136180. ** is if bContent is false. */
  136181. assert( p->zContentTbl==0 || bContent==0 );
  136182. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  136183. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  136184. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  136185. if( p->bHasDocsize ){
  136186. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  136187. }
  136188. if( p->bHasStat ){
  136189. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  136190. }
  136191. return rc;
  136192. }
  136193. /*
  136194. **
  136195. */
  136196. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  136197. int iLangid = 0;
  136198. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  136199. return iLangid;
  136200. }
  136201. /*
  136202. ** The first element in the apVal[] array is assumed to contain the docid
  136203. ** (an integer) of a row about to be deleted. Remove all terms from the
  136204. ** full-text index.
  136205. */
  136206. static void fts3DeleteTerms(
  136207. int *pRC, /* Result code */
  136208. Fts3Table *p, /* The FTS table to delete from */
  136209. sqlite3_value *pRowid, /* The docid to be deleted */
  136210. u32 *aSz, /* Sizes of deleted document written here */
  136211. int *pbFound /* OUT: Set to true if row really does exist */
  136212. ){
  136213. int rc;
  136214. sqlite3_stmt *pSelect;
  136215. assert( *pbFound==0 );
  136216. if( *pRC ) return;
  136217. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  136218. if( rc==SQLITE_OK ){
  136219. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  136220. int i;
  136221. int iLangid = langidFromSelect(p, pSelect);
  136222. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  136223. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  136224. int iCol = i-1;
  136225. if( p->abNotindexed[iCol]==0 ){
  136226. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  136227. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  136228. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  136229. }
  136230. }
  136231. if( rc!=SQLITE_OK ){
  136232. sqlite3_reset(pSelect);
  136233. *pRC = rc;
  136234. return;
  136235. }
  136236. *pbFound = 1;
  136237. }
  136238. rc = sqlite3_reset(pSelect);
  136239. }else{
  136240. sqlite3_reset(pSelect);
  136241. }
  136242. *pRC = rc;
  136243. }
  136244. /*
  136245. ** Forward declaration to account for the circular dependency between
  136246. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  136247. */
  136248. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  136249. /*
  136250. ** This function allocates a new level iLevel index in the segdir table.
  136251. ** Usually, indexes are allocated within a level sequentially starting
  136252. ** with 0, so the allocated index is one greater than the value returned
  136253. ** by:
  136254. **
  136255. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  136256. **
  136257. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  136258. ** level, they are merged into a single level (iLevel+1) segment and the
  136259. ** allocated index is 0.
  136260. **
  136261. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  136262. ** returned. Otherwise, an SQLite error code is returned.
  136263. */
  136264. static int fts3AllocateSegdirIdx(
  136265. Fts3Table *p,
  136266. int iLangid, /* Language id */
  136267. int iIndex, /* Index for p->aIndex */
  136268. int iLevel,
  136269. int *piIdx
  136270. ){
  136271. int rc; /* Return Code */
  136272. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  136273. int iNext = 0; /* Result of query pNextIdx */
  136274. assert( iLangid>=0 );
  136275. assert( p->nIndex>=1 );
  136276. /* Set variable iNext to the next available segdir index at level iLevel. */
  136277. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  136278. if( rc==SQLITE_OK ){
  136279. sqlite3_bind_int64(
  136280. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  136281. );
  136282. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  136283. iNext = sqlite3_column_int(pNextIdx, 0);
  136284. }
  136285. rc = sqlite3_reset(pNextIdx);
  136286. }
  136287. if( rc==SQLITE_OK ){
  136288. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  136289. ** full, merge all segments in level iLevel into a single iLevel+1
  136290. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  136291. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  136292. */
  136293. if( iNext>=FTS3_MERGE_COUNT ){
  136294. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  136295. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  136296. *piIdx = 0;
  136297. }else{
  136298. *piIdx = iNext;
  136299. }
  136300. }
  136301. return rc;
  136302. }
  136303. /*
  136304. ** The %_segments table is declared as follows:
  136305. **
  136306. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  136307. **
  136308. ** This function reads data from a single row of the %_segments table. The
  136309. ** specific row is identified by the iBlockid parameter. If paBlob is not
  136310. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  136311. ** with the contents of the blob stored in the "block" column of the
  136312. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  136313. ** to the size of the blob in bytes before returning.
  136314. **
  136315. ** If an error occurs, or the table does not contain the specified row,
  136316. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  136317. ** paBlob is non-NULL, then it is the responsibility of the caller to
  136318. ** eventually free the returned buffer.
  136319. **
  136320. ** This function may leave an open sqlite3_blob* handle in the
  136321. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  136322. ** to this function. The handle may be closed by calling the
  136323. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  136324. ** performance improvement, but the blob handle should always be closed
  136325. ** before control is returned to the user (to prevent a lock being held
  136326. ** on the database file for longer than necessary). Thus, any virtual table
  136327. ** method (xFilter etc.) that may directly or indirectly call this function
  136328. ** must call sqlite3Fts3SegmentsClose() before returning.
  136329. */
  136330. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  136331. Fts3Table *p, /* FTS3 table handle */
  136332. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  136333. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  136334. int *pnBlob, /* OUT: Size of blob data */
  136335. int *pnLoad /* OUT: Bytes actually loaded */
  136336. ){
  136337. int rc; /* Return code */
  136338. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  136339. assert( pnBlob );
  136340. if( p->pSegments ){
  136341. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  136342. }else{
  136343. if( 0==p->zSegmentsTbl ){
  136344. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  136345. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  136346. }
  136347. rc = sqlite3_blob_open(
  136348. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  136349. );
  136350. }
  136351. if( rc==SQLITE_OK ){
  136352. int nByte = sqlite3_blob_bytes(p->pSegments);
  136353. *pnBlob = nByte;
  136354. if( paBlob ){
  136355. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  136356. if( !aByte ){
  136357. rc = SQLITE_NOMEM;
  136358. }else{
  136359. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  136360. nByte = FTS3_NODE_CHUNKSIZE;
  136361. *pnLoad = nByte;
  136362. }
  136363. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  136364. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  136365. if( rc!=SQLITE_OK ){
  136366. sqlite3_free(aByte);
  136367. aByte = 0;
  136368. }
  136369. }
  136370. *paBlob = aByte;
  136371. }
  136372. }
  136373. return rc;
  136374. }
  136375. /*
  136376. ** Close the blob handle at p->pSegments, if it is open. See comments above
  136377. ** the sqlite3Fts3ReadBlock() function for details.
  136378. */
  136379. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  136380. sqlite3_blob_close(p->pSegments);
  136381. p->pSegments = 0;
  136382. }
  136383. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  136384. int nRead; /* Number of bytes to read */
  136385. int rc; /* Return code */
  136386. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  136387. rc = sqlite3_blob_read(
  136388. pReader->pBlob,
  136389. &pReader->aNode[pReader->nPopulate],
  136390. nRead,
  136391. pReader->nPopulate
  136392. );
  136393. if( rc==SQLITE_OK ){
  136394. pReader->nPopulate += nRead;
  136395. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  136396. if( pReader->nPopulate==pReader->nNode ){
  136397. sqlite3_blob_close(pReader->pBlob);
  136398. pReader->pBlob = 0;
  136399. pReader->nPopulate = 0;
  136400. }
  136401. }
  136402. return rc;
  136403. }
  136404. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  136405. int rc = SQLITE_OK;
  136406. assert( !pReader->pBlob
  136407. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  136408. );
  136409. while( pReader->pBlob && rc==SQLITE_OK
  136410. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  136411. ){
  136412. rc = fts3SegReaderIncrRead(pReader);
  136413. }
  136414. return rc;
  136415. }
  136416. /*
  136417. ** Set an Fts3SegReader cursor to point at EOF.
  136418. */
  136419. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  136420. if( !fts3SegReaderIsRootOnly(pSeg) ){
  136421. sqlite3_free(pSeg->aNode);
  136422. sqlite3_blob_close(pSeg->pBlob);
  136423. pSeg->pBlob = 0;
  136424. }
  136425. pSeg->aNode = 0;
  136426. }
  136427. /*
  136428. ** Move the iterator passed as the first argument to the next term in the
  136429. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  136430. ** SQLITE_DONE. Otherwise, an SQLite error code.
  136431. */
  136432. static int fts3SegReaderNext(
  136433. Fts3Table *p,
  136434. Fts3SegReader *pReader,
  136435. int bIncr
  136436. ){
  136437. int rc; /* Return code of various sub-routines */
  136438. char *pNext; /* Cursor variable */
  136439. int nPrefix; /* Number of bytes in term prefix */
  136440. int nSuffix; /* Number of bytes in term suffix */
  136441. if( !pReader->aDoclist ){
  136442. pNext = pReader->aNode;
  136443. }else{
  136444. pNext = &pReader->aDoclist[pReader->nDoclist];
  136445. }
  136446. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  136447. if( fts3SegReaderIsPending(pReader) ){
  136448. Fts3HashElem *pElem = *(pReader->ppNextElem);
  136449. if( pElem==0 ){
  136450. pReader->aNode = 0;
  136451. }else{
  136452. PendingList *pList = (PendingList *)fts3HashData(pElem);
  136453. pReader->zTerm = (char *)fts3HashKey(pElem);
  136454. pReader->nTerm = fts3HashKeysize(pElem);
  136455. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  136456. pReader->aNode = pReader->aDoclist = pList->aData;
  136457. pReader->ppNextElem++;
  136458. assert( pReader->aNode );
  136459. }
  136460. return SQLITE_OK;
  136461. }
  136462. fts3SegReaderSetEof(pReader);
  136463. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  136464. ** blocks have already been traversed. */
  136465. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  136466. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  136467. return SQLITE_OK;
  136468. }
  136469. rc = sqlite3Fts3ReadBlock(
  136470. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  136471. (bIncr ? &pReader->nPopulate : 0)
  136472. );
  136473. if( rc!=SQLITE_OK ) return rc;
  136474. assert( pReader->pBlob==0 );
  136475. if( bIncr && pReader->nPopulate<pReader->nNode ){
  136476. pReader->pBlob = p->pSegments;
  136477. p->pSegments = 0;
  136478. }
  136479. pNext = pReader->aNode;
  136480. }
  136481. assert( !fts3SegReaderIsPending(pReader) );
  136482. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  136483. if( rc!=SQLITE_OK ) return rc;
  136484. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  136485. ** safe (no risk of overread) even if the node data is corrupted. */
  136486. pNext += fts3GetVarint32(pNext, &nPrefix);
  136487. pNext += fts3GetVarint32(pNext, &nSuffix);
  136488. if( nPrefix<0 || nSuffix<=0
  136489. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  136490. ){
  136491. return FTS_CORRUPT_VTAB;
  136492. }
  136493. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  136494. int nNew = (nPrefix+nSuffix)*2;
  136495. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  136496. if( !zNew ){
  136497. return SQLITE_NOMEM;
  136498. }
  136499. pReader->zTerm = zNew;
  136500. pReader->nTermAlloc = nNew;
  136501. }
  136502. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  136503. if( rc!=SQLITE_OK ) return rc;
  136504. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  136505. pReader->nTerm = nPrefix+nSuffix;
  136506. pNext += nSuffix;
  136507. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  136508. pReader->aDoclist = pNext;
  136509. pReader->pOffsetList = 0;
  136510. /* Check that the doclist does not appear to extend past the end of the
  136511. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  136512. ** of these statements is untrue, then the data structure is corrupt.
  136513. */
  136514. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  136515. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  136516. ){
  136517. return FTS_CORRUPT_VTAB;
  136518. }
  136519. return SQLITE_OK;
  136520. }
  136521. /*
  136522. ** Set the SegReader to point to the first docid in the doclist associated
  136523. ** with the current term.
  136524. */
  136525. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  136526. int rc = SQLITE_OK;
  136527. assert( pReader->aDoclist );
  136528. assert( !pReader->pOffsetList );
  136529. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  136530. u8 bEof = 0;
  136531. pReader->iDocid = 0;
  136532. pReader->nOffsetList = 0;
  136533. sqlite3Fts3DoclistPrev(0,
  136534. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  136535. &pReader->iDocid, &pReader->nOffsetList, &bEof
  136536. );
  136537. }else{
  136538. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  136539. if( rc==SQLITE_OK ){
  136540. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  136541. pReader->pOffsetList = &pReader->aDoclist[n];
  136542. }
  136543. }
  136544. return rc;
  136545. }
  136546. /*
  136547. ** Advance the SegReader to point to the next docid in the doclist
  136548. ** associated with the current term.
  136549. **
  136550. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  136551. ** *ppOffsetList is set to point to the first column-offset list
  136552. ** in the doclist entry (i.e. immediately past the docid varint).
  136553. ** *pnOffsetList is set to the length of the set of column-offset
  136554. ** lists, not including the nul-terminator byte. For example:
  136555. */
  136556. static int fts3SegReaderNextDocid(
  136557. Fts3Table *pTab,
  136558. Fts3SegReader *pReader, /* Reader to advance to next docid */
  136559. char **ppOffsetList, /* OUT: Pointer to current position-list */
  136560. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  136561. ){
  136562. int rc = SQLITE_OK;
  136563. char *p = pReader->pOffsetList;
  136564. char c = 0;
  136565. assert( p );
  136566. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  136567. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  136568. ** Pending-terms doclists are always built up in ascending order, so
  136569. ** we have to iterate through them backwards here. */
  136570. u8 bEof = 0;
  136571. if( ppOffsetList ){
  136572. *ppOffsetList = pReader->pOffsetList;
  136573. *pnOffsetList = pReader->nOffsetList - 1;
  136574. }
  136575. sqlite3Fts3DoclistPrev(0,
  136576. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  136577. &pReader->nOffsetList, &bEof
  136578. );
  136579. if( bEof ){
  136580. pReader->pOffsetList = 0;
  136581. }else{
  136582. pReader->pOffsetList = p;
  136583. }
  136584. }else{
  136585. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  136586. /* Pointer p currently points at the first byte of an offset list. The
  136587. ** following block advances it to point one byte past the end of
  136588. ** the same offset list. */
  136589. while( 1 ){
  136590. /* The following line of code (and the "p++" below the while() loop) is
  136591. ** normally all that is required to move pointer p to the desired
  136592. ** position. The exception is if this node is being loaded from disk
  136593. ** incrementally and pointer "p" now points to the first byte past
  136594. ** the populated part of pReader->aNode[].
  136595. */
  136596. while( *p | c ) c = *p++ & 0x80;
  136597. assert( *p==0 );
  136598. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  136599. rc = fts3SegReaderIncrRead(pReader);
  136600. if( rc!=SQLITE_OK ) return rc;
  136601. }
  136602. p++;
  136603. /* If required, populate the output variables with a pointer to and the
  136604. ** size of the previous offset-list.
  136605. */
  136606. if( ppOffsetList ){
  136607. *ppOffsetList = pReader->pOffsetList;
  136608. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  136609. }
  136610. /* List may have been edited in place by fts3EvalNearTrim() */
  136611. while( p<pEnd && *p==0 ) p++;
  136612. /* If there are no more entries in the doclist, set pOffsetList to
  136613. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  136614. ** Fts3SegReader.pOffsetList to point to the next offset list before
  136615. ** returning.
  136616. */
  136617. if( p>=pEnd ){
  136618. pReader->pOffsetList = 0;
  136619. }else{
  136620. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  136621. if( rc==SQLITE_OK ){
  136622. sqlite3_int64 iDelta;
  136623. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  136624. if( pTab->bDescIdx ){
  136625. pReader->iDocid -= iDelta;
  136626. }else{
  136627. pReader->iDocid += iDelta;
  136628. }
  136629. }
  136630. }
  136631. }
  136632. return SQLITE_OK;
  136633. }
  136634. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  136635. Fts3Cursor *pCsr,
  136636. Fts3MultiSegReader *pMsr,
  136637. int *pnOvfl
  136638. ){
  136639. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  136640. int nOvfl = 0;
  136641. int ii;
  136642. int rc = SQLITE_OK;
  136643. int pgsz = p->nPgsz;
  136644. assert( p->bFts4 );
  136645. assert( pgsz>0 );
  136646. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  136647. Fts3SegReader *pReader = pMsr->apSegment[ii];
  136648. if( !fts3SegReaderIsPending(pReader)
  136649. && !fts3SegReaderIsRootOnly(pReader)
  136650. ){
  136651. sqlite3_int64 jj;
  136652. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  136653. int nBlob;
  136654. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  136655. if( rc!=SQLITE_OK ) break;
  136656. if( (nBlob+35)>pgsz ){
  136657. nOvfl += (nBlob + 34)/pgsz;
  136658. }
  136659. }
  136660. }
  136661. }
  136662. *pnOvfl = nOvfl;
  136663. return rc;
  136664. }
  136665. /*
  136666. ** Free all allocations associated with the iterator passed as the
  136667. ** second argument.
  136668. */
  136669. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  136670. if( pReader && !fts3SegReaderIsPending(pReader) ){
  136671. sqlite3_free(pReader->zTerm);
  136672. if( !fts3SegReaderIsRootOnly(pReader) ){
  136673. sqlite3_free(pReader->aNode);
  136674. sqlite3_blob_close(pReader->pBlob);
  136675. }
  136676. }
  136677. sqlite3_free(pReader);
  136678. }
  136679. /*
  136680. ** Allocate a new SegReader object.
  136681. */
  136682. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  136683. int iAge, /* Segment "age". */
  136684. int bLookup, /* True for a lookup only */
  136685. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  136686. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  136687. sqlite3_int64 iEndBlock, /* Final block of segment */
  136688. const char *zRoot, /* Buffer containing root node */
  136689. int nRoot, /* Size of buffer containing root node */
  136690. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  136691. ){
  136692. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  136693. int nExtra = 0; /* Bytes to allocate segment root node */
  136694. assert( iStartLeaf<=iEndLeaf );
  136695. if( iStartLeaf==0 ){
  136696. nExtra = nRoot + FTS3_NODE_PADDING;
  136697. }
  136698. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  136699. if( !pReader ){
  136700. return SQLITE_NOMEM;
  136701. }
  136702. memset(pReader, 0, sizeof(Fts3SegReader));
  136703. pReader->iIdx = iAge;
  136704. pReader->bLookup = bLookup!=0;
  136705. pReader->iStartBlock = iStartLeaf;
  136706. pReader->iLeafEndBlock = iEndLeaf;
  136707. pReader->iEndBlock = iEndBlock;
  136708. if( nExtra ){
  136709. /* The entire segment is stored in the root node. */
  136710. pReader->aNode = (char *)&pReader[1];
  136711. pReader->rootOnly = 1;
  136712. pReader->nNode = nRoot;
  136713. memcpy(pReader->aNode, zRoot, nRoot);
  136714. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  136715. }else{
  136716. pReader->iCurrentBlock = iStartLeaf-1;
  136717. }
  136718. *ppReader = pReader;
  136719. return SQLITE_OK;
  136720. }
  136721. /*
  136722. ** This is a comparison function used as a qsort() callback when sorting
  136723. ** an array of pending terms by term. This occurs as part of flushing
  136724. ** the contents of the pending-terms hash table to the database.
  136725. */
  136726. static int SQLITE_CDECL fts3CompareElemByTerm(
  136727. const void *lhs,
  136728. const void *rhs
  136729. ){
  136730. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  136731. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  136732. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  136733. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  136734. int n = (n1<n2 ? n1 : n2);
  136735. int c = memcmp(z1, z2, n);
  136736. if( c==0 ){
  136737. c = n1 - n2;
  136738. }
  136739. return c;
  136740. }
  136741. /*
  136742. ** This function is used to allocate an Fts3SegReader that iterates through
  136743. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  136744. **
  136745. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  136746. ** through each term in the pending-terms table. Or, if isPrefixIter is
  136747. ** non-zero, it iterates through each term and its prefixes. For example, if
  136748. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  136749. ** "firebird", then the iterator visits the following 'terms' (in the order
  136750. ** shown):
  136751. **
  136752. ** f fi fir fire fireb firebi firebir firebird
  136753. ** m my mys mysq mysql
  136754. ** s sq sql sqli sqlit sqlite
  136755. **
  136756. ** Whereas if isPrefixIter is zero, the terms visited are:
  136757. **
  136758. ** firebird mysql sqlite
  136759. */
  136760. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  136761. Fts3Table *p, /* Virtual table handle */
  136762. int iIndex, /* Index for p->aIndex */
  136763. const char *zTerm, /* Term to search for */
  136764. int nTerm, /* Size of buffer zTerm */
  136765. int bPrefix, /* True for a prefix iterator */
  136766. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  136767. ){
  136768. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  136769. Fts3HashElem *pE; /* Iterator variable */
  136770. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  136771. int nElem = 0; /* Size of array at aElem */
  136772. int rc = SQLITE_OK; /* Return Code */
  136773. Fts3Hash *pHash;
  136774. pHash = &p->aIndex[iIndex].hPending;
  136775. if( bPrefix ){
  136776. int nAlloc = 0; /* Size of allocated array at aElem */
  136777. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  136778. char *zKey = (char *)fts3HashKey(pE);
  136779. int nKey = fts3HashKeysize(pE);
  136780. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  136781. if( nElem==nAlloc ){
  136782. Fts3HashElem **aElem2;
  136783. nAlloc += 16;
  136784. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  136785. aElem, nAlloc*sizeof(Fts3HashElem *)
  136786. );
  136787. if( !aElem2 ){
  136788. rc = SQLITE_NOMEM;
  136789. nElem = 0;
  136790. break;
  136791. }
  136792. aElem = aElem2;
  136793. }
  136794. aElem[nElem++] = pE;
  136795. }
  136796. }
  136797. /* If more than one term matches the prefix, sort the Fts3HashElem
  136798. ** objects in term order using qsort(). This uses the same comparison
  136799. ** callback as is used when flushing terms to disk.
  136800. */
  136801. if( nElem>1 ){
  136802. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  136803. }
  136804. }else{
  136805. /* The query is a simple term lookup that matches at most one term in
  136806. ** the index. All that is required is a straight hash-lookup.
  136807. **
  136808. ** Because the stack address of pE may be accessed via the aElem pointer
  136809. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  136810. ** within this entire function, not just this "else{...}" block.
  136811. */
  136812. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  136813. if( pE ){
  136814. aElem = &pE;
  136815. nElem = 1;
  136816. }
  136817. }
  136818. if( nElem>0 ){
  136819. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  136820. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  136821. if( !pReader ){
  136822. rc = SQLITE_NOMEM;
  136823. }else{
  136824. memset(pReader, 0, nByte);
  136825. pReader->iIdx = 0x7FFFFFFF;
  136826. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  136827. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  136828. }
  136829. }
  136830. if( bPrefix ){
  136831. sqlite3_free(aElem);
  136832. }
  136833. *ppReader = pReader;
  136834. return rc;
  136835. }
  136836. /*
  136837. ** Compare the entries pointed to by two Fts3SegReader structures.
  136838. ** Comparison is as follows:
  136839. **
  136840. ** 1) EOF is greater than not EOF.
  136841. **
  136842. ** 2) The current terms (if any) are compared using memcmp(). If one
  136843. ** term is a prefix of another, the longer term is considered the
  136844. ** larger.
  136845. **
  136846. ** 3) By segment age. An older segment is considered larger.
  136847. */
  136848. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  136849. int rc;
  136850. if( pLhs->aNode && pRhs->aNode ){
  136851. int rc2 = pLhs->nTerm - pRhs->nTerm;
  136852. if( rc2<0 ){
  136853. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  136854. }else{
  136855. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  136856. }
  136857. if( rc==0 ){
  136858. rc = rc2;
  136859. }
  136860. }else{
  136861. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  136862. }
  136863. if( rc==0 ){
  136864. rc = pRhs->iIdx - pLhs->iIdx;
  136865. }
  136866. assert( rc!=0 );
  136867. return rc;
  136868. }
  136869. /*
  136870. ** A different comparison function for SegReader structures. In this
  136871. ** version, it is assumed that each SegReader points to an entry in
  136872. ** a doclist for identical terms. Comparison is made as follows:
  136873. **
  136874. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  136875. **
  136876. ** 2) By current docid.
  136877. **
  136878. ** 3) By segment age. An older segment is considered larger.
  136879. */
  136880. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  136881. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  136882. if( rc==0 ){
  136883. if( pLhs->iDocid==pRhs->iDocid ){
  136884. rc = pRhs->iIdx - pLhs->iIdx;
  136885. }else{
  136886. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  136887. }
  136888. }
  136889. assert( pLhs->aNode && pRhs->aNode );
  136890. return rc;
  136891. }
  136892. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  136893. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  136894. if( rc==0 ){
  136895. if( pLhs->iDocid==pRhs->iDocid ){
  136896. rc = pRhs->iIdx - pLhs->iIdx;
  136897. }else{
  136898. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  136899. }
  136900. }
  136901. assert( pLhs->aNode && pRhs->aNode );
  136902. return rc;
  136903. }
  136904. /*
  136905. ** Compare the term that the Fts3SegReader object passed as the first argument
  136906. ** points to with the term specified by arguments zTerm and nTerm.
  136907. **
  136908. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  136909. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  136910. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  136911. */
  136912. static int fts3SegReaderTermCmp(
  136913. Fts3SegReader *pSeg, /* Segment reader object */
  136914. const char *zTerm, /* Term to compare to */
  136915. int nTerm /* Size of term zTerm in bytes */
  136916. ){
  136917. int res = 0;
  136918. if( pSeg->aNode ){
  136919. if( pSeg->nTerm>nTerm ){
  136920. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  136921. }else{
  136922. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  136923. }
  136924. if( res==0 ){
  136925. res = pSeg->nTerm-nTerm;
  136926. }
  136927. }
  136928. return res;
  136929. }
  136930. /*
  136931. ** Argument apSegment is an array of nSegment elements. It is known that
  136932. ** the final (nSegment-nSuspect) members are already in sorted order
  136933. ** (according to the comparison function provided). This function shuffles
  136934. ** the array around until all entries are in sorted order.
  136935. */
  136936. static void fts3SegReaderSort(
  136937. Fts3SegReader **apSegment, /* Array to sort entries of */
  136938. int nSegment, /* Size of apSegment array */
  136939. int nSuspect, /* Unsorted entry count */
  136940. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  136941. ){
  136942. int i; /* Iterator variable */
  136943. assert( nSuspect<=nSegment );
  136944. if( nSuspect==nSegment ) nSuspect--;
  136945. for(i=nSuspect-1; i>=0; i--){
  136946. int j;
  136947. for(j=i; j<(nSegment-1); j++){
  136948. Fts3SegReader *pTmp;
  136949. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  136950. pTmp = apSegment[j+1];
  136951. apSegment[j+1] = apSegment[j];
  136952. apSegment[j] = pTmp;
  136953. }
  136954. }
  136955. #ifndef NDEBUG
  136956. /* Check that the list really is sorted now. */
  136957. for(i=0; i<(nSuspect-1); i++){
  136958. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  136959. }
  136960. #endif
  136961. }
  136962. /*
  136963. ** Insert a record into the %_segments table.
  136964. */
  136965. static int fts3WriteSegment(
  136966. Fts3Table *p, /* Virtual table handle */
  136967. sqlite3_int64 iBlock, /* Block id for new block */
  136968. char *z, /* Pointer to buffer containing block data */
  136969. int n /* Size of buffer z in bytes */
  136970. ){
  136971. sqlite3_stmt *pStmt;
  136972. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  136973. if( rc==SQLITE_OK ){
  136974. sqlite3_bind_int64(pStmt, 1, iBlock);
  136975. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  136976. sqlite3_step(pStmt);
  136977. rc = sqlite3_reset(pStmt);
  136978. }
  136979. return rc;
  136980. }
  136981. /*
  136982. ** Find the largest relative level number in the table. If successful, set
  136983. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  136984. ** set *pnMax to zero and return an SQLite error code.
  136985. */
  136986. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  136987. int rc;
  136988. int mxLevel = 0;
  136989. sqlite3_stmt *pStmt = 0;
  136990. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  136991. if( rc==SQLITE_OK ){
  136992. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  136993. mxLevel = sqlite3_column_int(pStmt, 0);
  136994. }
  136995. rc = sqlite3_reset(pStmt);
  136996. }
  136997. *pnMax = mxLevel;
  136998. return rc;
  136999. }
  137000. /*
  137001. ** Insert a record into the %_segdir table.
  137002. */
  137003. static int fts3WriteSegdir(
  137004. Fts3Table *p, /* Virtual table handle */
  137005. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  137006. int iIdx, /* Value for "idx" field */
  137007. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  137008. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  137009. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  137010. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  137011. char *zRoot, /* Blob value for "root" field */
  137012. int nRoot /* Number of bytes in buffer zRoot */
  137013. ){
  137014. sqlite3_stmt *pStmt;
  137015. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  137016. if( rc==SQLITE_OK ){
  137017. sqlite3_bind_int64(pStmt, 1, iLevel);
  137018. sqlite3_bind_int(pStmt, 2, iIdx);
  137019. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  137020. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  137021. if( nLeafData==0 ){
  137022. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  137023. }else{
  137024. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  137025. if( !zEnd ) return SQLITE_NOMEM;
  137026. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  137027. }
  137028. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  137029. sqlite3_step(pStmt);
  137030. rc = sqlite3_reset(pStmt);
  137031. }
  137032. return rc;
  137033. }
  137034. /*
  137035. ** Return the size of the common prefix (if any) shared by zPrev and
  137036. ** zNext, in bytes. For example,
  137037. **
  137038. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  137039. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  137040. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  137041. */
  137042. static int fts3PrefixCompress(
  137043. const char *zPrev, /* Buffer containing previous term */
  137044. int nPrev, /* Size of buffer zPrev in bytes */
  137045. const char *zNext, /* Buffer containing next term */
  137046. int nNext /* Size of buffer zNext in bytes */
  137047. ){
  137048. int n;
  137049. UNUSED_PARAMETER(nNext);
  137050. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  137051. return n;
  137052. }
  137053. /*
  137054. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  137055. ** (according to memcmp) than the previous term.
  137056. */
  137057. static int fts3NodeAddTerm(
  137058. Fts3Table *p, /* Virtual table handle */
  137059. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  137060. int isCopyTerm, /* True if zTerm/nTerm is transient */
  137061. const char *zTerm, /* Pointer to buffer containing term */
  137062. int nTerm /* Size of term in bytes */
  137063. ){
  137064. SegmentNode *pTree = *ppTree;
  137065. int rc;
  137066. SegmentNode *pNew;
  137067. /* First try to append the term to the current node. Return early if
  137068. ** this is possible.
  137069. */
  137070. if( pTree ){
  137071. int nData = pTree->nData; /* Current size of node in bytes */
  137072. int nReq = nData; /* Required space after adding zTerm */
  137073. int nPrefix; /* Number of bytes of prefix compression */
  137074. int nSuffix; /* Suffix length */
  137075. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  137076. nSuffix = nTerm-nPrefix;
  137077. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  137078. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  137079. if( nReq>p->nNodeSize ){
  137080. /* An unusual case: this is the first term to be added to the node
  137081. ** and the static node buffer (p->nNodeSize bytes) is not large
  137082. ** enough. Use a separately malloced buffer instead This wastes
  137083. ** p->nNodeSize bytes, but since this scenario only comes about when
  137084. ** the database contain two terms that share a prefix of almost 2KB,
  137085. ** this is not expected to be a serious problem.
  137086. */
  137087. assert( pTree->aData==(char *)&pTree[1] );
  137088. pTree->aData = (char *)sqlite3_malloc(nReq);
  137089. if( !pTree->aData ){
  137090. return SQLITE_NOMEM;
  137091. }
  137092. }
  137093. if( pTree->zTerm ){
  137094. /* There is no prefix-length field for first term in a node */
  137095. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  137096. }
  137097. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  137098. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  137099. pTree->nData = nData + nSuffix;
  137100. pTree->nEntry++;
  137101. if( isCopyTerm ){
  137102. if( pTree->nMalloc<nTerm ){
  137103. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  137104. if( !zNew ){
  137105. return SQLITE_NOMEM;
  137106. }
  137107. pTree->nMalloc = nTerm*2;
  137108. pTree->zMalloc = zNew;
  137109. }
  137110. pTree->zTerm = pTree->zMalloc;
  137111. memcpy(pTree->zTerm, zTerm, nTerm);
  137112. pTree->nTerm = nTerm;
  137113. }else{
  137114. pTree->zTerm = (char *)zTerm;
  137115. pTree->nTerm = nTerm;
  137116. }
  137117. return SQLITE_OK;
  137118. }
  137119. }
  137120. /* If control flows to here, it was not possible to append zTerm to the
  137121. ** current node. Create a new node (a right-sibling of the current node).
  137122. ** If this is the first node in the tree, the term is added to it.
  137123. **
  137124. ** Otherwise, the term is not added to the new node, it is left empty for
  137125. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  137126. ** has no parent, one is created here.
  137127. */
  137128. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  137129. if( !pNew ){
  137130. return SQLITE_NOMEM;
  137131. }
  137132. memset(pNew, 0, sizeof(SegmentNode));
  137133. pNew->nData = 1 + FTS3_VARINT_MAX;
  137134. pNew->aData = (char *)&pNew[1];
  137135. if( pTree ){
  137136. SegmentNode *pParent = pTree->pParent;
  137137. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  137138. if( pTree->pParent==0 ){
  137139. pTree->pParent = pParent;
  137140. }
  137141. pTree->pRight = pNew;
  137142. pNew->pLeftmost = pTree->pLeftmost;
  137143. pNew->pParent = pParent;
  137144. pNew->zMalloc = pTree->zMalloc;
  137145. pNew->nMalloc = pTree->nMalloc;
  137146. pTree->zMalloc = 0;
  137147. }else{
  137148. pNew->pLeftmost = pNew;
  137149. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  137150. }
  137151. *ppTree = pNew;
  137152. return rc;
  137153. }
  137154. /*
  137155. ** Helper function for fts3NodeWrite().
  137156. */
  137157. static int fts3TreeFinishNode(
  137158. SegmentNode *pTree,
  137159. int iHeight,
  137160. sqlite3_int64 iLeftChild
  137161. ){
  137162. int nStart;
  137163. assert( iHeight>=1 && iHeight<128 );
  137164. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  137165. pTree->aData[nStart] = (char)iHeight;
  137166. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  137167. return nStart;
  137168. }
  137169. /*
  137170. ** Write the buffer for the segment node pTree and all of its peers to the
  137171. ** database. Then call this function recursively to write the parent of
  137172. ** pTree and its peers to the database.
  137173. **
  137174. ** Except, if pTree is a root node, do not write it to the database. Instead,
  137175. ** set output variables *paRoot and *pnRoot to contain the root node.
  137176. **
  137177. ** If successful, SQLITE_OK is returned and output variable *piLast is
  137178. ** set to the largest blockid written to the database (or zero if no
  137179. ** blocks were written to the db). Otherwise, an SQLite error code is
  137180. ** returned.
  137181. */
  137182. static int fts3NodeWrite(
  137183. Fts3Table *p, /* Virtual table handle */
  137184. SegmentNode *pTree, /* SegmentNode handle */
  137185. int iHeight, /* Height of this node in tree */
  137186. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  137187. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  137188. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  137189. char **paRoot, /* OUT: Data for root node */
  137190. int *pnRoot /* OUT: Size of root node in bytes */
  137191. ){
  137192. int rc = SQLITE_OK;
  137193. if( !pTree->pParent ){
  137194. /* Root node of the tree. */
  137195. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  137196. *piLast = iFree-1;
  137197. *pnRoot = pTree->nData - nStart;
  137198. *paRoot = &pTree->aData[nStart];
  137199. }else{
  137200. SegmentNode *pIter;
  137201. sqlite3_int64 iNextFree = iFree;
  137202. sqlite3_int64 iNextLeaf = iLeaf;
  137203. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  137204. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  137205. int nWrite = pIter->nData - nStart;
  137206. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  137207. iNextFree++;
  137208. iNextLeaf += (pIter->nEntry+1);
  137209. }
  137210. if( rc==SQLITE_OK ){
  137211. assert( iNextLeaf==iFree );
  137212. rc = fts3NodeWrite(
  137213. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  137214. );
  137215. }
  137216. }
  137217. return rc;
  137218. }
  137219. /*
  137220. ** Free all memory allocations associated with the tree pTree.
  137221. */
  137222. static void fts3NodeFree(SegmentNode *pTree){
  137223. if( pTree ){
  137224. SegmentNode *p = pTree->pLeftmost;
  137225. fts3NodeFree(p->pParent);
  137226. while( p ){
  137227. SegmentNode *pRight = p->pRight;
  137228. if( p->aData!=(char *)&p[1] ){
  137229. sqlite3_free(p->aData);
  137230. }
  137231. assert( pRight==0 || p->zMalloc==0 );
  137232. sqlite3_free(p->zMalloc);
  137233. sqlite3_free(p);
  137234. p = pRight;
  137235. }
  137236. }
  137237. }
  137238. /*
  137239. ** Add a term to the segment being constructed by the SegmentWriter object
  137240. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  137241. ** be passed NULL. This function will allocate a new SegmentWriter object
  137242. ** and return it via the input/output variable *ppWriter in this case.
  137243. **
  137244. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  137245. */
  137246. static int fts3SegWriterAdd(
  137247. Fts3Table *p, /* Virtual table handle */
  137248. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  137249. int isCopyTerm, /* True if buffer zTerm must be copied */
  137250. const char *zTerm, /* Pointer to buffer containing term */
  137251. int nTerm, /* Size of term in bytes */
  137252. const char *aDoclist, /* Pointer to buffer containing doclist */
  137253. int nDoclist /* Size of doclist in bytes */
  137254. ){
  137255. int nPrefix; /* Size of term prefix in bytes */
  137256. int nSuffix; /* Size of term suffix in bytes */
  137257. int nReq; /* Number of bytes required on leaf page */
  137258. int nData;
  137259. SegmentWriter *pWriter = *ppWriter;
  137260. if( !pWriter ){
  137261. int rc;
  137262. sqlite3_stmt *pStmt;
  137263. /* Allocate the SegmentWriter structure */
  137264. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  137265. if( !pWriter ) return SQLITE_NOMEM;
  137266. memset(pWriter, 0, sizeof(SegmentWriter));
  137267. *ppWriter = pWriter;
  137268. /* Allocate a buffer in which to accumulate data */
  137269. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  137270. if( !pWriter->aData ) return SQLITE_NOMEM;
  137271. pWriter->nSize = p->nNodeSize;
  137272. /* Find the next free blockid in the %_segments table */
  137273. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  137274. if( rc!=SQLITE_OK ) return rc;
  137275. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  137276. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  137277. pWriter->iFirst = pWriter->iFree;
  137278. }
  137279. rc = sqlite3_reset(pStmt);
  137280. if( rc!=SQLITE_OK ) return rc;
  137281. }
  137282. nData = pWriter->nData;
  137283. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  137284. nSuffix = nTerm-nPrefix;
  137285. /* Figure out how many bytes are required by this new entry */
  137286. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  137287. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  137288. nSuffix + /* Term suffix */
  137289. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  137290. nDoclist; /* Doclist data */
  137291. if( nData>0 && nData+nReq>p->nNodeSize ){
  137292. int rc;
  137293. /* The current leaf node is full. Write it out to the database. */
  137294. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  137295. if( rc!=SQLITE_OK ) return rc;
  137296. p->nLeafAdd++;
  137297. /* Add the current term to the interior node tree. The term added to
  137298. ** the interior tree must:
  137299. **
  137300. ** a) be greater than the largest term on the leaf node just written
  137301. ** to the database (still available in pWriter->zTerm), and
  137302. **
  137303. ** b) be less than or equal to the term about to be added to the new
  137304. ** leaf node (zTerm/nTerm).
  137305. **
  137306. ** In other words, it must be the prefix of zTerm 1 byte longer than
  137307. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  137308. */
  137309. assert( nPrefix<nTerm );
  137310. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  137311. if( rc!=SQLITE_OK ) return rc;
  137312. nData = 0;
  137313. pWriter->nTerm = 0;
  137314. nPrefix = 0;
  137315. nSuffix = nTerm;
  137316. nReq = 1 + /* varint containing prefix size */
  137317. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  137318. nTerm + /* Term suffix */
  137319. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  137320. nDoclist; /* Doclist data */
  137321. }
  137322. /* Increase the total number of bytes written to account for the new entry. */
  137323. pWriter->nLeafData += nReq;
  137324. /* If the buffer currently allocated is too small for this entry, realloc
  137325. ** the buffer to make it large enough.
  137326. */
  137327. if( nReq>pWriter->nSize ){
  137328. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  137329. if( !aNew ) return SQLITE_NOMEM;
  137330. pWriter->aData = aNew;
  137331. pWriter->nSize = nReq;
  137332. }
  137333. assert( nData+nReq<=pWriter->nSize );
  137334. /* Append the prefix-compressed term and doclist to the buffer. */
  137335. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  137336. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  137337. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  137338. nData += nSuffix;
  137339. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  137340. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  137341. pWriter->nData = nData + nDoclist;
  137342. /* Save the current term so that it can be used to prefix-compress the next.
  137343. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  137344. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  137345. ** store a copy of the pointer.
  137346. */
  137347. if( isCopyTerm ){
  137348. if( nTerm>pWriter->nMalloc ){
  137349. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  137350. if( !zNew ){
  137351. return SQLITE_NOMEM;
  137352. }
  137353. pWriter->nMalloc = nTerm*2;
  137354. pWriter->zMalloc = zNew;
  137355. pWriter->zTerm = zNew;
  137356. }
  137357. assert( pWriter->zTerm==pWriter->zMalloc );
  137358. memcpy(pWriter->zTerm, zTerm, nTerm);
  137359. }else{
  137360. pWriter->zTerm = (char *)zTerm;
  137361. }
  137362. pWriter->nTerm = nTerm;
  137363. return SQLITE_OK;
  137364. }
  137365. /*
  137366. ** Flush all data associated with the SegmentWriter object pWriter to the
  137367. ** database. This function must be called after all terms have been added
  137368. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  137369. ** returned. Otherwise, an SQLite error code.
  137370. */
  137371. static int fts3SegWriterFlush(
  137372. Fts3Table *p, /* Virtual table handle */
  137373. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  137374. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  137375. int iIdx /* Value for 'idx' column of %_segdir */
  137376. ){
  137377. int rc; /* Return code */
  137378. if( pWriter->pTree ){
  137379. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  137380. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  137381. char *zRoot = NULL; /* Pointer to buffer containing root node */
  137382. int nRoot = 0; /* Size of buffer zRoot */
  137383. iLastLeaf = pWriter->iFree;
  137384. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  137385. if( rc==SQLITE_OK ){
  137386. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  137387. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  137388. }
  137389. if( rc==SQLITE_OK ){
  137390. rc = fts3WriteSegdir(p, iLevel, iIdx,
  137391. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  137392. }
  137393. }else{
  137394. /* The entire tree fits on the root node. Write it to the segdir table. */
  137395. rc = fts3WriteSegdir(p, iLevel, iIdx,
  137396. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  137397. }
  137398. p->nLeafAdd++;
  137399. return rc;
  137400. }
  137401. /*
  137402. ** Release all memory held by the SegmentWriter object passed as the
  137403. ** first argument.
  137404. */
  137405. static void fts3SegWriterFree(SegmentWriter *pWriter){
  137406. if( pWriter ){
  137407. sqlite3_free(pWriter->aData);
  137408. sqlite3_free(pWriter->zMalloc);
  137409. fts3NodeFree(pWriter->pTree);
  137410. sqlite3_free(pWriter);
  137411. }
  137412. }
  137413. /*
  137414. ** The first value in the apVal[] array is assumed to contain an integer.
  137415. ** This function tests if there exist any documents with docid values that
  137416. ** are different from that integer. i.e. if deleting the document with docid
  137417. ** pRowid would mean the FTS3 table were empty.
  137418. **
  137419. ** If successful, *pisEmpty is set to true if the table is empty except for
  137420. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  137421. ** error occurs, an SQLite error code is returned.
  137422. */
  137423. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  137424. sqlite3_stmt *pStmt;
  137425. int rc;
  137426. if( p->zContentTbl ){
  137427. /* If using the content=xxx option, assume the table is never empty */
  137428. *pisEmpty = 0;
  137429. rc = SQLITE_OK;
  137430. }else{
  137431. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  137432. if( rc==SQLITE_OK ){
  137433. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  137434. *pisEmpty = sqlite3_column_int(pStmt, 0);
  137435. }
  137436. rc = sqlite3_reset(pStmt);
  137437. }
  137438. }
  137439. return rc;
  137440. }
  137441. /*
  137442. ** Set *pnMax to the largest segment level in the database for the index
  137443. ** iIndex.
  137444. **
  137445. ** Segment levels are stored in the 'level' column of the %_segdir table.
  137446. **
  137447. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  137448. */
  137449. static int fts3SegmentMaxLevel(
  137450. Fts3Table *p,
  137451. int iLangid,
  137452. int iIndex,
  137453. sqlite3_int64 *pnMax
  137454. ){
  137455. sqlite3_stmt *pStmt;
  137456. int rc;
  137457. assert( iIndex>=0 && iIndex<p->nIndex );
  137458. /* Set pStmt to the compiled version of:
  137459. **
  137460. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  137461. **
  137462. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  137463. */
  137464. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  137465. if( rc!=SQLITE_OK ) return rc;
  137466. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  137467. sqlite3_bind_int64(pStmt, 2,
  137468. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  137469. );
  137470. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  137471. *pnMax = sqlite3_column_int64(pStmt, 0);
  137472. }
  137473. return sqlite3_reset(pStmt);
  137474. }
  137475. /*
  137476. ** iAbsLevel is an absolute level that may be assumed to exist within
  137477. ** the database. This function checks if it is the largest level number
  137478. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  137479. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  137480. ** is returned. If an error occurs, an error code is returned and the
  137481. ** final value of *pbMax is undefined.
  137482. */
  137483. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  137484. /* Set pStmt to the compiled version of:
  137485. **
  137486. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  137487. **
  137488. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  137489. */
  137490. sqlite3_stmt *pStmt;
  137491. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  137492. if( rc!=SQLITE_OK ) return rc;
  137493. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  137494. sqlite3_bind_int64(pStmt, 2,
  137495. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  137496. );
  137497. *pbMax = 0;
  137498. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  137499. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  137500. }
  137501. return sqlite3_reset(pStmt);
  137502. }
  137503. /*
  137504. ** Delete all entries in the %_segments table associated with the segment
  137505. ** opened with seg-reader pSeg. This function does not affect the contents
  137506. ** of the %_segdir table.
  137507. */
  137508. static int fts3DeleteSegment(
  137509. Fts3Table *p, /* FTS table handle */
  137510. Fts3SegReader *pSeg /* Segment to delete */
  137511. ){
  137512. int rc = SQLITE_OK; /* Return code */
  137513. if( pSeg->iStartBlock ){
  137514. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  137515. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  137516. if( rc==SQLITE_OK ){
  137517. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  137518. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  137519. sqlite3_step(pDelete);
  137520. rc = sqlite3_reset(pDelete);
  137521. }
  137522. }
  137523. return rc;
  137524. }
  137525. /*
  137526. ** This function is used after merging multiple segments into a single large
  137527. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  137528. ** it:
  137529. **
  137530. ** 1) Deletes all %_segments entries for the segments associated with
  137531. ** each of the SegReader objects in the array passed as the third
  137532. ** argument, and
  137533. **
  137534. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  137535. ** entries regardless of level if (iLevel<0).
  137536. **
  137537. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  137538. */
  137539. static int fts3DeleteSegdir(
  137540. Fts3Table *p, /* Virtual table handle */
  137541. int iLangid, /* Language id */
  137542. int iIndex, /* Index for p->aIndex */
  137543. int iLevel, /* Level of %_segdir entries to delete */
  137544. Fts3SegReader **apSegment, /* Array of SegReader objects */
  137545. int nReader /* Size of array apSegment */
  137546. ){
  137547. int rc = SQLITE_OK; /* Return Code */
  137548. int i; /* Iterator variable */
  137549. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  137550. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  137551. rc = fts3DeleteSegment(p, apSegment[i]);
  137552. }
  137553. if( rc!=SQLITE_OK ){
  137554. return rc;
  137555. }
  137556. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  137557. if( iLevel==FTS3_SEGCURSOR_ALL ){
  137558. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  137559. if( rc==SQLITE_OK ){
  137560. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  137561. sqlite3_bind_int64(pDelete, 2,
  137562. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  137563. );
  137564. }
  137565. }else{
  137566. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  137567. if( rc==SQLITE_OK ){
  137568. sqlite3_bind_int64(
  137569. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  137570. );
  137571. }
  137572. }
  137573. if( rc==SQLITE_OK ){
  137574. sqlite3_step(pDelete);
  137575. rc = sqlite3_reset(pDelete);
  137576. }
  137577. return rc;
  137578. }
  137579. /*
  137580. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  137581. ** a position list that may (or may not) feature multiple columns. This
  137582. ** function adjusts the pointer *ppList and the length *pnList so that they
  137583. ** identify the subset of the position list that corresponds to column iCol.
  137584. **
  137585. ** If there are no entries in the input position list for column iCol, then
  137586. ** *pnList is set to zero before returning.
  137587. **
  137588. ** If parameter bZero is non-zero, then any part of the input list following
  137589. ** the end of the output list is zeroed before returning.
  137590. */
  137591. static void fts3ColumnFilter(
  137592. int iCol, /* Column to filter on */
  137593. int bZero, /* Zero out anything following *ppList */
  137594. char **ppList, /* IN/OUT: Pointer to position list */
  137595. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  137596. ){
  137597. char *pList = *ppList;
  137598. int nList = *pnList;
  137599. char *pEnd = &pList[nList];
  137600. int iCurrent = 0;
  137601. char *p = pList;
  137602. assert( iCol>=0 );
  137603. while( 1 ){
  137604. char c = 0;
  137605. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  137606. if( iCol==iCurrent ){
  137607. nList = (int)(p - pList);
  137608. break;
  137609. }
  137610. nList -= (int)(p - pList);
  137611. pList = p;
  137612. if( nList==0 ){
  137613. break;
  137614. }
  137615. p = &pList[1];
  137616. p += fts3GetVarint32(p, &iCurrent);
  137617. }
  137618. if( bZero && &pList[nList]!=pEnd ){
  137619. memset(&pList[nList], 0, pEnd - &pList[nList]);
  137620. }
  137621. *ppList = pList;
  137622. *pnList = nList;
  137623. }
  137624. /*
  137625. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  137626. ** existing data). Grow the buffer if required.
  137627. **
  137628. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  137629. ** trying to resize the buffer, return SQLITE_NOMEM.
  137630. */
  137631. static int fts3MsrBufferData(
  137632. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  137633. char *pList,
  137634. int nList
  137635. ){
  137636. if( nList>pMsr->nBuffer ){
  137637. char *pNew;
  137638. pMsr->nBuffer = nList*2;
  137639. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  137640. if( !pNew ) return SQLITE_NOMEM;
  137641. pMsr->aBuffer = pNew;
  137642. }
  137643. memcpy(pMsr->aBuffer, pList, nList);
  137644. return SQLITE_OK;
  137645. }
  137646. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  137647. Fts3Table *p, /* Virtual table handle */
  137648. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  137649. sqlite3_int64 *piDocid, /* OUT: Docid value */
  137650. char **paPoslist, /* OUT: Pointer to position list */
  137651. int *pnPoslist /* OUT: Size of position list in bytes */
  137652. ){
  137653. int nMerge = pMsr->nAdvance;
  137654. Fts3SegReader **apSegment = pMsr->apSegment;
  137655. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  137656. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  137657. );
  137658. if( nMerge==0 ){
  137659. *paPoslist = 0;
  137660. return SQLITE_OK;
  137661. }
  137662. while( 1 ){
  137663. Fts3SegReader *pSeg;
  137664. pSeg = pMsr->apSegment[0];
  137665. if( pSeg->pOffsetList==0 ){
  137666. *paPoslist = 0;
  137667. break;
  137668. }else{
  137669. int rc;
  137670. char *pList;
  137671. int nList;
  137672. int j;
  137673. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  137674. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  137675. j = 1;
  137676. while( rc==SQLITE_OK
  137677. && j<nMerge
  137678. && apSegment[j]->pOffsetList
  137679. && apSegment[j]->iDocid==iDocid
  137680. ){
  137681. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  137682. j++;
  137683. }
  137684. if( rc!=SQLITE_OK ) return rc;
  137685. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  137686. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  137687. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  137688. if( rc!=SQLITE_OK ) return rc;
  137689. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  137690. pList = pMsr->aBuffer;
  137691. }
  137692. if( pMsr->iColFilter>=0 ){
  137693. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  137694. }
  137695. if( nList>0 ){
  137696. *paPoslist = pList;
  137697. *piDocid = iDocid;
  137698. *pnPoslist = nList;
  137699. break;
  137700. }
  137701. }
  137702. }
  137703. return SQLITE_OK;
  137704. }
  137705. static int fts3SegReaderStart(
  137706. Fts3Table *p, /* Virtual table handle */
  137707. Fts3MultiSegReader *pCsr, /* Cursor object */
  137708. const char *zTerm, /* Term searched for (or NULL) */
  137709. int nTerm /* Length of zTerm in bytes */
  137710. ){
  137711. int i;
  137712. int nSeg = pCsr->nSegment;
  137713. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  137714. ** for, then advance each segment iterator until it points to a term of
  137715. ** equal or greater value than the specified term. This prevents many
  137716. ** unnecessary merge/sort operations for the case where single segment
  137717. ** b-tree leaf nodes contain more than one term.
  137718. */
  137719. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  137720. int res = 0;
  137721. Fts3SegReader *pSeg = pCsr->apSegment[i];
  137722. do {
  137723. int rc = fts3SegReaderNext(p, pSeg, 0);
  137724. if( rc!=SQLITE_OK ) return rc;
  137725. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  137726. if( pSeg->bLookup && res!=0 ){
  137727. fts3SegReaderSetEof(pSeg);
  137728. }
  137729. }
  137730. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  137731. return SQLITE_OK;
  137732. }
  137733. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  137734. Fts3Table *p, /* Virtual table handle */
  137735. Fts3MultiSegReader *pCsr, /* Cursor object */
  137736. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  137737. ){
  137738. pCsr->pFilter = pFilter;
  137739. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  137740. }
  137741. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  137742. Fts3Table *p, /* Virtual table handle */
  137743. Fts3MultiSegReader *pCsr, /* Cursor object */
  137744. int iCol, /* Column to match on. */
  137745. const char *zTerm, /* Term to iterate through a doclist for */
  137746. int nTerm /* Number of bytes in zTerm */
  137747. ){
  137748. int i;
  137749. int rc;
  137750. int nSegment = pCsr->nSegment;
  137751. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  137752. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  137753. );
  137754. assert( pCsr->pFilter==0 );
  137755. assert( zTerm && nTerm>0 );
  137756. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  137757. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  137758. if( rc!=SQLITE_OK ) return rc;
  137759. /* Determine how many of the segments actually point to zTerm/nTerm. */
  137760. for(i=0; i<nSegment; i++){
  137761. Fts3SegReader *pSeg = pCsr->apSegment[i];
  137762. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  137763. break;
  137764. }
  137765. }
  137766. pCsr->nAdvance = i;
  137767. /* Advance each of the segments to point to the first docid. */
  137768. for(i=0; i<pCsr->nAdvance; i++){
  137769. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  137770. if( rc!=SQLITE_OK ) return rc;
  137771. }
  137772. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  137773. assert( iCol<0 || iCol<p->nColumn );
  137774. pCsr->iColFilter = iCol;
  137775. return SQLITE_OK;
  137776. }
  137777. /*
  137778. ** This function is called on a MultiSegReader that has been started using
  137779. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  137780. ** have been made. Calling this function puts the MultiSegReader in such
  137781. ** a state that if the next two calls are:
  137782. **
  137783. ** sqlite3Fts3SegReaderStart()
  137784. ** sqlite3Fts3SegReaderStep()
  137785. **
  137786. ** then the entire doclist for the term is available in
  137787. ** MultiSegReader.aDoclist/nDoclist.
  137788. */
  137789. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  137790. int i; /* Used to iterate through segment-readers */
  137791. assert( pCsr->zTerm==0 );
  137792. assert( pCsr->nTerm==0 );
  137793. assert( pCsr->aDoclist==0 );
  137794. assert( pCsr->nDoclist==0 );
  137795. pCsr->nAdvance = 0;
  137796. pCsr->bRestart = 1;
  137797. for(i=0; i<pCsr->nSegment; i++){
  137798. pCsr->apSegment[i]->pOffsetList = 0;
  137799. pCsr->apSegment[i]->nOffsetList = 0;
  137800. pCsr->apSegment[i]->iDocid = 0;
  137801. }
  137802. return SQLITE_OK;
  137803. }
  137804. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  137805. Fts3Table *p, /* Virtual table handle */
  137806. Fts3MultiSegReader *pCsr /* Cursor object */
  137807. ){
  137808. int rc = SQLITE_OK;
  137809. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  137810. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  137811. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  137812. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  137813. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  137814. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  137815. Fts3SegReader **apSegment = pCsr->apSegment;
  137816. int nSegment = pCsr->nSegment;
  137817. Fts3SegFilter *pFilter = pCsr->pFilter;
  137818. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  137819. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  137820. );
  137821. if( pCsr->nSegment==0 ) return SQLITE_OK;
  137822. do {
  137823. int nMerge;
  137824. int i;
  137825. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  137826. ** forward. Then sort the list in order of current term again.
  137827. */
  137828. for(i=0; i<pCsr->nAdvance; i++){
  137829. Fts3SegReader *pSeg = apSegment[i];
  137830. if( pSeg->bLookup ){
  137831. fts3SegReaderSetEof(pSeg);
  137832. }else{
  137833. rc = fts3SegReaderNext(p, pSeg, 0);
  137834. }
  137835. if( rc!=SQLITE_OK ) return rc;
  137836. }
  137837. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  137838. pCsr->nAdvance = 0;
  137839. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  137840. assert( rc==SQLITE_OK );
  137841. if( apSegment[0]->aNode==0 ) break;
  137842. pCsr->nTerm = apSegment[0]->nTerm;
  137843. pCsr->zTerm = apSegment[0]->zTerm;
  137844. /* If this is a prefix-search, and if the term that apSegment[0] points
  137845. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  137846. ** required callbacks have been made. In this case exit early.
  137847. **
  137848. ** Similarly, if this is a search for an exact match, and the first term
  137849. ** of segment apSegment[0] is not a match, exit early.
  137850. */
  137851. if( pFilter->zTerm && !isScan ){
  137852. if( pCsr->nTerm<pFilter->nTerm
  137853. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  137854. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  137855. ){
  137856. break;
  137857. }
  137858. }
  137859. nMerge = 1;
  137860. while( nMerge<nSegment
  137861. && apSegment[nMerge]->aNode
  137862. && apSegment[nMerge]->nTerm==pCsr->nTerm
  137863. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  137864. ){
  137865. nMerge++;
  137866. }
  137867. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  137868. if( nMerge==1
  137869. && !isIgnoreEmpty
  137870. && !isFirst
  137871. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  137872. ){
  137873. pCsr->nDoclist = apSegment[0]->nDoclist;
  137874. if( fts3SegReaderIsPending(apSegment[0]) ){
  137875. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  137876. pCsr->aDoclist = pCsr->aBuffer;
  137877. }else{
  137878. pCsr->aDoclist = apSegment[0]->aDoclist;
  137879. }
  137880. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  137881. }else{
  137882. int nDoclist = 0; /* Size of doclist */
  137883. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  137884. /* The current term of the first nMerge entries in the array
  137885. ** of Fts3SegReader objects is the same. The doclists must be merged
  137886. ** and a single term returned with the merged doclist.
  137887. */
  137888. for(i=0; i<nMerge; i++){
  137889. fts3SegReaderFirstDocid(p, apSegment[i]);
  137890. }
  137891. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  137892. while( apSegment[0]->pOffsetList ){
  137893. int j; /* Number of segments that share a docid */
  137894. char *pList = 0;
  137895. int nList = 0;
  137896. int nByte;
  137897. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  137898. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  137899. j = 1;
  137900. while( j<nMerge
  137901. && apSegment[j]->pOffsetList
  137902. && apSegment[j]->iDocid==iDocid
  137903. ){
  137904. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  137905. j++;
  137906. }
  137907. if( isColFilter ){
  137908. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  137909. }
  137910. if( !isIgnoreEmpty || nList>0 ){
  137911. /* Calculate the 'docid' delta value to write into the merged
  137912. ** doclist. */
  137913. sqlite3_int64 iDelta;
  137914. if( p->bDescIdx && nDoclist>0 ){
  137915. iDelta = iPrev - iDocid;
  137916. }else{
  137917. iDelta = iDocid - iPrev;
  137918. }
  137919. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  137920. assert( nDoclist>0 || iDelta==iDocid );
  137921. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  137922. if( nDoclist+nByte>pCsr->nBuffer ){
  137923. char *aNew;
  137924. pCsr->nBuffer = (nDoclist+nByte)*2;
  137925. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  137926. if( !aNew ){
  137927. return SQLITE_NOMEM;
  137928. }
  137929. pCsr->aBuffer = aNew;
  137930. }
  137931. if( isFirst ){
  137932. char *a = &pCsr->aBuffer[nDoclist];
  137933. int nWrite;
  137934. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  137935. if( nWrite ){
  137936. iPrev = iDocid;
  137937. nDoclist += nWrite;
  137938. }
  137939. }else{
  137940. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  137941. iPrev = iDocid;
  137942. if( isRequirePos ){
  137943. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  137944. nDoclist += nList;
  137945. pCsr->aBuffer[nDoclist++] = '\0';
  137946. }
  137947. }
  137948. }
  137949. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  137950. }
  137951. if( nDoclist>0 ){
  137952. pCsr->aDoclist = pCsr->aBuffer;
  137953. pCsr->nDoclist = nDoclist;
  137954. rc = SQLITE_ROW;
  137955. }
  137956. }
  137957. pCsr->nAdvance = nMerge;
  137958. }while( rc==SQLITE_OK );
  137959. return rc;
  137960. }
  137961. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  137962. Fts3MultiSegReader *pCsr /* Cursor object */
  137963. ){
  137964. if( pCsr ){
  137965. int i;
  137966. for(i=0; i<pCsr->nSegment; i++){
  137967. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  137968. }
  137969. sqlite3_free(pCsr->apSegment);
  137970. sqlite3_free(pCsr->aBuffer);
  137971. pCsr->nSegment = 0;
  137972. pCsr->apSegment = 0;
  137973. pCsr->aBuffer = 0;
  137974. }
  137975. }
  137976. /*
  137977. ** Decode the "end_block" field, selected by column iCol of the SELECT
  137978. ** statement passed as the first argument.
  137979. **
  137980. ** The "end_block" field may contain either an integer, or a text field
  137981. ** containing the text representation of two non-negative integers separated
  137982. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  137983. ** to the integer value and *pnByte to zero before returning. In the second,
  137984. ** set *piEndBlock to the first value and *pnByte to the second.
  137985. */
  137986. static void fts3ReadEndBlockField(
  137987. sqlite3_stmt *pStmt,
  137988. int iCol,
  137989. i64 *piEndBlock,
  137990. i64 *pnByte
  137991. ){
  137992. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  137993. if( zText ){
  137994. int i;
  137995. int iMul = 1;
  137996. i64 iVal = 0;
  137997. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  137998. iVal = iVal*10 + (zText[i] - '0');
  137999. }
  138000. *piEndBlock = iVal;
  138001. while( zText[i]==' ' ) i++;
  138002. iVal = 0;
  138003. if( zText[i]=='-' ){
  138004. i++;
  138005. iMul = -1;
  138006. }
  138007. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  138008. iVal = iVal*10 + (zText[i] - '0');
  138009. }
  138010. *pnByte = (iVal * (i64)iMul);
  138011. }
  138012. }
  138013. /*
  138014. ** A segment of size nByte bytes has just been written to absolute level
  138015. ** iAbsLevel. Promote any segments that should be promoted as a result.
  138016. */
  138017. static int fts3PromoteSegments(
  138018. Fts3Table *p, /* FTS table handle */
  138019. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  138020. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  138021. ){
  138022. int rc = SQLITE_OK;
  138023. sqlite3_stmt *pRange;
  138024. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  138025. if( rc==SQLITE_OK ){
  138026. int bOk = 0;
  138027. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  138028. i64 nLimit = (nByte*3)/2;
  138029. /* Loop through all entries in the %_segdir table corresponding to
  138030. ** segments in this index on levels greater than iAbsLevel. If there is
  138031. ** at least one such segment, and it is possible to determine that all
  138032. ** such segments are smaller than nLimit bytes in size, they will be
  138033. ** promoted to level iAbsLevel. */
  138034. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  138035. sqlite3_bind_int64(pRange, 2, iLast);
  138036. while( SQLITE_ROW==sqlite3_step(pRange) ){
  138037. i64 nSize = 0, dummy;
  138038. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  138039. if( nSize<=0 || nSize>nLimit ){
  138040. /* If nSize==0, then the %_segdir.end_block field does not not
  138041. ** contain a size value. This happens if it was written by an
  138042. ** old version of FTS. In this case it is not possible to determine
  138043. ** the size of the segment, and so segment promotion does not
  138044. ** take place. */
  138045. bOk = 0;
  138046. break;
  138047. }
  138048. bOk = 1;
  138049. }
  138050. rc = sqlite3_reset(pRange);
  138051. if( bOk ){
  138052. int iIdx = 0;
  138053. sqlite3_stmt *pUpdate1 = 0;
  138054. sqlite3_stmt *pUpdate2 = 0;
  138055. if( rc==SQLITE_OK ){
  138056. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  138057. }
  138058. if( rc==SQLITE_OK ){
  138059. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  138060. }
  138061. if( rc==SQLITE_OK ){
  138062. /* Loop through all %_segdir entries for segments in this index with
  138063. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  138064. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  138065. ** oldest segment in the range, 1 for the next oldest, and so on.
  138066. **
  138067. ** In other words, move all segments being promoted to level -1,
  138068. ** setting the "idx" fields as appropriate to keep them in the same
  138069. ** order. The contents of level -1 (which is never used, except
  138070. ** transiently here), will be moved back to level iAbsLevel below. */
  138071. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  138072. while( SQLITE_ROW==sqlite3_step(pRange) ){
  138073. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  138074. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  138075. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  138076. sqlite3_step(pUpdate1);
  138077. rc = sqlite3_reset(pUpdate1);
  138078. if( rc!=SQLITE_OK ){
  138079. sqlite3_reset(pRange);
  138080. break;
  138081. }
  138082. }
  138083. }
  138084. if( rc==SQLITE_OK ){
  138085. rc = sqlite3_reset(pRange);
  138086. }
  138087. /* Move level -1 to level iAbsLevel */
  138088. if( rc==SQLITE_OK ){
  138089. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  138090. sqlite3_step(pUpdate2);
  138091. rc = sqlite3_reset(pUpdate2);
  138092. }
  138093. }
  138094. }
  138095. return rc;
  138096. }
  138097. /*
  138098. ** Merge all level iLevel segments in the database into a single
  138099. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  138100. ** single segment with a level equal to the numerically largest level
  138101. ** currently present in the database.
  138102. **
  138103. ** If this function is called with iLevel<0, but there is only one
  138104. ** segment in the database, SQLITE_DONE is returned immediately.
  138105. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  138106. ** an SQLite error code is returned.
  138107. */
  138108. static int fts3SegmentMerge(
  138109. Fts3Table *p,
  138110. int iLangid, /* Language id to merge */
  138111. int iIndex, /* Index in p->aIndex[] to merge */
  138112. int iLevel /* Level to merge */
  138113. ){
  138114. int rc; /* Return code */
  138115. int iIdx = 0; /* Index of new segment */
  138116. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  138117. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  138118. Fts3SegFilter filter; /* Segment term filter condition */
  138119. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  138120. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  138121. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  138122. assert( iLevel==FTS3_SEGCURSOR_ALL
  138123. || iLevel==FTS3_SEGCURSOR_PENDING
  138124. || iLevel>=0
  138125. );
  138126. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  138127. assert( iIndex>=0 && iIndex<p->nIndex );
  138128. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  138129. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  138130. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  138131. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  138132. if( rc!=SQLITE_OK ) goto finished;
  138133. }
  138134. if( iLevel==FTS3_SEGCURSOR_ALL ){
  138135. /* This call is to merge all segments in the database to a single
  138136. ** segment. The level of the new segment is equal to the numerically
  138137. ** greatest segment level currently present in the database for this
  138138. ** index. The idx of the new segment is always 0. */
  138139. if( csr.nSegment==1 ){
  138140. rc = SQLITE_DONE;
  138141. goto finished;
  138142. }
  138143. iNewLevel = iMaxLevel;
  138144. bIgnoreEmpty = 1;
  138145. }else{
  138146. /* This call is to merge all segments at level iLevel. find the next
  138147. ** available segment index at level iLevel+1. The call to
  138148. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  138149. ** a single iLevel+2 segment if necessary. */
  138150. assert( FTS3_SEGCURSOR_PENDING==-1 );
  138151. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  138152. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  138153. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  138154. }
  138155. if( rc!=SQLITE_OK ) goto finished;
  138156. assert( csr.nSegment>0 );
  138157. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  138158. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  138159. memset(&filter, 0, sizeof(Fts3SegFilter));
  138160. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  138161. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  138162. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  138163. while( SQLITE_OK==rc ){
  138164. rc = sqlite3Fts3SegReaderStep(p, &csr);
  138165. if( rc!=SQLITE_ROW ) break;
  138166. rc = fts3SegWriterAdd(p, &pWriter, 1,
  138167. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  138168. }
  138169. if( rc!=SQLITE_OK ) goto finished;
  138170. assert( pWriter || bIgnoreEmpty );
  138171. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  138172. rc = fts3DeleteSegdir(
  138173. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  138174. );
  138175. if( rc!=SQLITE_OK ) goto finished;
  138176. }
  138177. if( pWriter ){
  138178. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  138179. if( rc==SQLITE_OK ){
  138180. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  138181. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  138182. }
  138183. }
  138184. }
  138185. finished:
  138186. fts3SegWriterFree(pWriter);
  138187. sqlite3Fts3SegReaderFinish(&csr);
  138188. return rc;
  138189. }
  138190. /*
  138191. ** Flush the contents of pendingTerms to level 0 segments.
  138192. */
  138193. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  138194. int rc = SQLITE_OK;
  138195. int i;
  138196. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  138197. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  138198. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  138199. }
  138200. sqlite3Fts3PendingTermsClear(p);
  138201. /* Determine the auto-incr-merge setting if unknown. If enabled,
  138202. ** estimate the number of leaf blocks of content to be written
  138203. */
  138204. if( rc==SQLITE_OK && p->bHasStat
  138205. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  138206. ){
  138207. sqlite3_stmt *pStmt = 0;
  138208. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  138209. if( rc==SQLITE_OK ){
  138210. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  138211. rc = sqlite3_step(pStmt);
  138212. if( rc==SQLITE_ROW ){
  138213. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  138214. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  138215. }else if( rc==SQLITE_DONE ){
  138216. p->nAutoincrmerge = 0;
  138217. }
  138218. rc = sqlite3_reset(pStmt);
  138219. }
  138220. }
  138221. return rc;
  138222. }
  138223. /*
  138224. ** Encode N integers as varints into a blob.
  138225. */
  138226. static void fts3EncodeIntArray(
  138227. int N, /* The number of integers to encode */
  138228. u32 *a, /* The integer values */
  138229. char *zBuf, /* Write the BLOB here */
  138230. int *pNBuf /* Write number of bytes if zBuf[] used here */
  138231. ){
  138232. int i, j;
  138233. for(i=j=0; i<N; i++){
  138234. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  138235. }
  138236. *pNBuf = j;
  138237. }
  138238. /*
  138239. ** Decode a blob of varints into N integers
  138240. */
  138241. static void fts3DecodeIntArray(
  138242. int N, /* The number of integers to decode */
  138243. u32 *a, /* Write the integer values */
  138244. const char *zBuf, /* The BLOB containing the varints */
  138245. int nBuf /* size of the BLOB */
  138246. ){
  138247. int i, j;
  138248. UNUSED_PARAMETER(nBuf);
  138249. for(i=j=0; i<N; i++){
  138250. sqlite3_int64 x;
  138251. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  138252. assert(j<=nBuf);
  138253. a[i] = (u32)(x & 0xffffffff);
  138254. }
  138255. }
  138256. /*
  138257. ** Insert the sizes (in tokens) for each column of the document
  138258. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  138259. ** a blob of varints.
  138260. */
  138261. static void fts3InsertDocsize(
  138262. int *pRC, /* Result code */
  138263. Fts3Table *p, /* Table into which to insert */
  138264. u32 *aSz /* Sizes of each column, in tokens */
  138265. ){
  138266. char *pBlob; /* The BLOB encoding of the document size */
  138267. int nBlob; /* Number of bytes in the BLOB */
  138268. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  138269. int rc; /* Result code from subfunctions */
  138270. if( *pRC ) return;
  138271. pBlob = sqlite3_malloc( 10*p->nColumn );
  138272. if( pBlob==0 ){
  138273. *pRC = SQLITE_NOMEM;
  138274. return;
  138275. }
  138276. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  138277. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  138278. if( rc ){
  138279. sqlite3_free(pBlob);
  138280. *pRC = rc;
  138281. return;
  138282. }
  138283. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  138284. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  138285. sqlite3_step(pStmt);
  138286. *pRC = sqlite3_reset(pStmt);
  138287. }
  138288. /*
  138289. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  138290. ** where N is the number of user defined columns in the fts3 table plus
  138291. ** two. If nCol is the number of user defined columns, then values of the
  138292. ** varints are set as follows:
  138293. **
  138294. ** Varint 0: Total number of rows in the table.
  138295. **
  138296. ** Varint 1..nCol: For each column, the total number of tokens stored in
  138297. ** the column for all rows of the table.
  138298. **
  138299. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  138300. ** columns of all rows of the table.
  138301. **
  138302. */
  138303. static void fts3UpdateDocTotals(
  138304. int *pRC, /* The result code */
  138305. Fts3Table *p, /* Table being updated */
  138306. u32 *aSzIns, /* Size increases */
  138307. u32 *aSzDel, /* Size decreases */
  138308. int nChng /* Change in the number of documents */
  138309. ){
  138310. char *pBlob; /* Storage for BLOB written into %_stat */
  138311. int nBlob; /* Size of BLOB written into %_stat */
  138312. u32 *a; /* Array of integers that becomes the BLOB */
  138313. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  138314. int i; /* Loop counter */
  138315. int rc; /* Result code from subfunctions */
  138316. const int nStat = p->nColumn+2;
  138317. if( *pRC ) return;
  138318. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  138319. if( a==0 ){
  138320. *pRC = SQLITE_NOMEM;
  138321. return;
  138322. }
  138323. pBlob = (char*)&a[nStat];
  138324. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  138325. if( rc ){
  138326. sqlite3_free(a);
  138327. *pRC = rc;
  138328. return;
  138329. }
  138330. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  138331. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  138332. fts3DecodeIntArray(nStat, a,
  138333. sqlite3_column_blob(pStmt, 0),
  138334. sqlite3_column_bytes(pStmt, 0));
  138335. }else{
  138336. memset(a, 0, sizeof(u32)*(nStat) );
  138337. }
  138338. rc = sqlite3_reset(pStmt);
  138339. if( rc!=SQLITE_OK ){
  138340. sqlite3_free(a);
  138341. *pRC = rc;
  138342. return;
  138343. }
  138344. if( nChng<0 && a[0]<(u32)(-nChng) ){
  138345. a[0] = 0;
  138346. }else{
  138347. a[0] += nChng;
  138348. }
  138349. for(i=0; i<p->nColumn+1; i++){
  138350. u32 x = a[i+1];
  138351. if( x+aSzIns[i] < aSzDel[i] ){
  138352. x = 0;
  138353. }else{
  138354. x = x + aSzIns[i] - aSzDel[i];
  138355. }
  138356. a[i+1] = x;
  138357. }
  138358. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  138359. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  138360. if( rc ){
  138361. sqlite3_free(a);
  138362. *pRC = rc;
  138363. return;
  138364. }
  138365. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  138366. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  138367. sqlite3_step(pStmt);
  138368. *pRC = sqlite3_reset(pStmt);
  138369. sqlite3_free(a);
  138370. }
  138371. /*
  138372. ** Merge the entire database so that there is one segment for each
  138373. ** iIndex/iLangid combination.
  138374. */
  138375. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  138376. int bSeenDone = 0;
  138377. int rc;
  138378. sqlite3_stmt *pAllLangid = 0;
  138379. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  138380. if( rc==SQLITE_OK ){
  138381. int rc2;
  138382. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  138383. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  138384. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  138385. int i;
  138386. int iLangid = sqlite3_column_int(pAllLangid, 0);
  138387. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  138388. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  138389. if( rc==SQLITE_DONE ){
  138390. bSeenDone = 1;
  138391. rc = SQLITE_OK;
  138392. }
  138393. }
  138394. }
  138395. rc2 = sqlite3_reset(pAllLangid);
  138396. if( rc==SQLITE_OK ) rc = rc2;
  138397. }
  138398. sqlite3Fts3SegmentsClose(p);
  138399. sqlite3Fts3PendingTermsClear(p);
  138400. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  138401. }
  138402. /*
  138403. ** This function is called when the user executes the following statement:
  138404. **
  138405. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  138406. **
  138407. ** The entire FTS index is discarded and rebuilt. If the table is one
  138408. ** created using the content=xxx option, then the new index is based on
  138409. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  138410. ** on the contents of the %_content table.
  138411. */
  138412. static int fts3DoRebuild(Fts3Table *p){
  138413. int rc; /* Return Code */
  138414. rc = fts3DeleteAll(p, 0);
  138415. if( rc==SQLITE_OK ){
  138416. u32 *aSz = 0;
  138417. u32 *aSzIns = 0;
  138418. u32 *aSzDel = 0;
  138419. sqlite3_stmt *pStmt = 0;
  138420. int nEntry = 0;
  138421. /* Compose and prepare an SQL statement to loop through the content table */
  138422. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  138423. if( !zSql ){
  138424. rc = SQLITE_NOMEM;
  138425. }else{
  138426. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  138427. sqlite3_free(zSql);
  138428. }
  138429. if( rc==SQLITE_OK ){
  138430. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  138431. aSz = (u32 *)sqlite3_malloc(nByte);
  138432. if( aSz==0 ){
  138433. rc = SQLITE_NOMEM;
  138434. }else{
  138435. memset(aSz, 0, nByte);
  138436. aSzIns = &aSz[p->nColumn+1];
  138437. aSzDel = &aSzIns[p->nColumn+1];
  138438. }
  138439. }
  138440. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  138441. int iCol;
  138442. int iLangid = langidFromSelect(p, pStmt);
  138443. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  138444. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  138445. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  138446. if( p->abNotindexed[iCol]==0 ){
  138447. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  138448. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  138449. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  138450. }
  138451. }
  138452. if( p->bHasDocsize ){
  138453. fts3InsertDocsize(&rc, p, aSz);
  138454. }
  138455. if( rc!=SQLITE_OK ){
  138456. sqlite3_finalize(pStmt);
  138457. pStmt = 0;
  138458. }else{
  138459. nEntry++;
  138460. for(iCol=0; iCol<=p->nColumn; iCol++){
  138461. aSzIns[iCol] += aSz[iCol];
  138462. }
  138463. }
  138464. }
  138465. if( p->bFts4 ){
  138466. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  138467. }
  138468. sqlite3_free(aSz);
  138469. if( pStmt ){
  138470. int rc2 = sqlite3_finalize(pStmt);
  138471. if( rc==SQLITE_OK ){
  138472. rc = rc2;
  138473. }
  138474. }
  138475. }
  138476. return rc;
  138477. }
  138478. /*
  138479. ** This function opens a cursor used to read the input data for an
  138480. ** incremental merge operation. Specifically, it opens a cursor to scan
  138481. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  138482. ** level iAbsLevel.
  138483. */
  138484. static int fts3IncrmergeCsr(
  138485. Fts3Table *p, /* FTS3 table handle */
  138486. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  138487. int nSeg, /* Number of segments to merge */
  138488. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  138489. ){
  138490. int rc; /* Return Code */
  138491. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  138492. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  138493. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  138494. memset(pCsr, 0, sizeof(*pCsr));
  138495. nByte = sizeof(Fts3SegReader *) * nSeg;
  138496. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  138497. if( pCsr->apSegment==0 ){
  138498. rc = SQLITE_NOMEM;
  138499. }else{
  138500. memset(pCsr->apSegment, 0, nByte);
  138501. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  138502. }
  138503. if( rc==SQLITE_OK ){
  138504. int i;
  138505. int rc2;
  138506. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  138507. assert( pCsr->nSegment==0 );
  138508. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  138509. rc = sqlite3Fts3SegReaderNew(i, 0,
  138510. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  138511. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  138512. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  138513. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  138514. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  138515. &pCsr->apSegment[i]
  138516. );
  138517. pCsr->nSegment++;
  138518. }
  138519. rc2 = sqlite3_reset(pStmt);
  138520. if( rc==SQLITE_OK ) rc = rc2;
  138521. }
  138522. return rc;
  138523. }
  138524. typedef struct IncrmergeWriter IncrmergeWriter;
  138525. typedef struct NodeWriter NodeWriter;
  138526. typedef struct Blob Blob;
  138527. typedef struct NodeReader NodeReader;
  138528. /*
  138529. ** An instance of the following structure is used as a dynamic buffer
  138530. ** to build up nodes or other blobs of data in.
  138531. **
  138532. ** The function blobGrowBuffer() is used to extend the allocation.
  138533. */
  138534. struct Blob {
  138535. char *a; /* Pointer to allocation */
  138536. int n; /* Number of valid bytes of data in a[] */
  138537. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  138538. };
  138539. /*
  138540. ** This structure is used to build up buffers containing segment b-tree
  138541. ** nodes (blocks).
  138542. */
  138543. struct NodeWriter {
  138544. sqlite3_int64 iBlock; /* Current block id */
  138545. Blob key; /* Last key written to the current block */
  138546. Blob block; /* Current block image */
  138547. };
  138548. /*
  138549. ** An object of this type contains the state required to create or append
  138550. ** to an appendable b-tree segment.
  138551. */
  138552. struct IncrmergeWriter {
  138553. int nLeafEst; /* Space allocated for leaf blocks */
  138554. int nWork; /* Number of leaf pages flushed */
  138555. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  138556. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  138557. sqlite3_int64 iStart; /* Block number of first allocated block */
  138558. sqlite3_int64 iEnd; /* Block number of last allocated block */
  138559. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  138560. u8 bNoLeafData; /* If true, store 0 for segment size */
  138561. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  138562. };
  138563. /*
  138564. ** An object of the following type is used to read data from a single
  138565. ** FTS segment node. See the following functions:
  138566. **
  138567. ** nodeReaderInit()
  138568. ** nodeReaderNext()
  138569. ** nodeReaderRelease()
  138570. */
  138571. struct NodeReader {
  138572. const char *aNode;
  138573. int nNode;
  138574. int iOff; /* Current offset within aNode[] */
  138575. /* Output variables. Containing the current node entry. */
  138576. sqlite3_int64 iChild; /* Pointer to child node */
  138577. Blob term; /* Current term */
  138578. const char *aDoclist; /* Pointer to doclist */
  138579. int nDoclist; /* Size of doclist in bytes */
  138580. };
  138581. /*
  138582. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  138583. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  138584. ** bytes in size, extend (realloc) it to be so.
  138585. **
  138586. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  138587. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  138588. ** to reflect the new size of the pBlob->a[] buffer.
  138589. */
  138590. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  138591. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  138592. int nAlloc = nMin;
  138593. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  138594. if( a ){
  138595. pBlob->nAlloc = nAlloc;
  138596. pBlob->a = a;
  138597. }else{
  138598. *pRc = SQLITE_NOMEM;
  138599. }
  138600. }
  138601. }
  138602. /*
  138603. ** Attempt to advance the node-reader object passed as the first argument to
  138604. ** the next entry on the node.
  138605. **
  138606. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  138607. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  138608. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  138609. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  138610. ** variables for the new entry.
  138611. */
  138612. static int nodeReaderNext(NodeReader *p){
  138613. int bFirst = (p->term.n==0); /* True for first term on the node */
  138614. int nPrefix = 0; /* Bytes to copy from previous term */
  138615. int nSuffix = 0; /* Bytes to append to the prefix */
  138616. int rc = SQLITE_OK; /* Return code */
  138617. assert( p->aNode );
  138618. if( p->iChild && bFirst==0 ) p->iChild++;
  138619. if( p->iOff>=p->nNode ){
  138620. /* EOF */
  138621. p->aNode = 0;
  138622. }else{
  138623. if( bFirst==0 ){
  138624. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  138625. }
  138626. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  138627. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  138628. if( rc==SQLITE_OK ){
  138629. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  138630. p->term.n = nPrefix+nSuffix;
  138631. p->iOff += nSuffix;
  138632. if( p->iChild==0 ){
  138633. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  138634. p->aDoclist = &p->aNode[p->iOff];
  138635. p->iOff += p->nDoclist;
  138636. }
  138637. }
  138638. }
  138639. assert( p->iOff<=p->nNode );
  138640. return rc;
  138641. }
  138642. /*
  138643. ** Release all dynamic resources held by node-reader object *p.
  138644. */
  138645. static void nodeReaderRelease(NodeReader *p){
  138646. sqlite3_free(p->term.a);
  138647. }
  138648. /*
  138649. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  138650. **
  138651. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  138652. ** point to the first entry on the node (if any). Otherwise, an SQLite
  138653. ** error code is returned.
  138654. */
  138655. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  138656. memset(p, 0, sizeof(NodeReader));
  138657. p->aNode = aNode;
  138658. p->nNode = nNode;
  138659. /* Figure out if this is a leaf or an internal node. */
  138660. if( p->aNode[0] ){
  138661. /* An internal node. */
  138662. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  138663. }else{
  138664. p->iOff = 1;
  138665. }
  138666. return nodeReaderNext(p);
  138667. }
  138668. /*
  138669. ** This function is called while writing an FTS segment each time a leaf o
  138670. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  138671. ** to be greater than the largest key on the node just written, but smaller
  138672. ** than or equal to the first key that will be written to the next leaf
  138673. ** node.
  138674. **
  138675. ** The block id of the leaf node just written to disk may be found in
  138676. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  138677. */
  138678. static int fts3IncrmergePush(
  138679. Fts3Table *p, /* Fts3 table handle */
  138680. IncrmergeWriter *pWriter, /* Writer object */
  138681. const char *zTerm, /* Term to write to internal node */
  138682. int nTerm /* Bytes at zTerm */
  138683. ){
  138684. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  138685. int iLayer;
  138686. assert( nTerm>0 );
  138687. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  138688. sqlite3_int64 iNextPtr = 0;
  138689. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  138690. int rc = SQLITE_OK;
  138691. int nPrefix;
  138692. int nSuffix;
  138693. int nSpace;
  138694. /* Figure out how much space the key will consume if it is written to
  138695. ** the current node of layer iLayer. Due to the prefix compression,
  138696. ** the space required changes depending on which node the key is to
  138697. ** be added to. */
  138698. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  138699. nSuffix = nTerm - nPrefix;
  138700. nSpace = sqlite3Fts3VarintLen(nPrefix);
  138701. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  138702. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  138703. /* If the current node of layer iLayer contains zero keys, or if adding
  138704. ** the key to it will not cause it to grow to larger than nNodeSize
  138705. ** bytes in size, write the key here. */
  138706. Blob *pBlk = &pNode->block;
  138707. if( pBlk->n==0 ){
  138708. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  138709. if( rc==SQLITE_OK ){
  138710. pBlk->a[0] = (char)iLayer;
  138711. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  138712. }
  138713. }
  138714. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  138715. blobGrowBuffer(&pNode->key, nTerm, &rc);
  138716. if( rc==SQLITE_OK ){
  138717. if( pNode->key.n ){
  138718. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  138719. }
  138720. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  138721. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  138722. pBlk->n += nSuffix;
  138723. memcpy(pNode->key.a, zTerm, nTerm);
  138724. pNode->key.n = nTerm;
  138725. }
  138726. }else{
  138727. /* Otherwise, flush the current node of layer iLayer to disk.
  138728. ** Then allocate a new, empty sibling node. The key will be written
  138729. ** into the parent of this node. */
  138730. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  138731. assert( pNode->block.nAlloc>=p->nNodeSize );
  138732. pNode->block.a[0] = (char)iLayer;
  138733. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  138734. iNextPtr = pNode->iBlock;
  138735. pNode->iBlock++;
  138736. pNode->key.n = 0;
  138737. }
  138738. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  138739. iPtr = iNextPtr;
  138740. }
  138741. assert( 0 );
  138742. return 0;
  138743. }
  138744. /*
  138745. ** Append a term and (optionally) doclist to the FTS segment node currently
  138746. ** stored in blob *pNode. The node need not contain any terms, but the
  138747. ** header must be written before this function is called.
  138748. **
  138749. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  138750. ** followed by the left-hand-child varint for an internal node.
  138751. **
  138752. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  138753. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  138754. ** node, both aDoclist and nDoclist must be passed 0.
  138755. **
  138756. ** If the size of the value in blob pPrev is zero, then this is the first
  138757. ** term written to the node. Otherwise, pPrev contains a copy of the
  138758. ** previous term. Before this function returns, it is updated to contain a
  138759. ** copy of zTerm/nTerm.
  138760. **
  138761. ** It is assumed that the buffer associated with pNode is already large
  138762. ** enough to accommodate the new entry. The buffer associated with pPrev
  138763. ** is extended by this function if requrired.
  138764. **
  138765. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  138766. ** returned. Otherwise, SQLITE_OK.
  138767. */
  138768. static int fts3AppendToNode(
  138769. Blob *pNode, /* Current node image to append to */
  138770. Blob *pPrev, /* Buffer containing previous term written */
  138771. const char *zTerm, /* New term to write */
  138772. int nTerm, /* Size of zTerm in bytes */
  138773. const char *aDoclist, /* Doclist (or NULL) to write */
  138774. int nDoclist /* Size of aDoclist in bytes */
  138775. ){
  138776. int rc = SQLITE_OK; /* Return code */
  138777. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  138778. int nPrefix; /* Size of term prefix in bytes */
  138779. int nSuffix; /* Size of term suffix in bytes */
  138780. /* Node must have already been started. There must be a doclist for a
  138781. ** leaf node, and there must not be a doclist for an internal node. */
  138782. assert( pNode->n>0 );
  138783. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  138784. blobGrowBuffer(pPrev, nTerm, &rc);
  138785. if( rc!=SQLITE_OK ) return rc;
  138786. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  138787. nSuffix = nTerm - nPrefix;
  138788. memcpy(pPrev->a, zTerm, nTerm);
  138789. pPrev->n = nTerm;
  138790. if( bFirst==0 ){
  138791. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  138792. }
  138793. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  138794. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  138795. pNode->n += nSuffix;
  138796. if( aDoclist ){
  138797. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  138798. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  138799. pNode->n += nDoclist;
  138800. }
  138801. assert( pNode->n<=pNode->nAlloc );
  138802. return SQLITE_OK;
  138803. }
  138804. /*
  138805. ** Append the current term and doclist pointed to by cursor pCsr to the
  138806. ** appendable b-tree segment opened for writing by pWriter.
  138807. **
  138808. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  138809. */
  138810. static int fts3IncrmergeAppend(
  138811. Fts3Table *p, /* Fts3 table handle */
  138812. IncrmergeWriter *pWriter, /* Writer object */
  138813. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  138814. ){
  138815. const char *zTerm = pCsr->zTerm;
  138816. int nTerm = pCsr->nTerm;
  138817. const char *aDoclist = pCsr->aDoclist;
  138818. int nDoclist = pCsr->nDoclist;
  138819. int rc = SQLITE_OK; /* Return code */
  138820. int nSpace; /* Total space in bytes required on leaf */
  138821. int nPrefix; /* Size of prefix shared with previous term */
  138822. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  138823. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  138824. pLeaf = &pWriter->aNodeWriter[0];
  138825. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  138826. nSuffix = nTerm - nPrefix;
  138827. nSpace = sqlite3Fts3VarintLen(nPrefix);
  138828. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  138829. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  138830. /* If the current block is not empty, and if adding this term/doclist
  138831. ** to the current block would make it larger than Fts3Table.nNodeSize
  138832. ** bytes, write this block out to the database. */
  138833. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  138834. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  138835. pWriter->nWork++;
  138836. /* Add the current term to the parent node. The term added to the
  138837. ** parent must:
  138838. **
  138839. ** a) be greater than the largest term on the leaf node just written
  138840. ** to the database (still available in pLeaf->key), and
  138841. **
  138842. ** b) be less than or equal to the term about to be added to the new
  138843. ** leaf node (zTerm/nTerm).
  138844. **
  138845. ** In other words, it must be the prefix of zTerm 1 byte longer than
  138846. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  138847. */
  138848. if( rc==SQLITE_OK ){
  138849. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  138850. }
  138851. /* Advance to the next output block */
  138852. pLeaf->iBlock++;
  138853. pLeaf->key.n = 0;
  138854. pLeaf->block.n = 0;
  138855. nSuffix = nTerm;
  138856. nSpace = 1;
  138857. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  138858. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  138859. }
  138860. pWriter->nLeafData += nSpace;
  138861. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  138862. if( rc==SQLITE_OK ){
  138863. if( pLeaf->block.n==0 ){
  138864. pLeaf->block.n = 1;
  138865. pLeaf->block.a[0] = '\0';
  138866. }
  138867. rc = fts3AppendToNode(
  138868. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  138869. );
  138870. }
  138871. return rc;
  138872. }
  138873. /*
  138874. ** This function is called to release all dynamic resources held by the
  138875. ** merge-writer object pWriter, and if no error has occurred, to flush
  138876. ** all outstanding node buffers held by pWriter to disk.
  138877. **
  138878. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  138879. ** is made to write any data to disk. Instead, this function serves only
  138880. ** to release outstanding resources.
  138881. **
  138882. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  138883. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  138884. ** returning.
  138885. */
  138886. static void fts3IncrmergeRelease(
  138887. Fts3Table *p, /* FTS3 table handle */
  138888. IncrmergeWriter *pWriter, /* Merge-writer object */
  138889. int *pRc /* IN/OUT: Error code */
  138890. ){
  138891. int i; /* Used to iterate through non-root layers */
  138892. int iRoot; /* Index of root in pWriter->aNodeWriter */
  138893. NodeWriter *pRoot; /* NodeWriter for root node */
  138894. int rc = *pRc; /* Error code */
  138895. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  138896. ** root node. If the segment fits entirely on a single leaf node, iRoot
  138897. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  138898. ** will be 1. And so on. */
  138899. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  138900. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  138901. if( pNode->block.n>0 ) break;
  138902. assert( *pRc || pNode->block.nAlloc==0 );
  138903. assert( *pRc || pNode->key.nAlloc==0 );
  138904. sqlite3_free(pNode->block.a);
  138905. sqlite3_free(pNode->key.a);
  138906. }
  138907. /* Empty output segment. This is a no-op. */
  138908. if( iRoot<0 ) return;
  138909. /* The entire output segment fits on a single node. Normally, this means
  138910. ** the node would be stored as a blob in the "root" column of the %_segdir
  138911. ** table. However, this is not permitted in this case. The problem is that
  138912. ** space has already been reserved in the %_segments table, and so the
  138913. ** start_block and end_block fields of the %_segdir table must be populated.
  138914. ** And, by design or by accident, released versions of FTS cannot handle
  138915. ** segments that fit entirely on the root node with start_block!=0.
  138916. **
  138917. ** Instead, create a synthetic root node that contains nothing but a
  138918. ** pointer to the single content node. So that the segment consists of a
  138919. ** single leaf and a single interior (root) node.
  138920. **
  138921. ** Todo: Better might be to defer allocating space in the %_segments
  138922. ** table until we are sure it is needed.
  138923. */
  138924. if( iRoot==0 ){
  138925. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  138926. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  138927. if( rc==SQLITE_OK ){
  138928. pBlock->a[0] = 0x01;
  138929. pBlock->n = 1 + sqlite3Fts3PutVarint(
  138930. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  138931. );
  138932. }
  138933. iRoot = 1;
  138934. }
  138935. pRoot = &pWriter->aNodeWriter[iRoot];
  138936. /* Flush all currently outstanding nodes to disk. */
  138937. for(i=0; i<iRoot; i++){
  138938. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  138939. if( pNode->block.n>0 && rc==SQLITE_OK ){
  138940. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  138941. }
  138942. sqlite3_free(pNode->block.a);
  138943. sqlite3_free(pNode->key.a);
  138944. }
  138945. /* Write the %_segdir record. */
  138946. if( rc==SQLITE_OK ){
  138947. rc = fts3WriteSegdir(p,
  138948. pWriter->iAbsLevel+1, /* level */
  138949. pWriter->iIdx, /* idx */
  138950. pWriter->iStart, /* start_block */
  138951. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  138952. pWriter->iEnd, /* end_block */
  138953. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  138954. pRoot->block.a, pRoot->block.n /* root */
  138955. );
  138956. }
  138957. sqlite3_free(pRoot->block.a);
  138958. sqlite3_free(pRoot->key.a);
  138959. *pRc = rc;
  138960. }
  138961. /*
  138962. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  138963. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  138964. ** the other, it is considered to be smaller than the other.
  138965. **
  138966. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  138967. ** if it is greater.
  138968. */
  138969. static int fts3TermCmp(
  138970. const char *zLhs, int nLhs, /* LHS of comparison */
  138971. const char *zRhs, int nRhs /* RHS of comparison */
  138972. ){
  138973. int nCmp = MIN(nLhs, nRhs);
  138974. int res;
  138975. res = memcmp(zLhs, zRhs, nCmp);
  138976. if( res==0 ) res = nLhs - nRhs;
  138977. return res;
  138978. }
  138979. /*
  138980. ** Query to see if the entry in the %_segments table with blockid iEnd is
  138981. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  138982. ** returning. Otherwise, set *pbRes to 0.
  138983. **
  138984. ** Or, if an error occurs while querying the database, return an SQLite
  138985. ** error code. The final value of *pbRes is undefined in this case.
  138986. **
  138987. ** This is used to test if a segment is an "appendable" segment. If it
  138988. ** is, then a NULL entry has been inserted into the %_segments table
  138989. ** with blockid %_segdir.end_block.
  138990. */
  138991. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  138992. int bRes = 0; /* Result to set *pbRes to */
  138993. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  138994. int rc; /* Return code */
  138995. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  138996. if( rc==SQLITE_OK ){
  138997. sqlite3_bind_int64(pCheck, 1, iEnd);
  138998. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  138999. rc = sqlite3_reset(pCheck);
  139000. }
  139001. *pbRes = bRes;
  139002. return rc;
  139003. }
  139004. /*
  139005. ** This function is called when initializing an incremental-merge operation.
  139006. ** It checks if the existing segment with index value iIdx at absolute level
  139007. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  139008. ** merge-writer object *pWriter is initialized to write to it.
  139009. **
  139010. ** An existing segment can be appended to by an incremental merge if:
  139011. **
  139012. ** * It was initially created as an appendable segment (with all required
  139013. ** space pre-allocated), and
  139014. **
  139015. ** * The first key read from the input (arguments zKey and nKey) is
  139016. ** greater than the largest key currently stored in the potential
  139017. ** output segment.
  139018. */
  139019. static int fts3IncrmergeLoad(
  139020. Fts3Table *p, /* Fts3 table handle */
  139021. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  139022. int iIdx, /* Index of candidate output segment */
  139023. const char *zKey, /* First key to write */
  139024. int nKey, /* Number of bytes in nKey */
  139025. IncrmergeWriter *pWriter /* Populate this object */
  139026. ){
  139027. int rc; /* Return code */
  139028. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  139029. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  139030. if( rc==SQLITE_OK ){
  139031. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  139032. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  139033. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  139034. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  139035. int nRoot = 0; /* Size of aRoot[] in bytes */
  139036. int rc2; /* Return code from sqlite3_reset() */
  139037. int bAppendable = 0; /* Set to true if segment is appendable */
  139038. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  139039. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  139040. sqlite3_bind_int(pSelect, 2, iIdx);
  139041. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  139042. iStart = sqlite3_column_int64(pSelect, 1);
  139043. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  139044. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  139045. if( pWriter->nLeafData<0 ){
  139046. pWriter->nLeafData = pWriter->nLeafData * -1;
  139047. }
  139048. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  139049. nRoot = sqlite3_column_bytes(pSelect, 4);
  139050. aRoot = sqlite3_column_blob(pSelect, 4);
  139051. }else{
  139052. return sqlite3_reset(pSelect);
  139053. }
  139054. /* Check for the zero-length marker in the %_segments table */
  139055. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  139056. /* Check that zKey/nKey is larger than the largest key the candidate */
  139057. if( rc==SQLITE_OK && bAppendable ){
  139058. char *aLeaf = 0;
  139059. int nLeaf = 0;
  139060. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  139061. if( rc==SQLITE_OK ){
  139062. NodeReader reader;
  139063. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  139064. rc==SQLITE_OK && reader.aNode;
  139065. rc = nodeReaderNext(&reader)
  139066. ){
  139067. assert( reader.aNode );
  139068. }
  139069. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  139070. bAppendable = 0;
  139071. }
  139072. nodeReaderRelease(&reader);
  139073. }
  139074. sqlite3_free(aLeaf);
  139075. }
  139076. if( rc==SQLITE_OK && bAppendable ){
  139077. /* It is possible to append to this segment. Set up the IncrmergeWriter
  139078. ** object to do so. */
  139079. int i;
  139080. int nHeight = (int)aRoot[0];
  139081. NodeWriter *pNode;
  139082. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  139083. pWriter->iStart = iStart;
  139084. pWriter->iEnd = iEnd;
  139085. pWriter->iAbsLevel = iAbsLevel;
  139086. pWriter->iIdx = iIdx;
  139087. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  139088. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  139089. }
  139090. pNode = &pWriter->aNodeWriter[nHeight];
  139091. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  139092. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  139093. if( rc==SQLITE_OK ){
  139094. memcpy(pNode->block.a, aRoot, nRoot);
  139095. pNode->block.n = nRoot;
  139096. }
  139097. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  139098. NodeReader reader;
  139099. pNode = &pWriter->aNodeWriter[i];
  139100. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  139101. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  139102. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  139103. if( rc==SQLITE_OK ){
  139104. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  139105. pNode->key.n = reader.term.n;
  139106. if( i>0 ){
  139107. char *aBlock = 0;
  139108. int nBlock = 0;
  139109. pNode = &pWriter->aNodeWriter[i-1];
  139110. pNode->iBlock = reader.iChild;
  139111. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  139112. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  139113. if( rc==SQLITE_OK ){
  139114. memcpy(pNode->block.a, aBlock, nBlock);
  139115. pNode->block.n = nBlock;
  139116. }
  139117. sqlite3_free(aBlock);
  139118. }
  139119. }
  139120. nodeReaderRelease(&reader);
  139121. }
  139122. }
  139123. rc2 = sqlite3_reset(pSelect);
  139124. if( rc==SQLITE_OK ) rc = rc2;
  139125. }
  139126. return rc;
  139127. }
  139128. /*
  139129. ** Determine the largest segment index value that exists within absolute
  139130. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  139131. ** one before returning SQLITE_OK. Or, if there are no segments at all
  139132. ** within level iAbsLevel, set *piIdx to zero.
  139133. **
  139134. ** If an error occurs, return an SQLite error code. The final value of
  139135. ** *piIdx is undefined in this case.
  139136. */
  139137. static int fts3IncrmergeOutputIdx(
  139138. Fts3Table *p, /* FTS Table handle */
  139139. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  139140. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  139141. ){
  139142. int rc;
  139143. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  139144. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  139145. if( rc==SQLITE_OK ){
  139146. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  139147. sqlite3_step(pOutputIdx);
  139148. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  139149. rc = sqlite3_reset(pOutputIdx);
  139150. }
  139151. return rc;
  139152. }
  139153. /*
  139154. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  139155. ** with idx value iIdx.
  139156. **
  139157. ** In the %_segdir table, a segment is defined by the values in three
  139158. ** columns:
  139159. **
  139160. ** start_block
  139161. ** leaves_end_block
  139162. ** end_block
  139163. **
  139164. ** When an appendable segment is allocated, it is estimated that the
  139165. ** maximum number of leaf blocks that may be required is the sum of the
  139166. ** number of leaf blocks consumed by the input segments, plus the number
  139167. ** of input segments, multiplied by two. This value is stored in stack
  139168. ** variable nLeafEst.
  139169. **
  139170. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  139171. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  139172. ** array of leaf nodes starts at the first block allocated. The array
  139173. ** of interior nodes that are parents of the leaf nodes start at block
  139174. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  139175. **
  139176. ** In the actual code below, the value "16" is replaced with the
  139177. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  139178. */
  139179. static int fts3IncrmergeWriter(
  139180. Fts3Table *p, /* Fts3 table handle */
  139181. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  139182. int iIdx, /* Index of new output segment */
  139183. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  139184. IncrmergeWriter *pWriter /* Populate this object */
  139185. ){
  139186. int rc; /* Return Code */
  139187. int i; /* Iterator variable */
  139188. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  139189. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  139190. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  139191. /* Calculate nLeafEst. */
  139192. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  139193. if( rc==SQLITE_OK ){
  139194. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  139195. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  139196. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  139197. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  139198. }
  139199. rc = sqlite3_reset(pLeafEst);
  139200. }
  139201. if( rc!=SQLITE_OK ) return rc;
  139202. /* Calculate the first block to use in the output segment */
  139203. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  139204. if( rc==SQLITE_OK ){
  139205. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  139206. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  139207. pWriter->iEnd = pWriter->iStart - 1;
  139208. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  139209. }
  139210. rc = sqlite3_reset(pFirstBlock);
  139211. }
  139212. if( rc!=SQLITE_OK ) return rc;
  139213. /* Insert the marker in the %_segments table to make sure nobody tries
  139214. ** to steal the space just allocated. This is also used to identify
  139215. ** appendable segments. */
  139216. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  139217. if( rc!=SQLITE_OK ) return rc;
  139218. pWriter->iAbsLevel = iAbsLevel;
  139219. pWriter->nLeafEst = nLeafEst;
  139220. pWriter->iIdx = iIdx;
  139221. /* Set up the array of NodeWriter objects */
  139222. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  139223. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  139224. }
  139225. return SQLITE_OK;
  139226. }
  139227. /*
  139228. ** Remove an entry from the %_segdir table. This involves running the
  139229. ** following two statements:
  139230. **
  139231. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  139232. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  139233. **
  139234. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  139235. ** statement ensures that the remaining segments have contiguously allocated
  139236. ** idx values.
  139237. */
  139238. static int fts3RemoveSegdirEntry(
  139239. Fts3Table *p, /* FTS3 table handle */
  139240. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  139241. int iIdx /* Index of %_segdir entry to delete */
  139242. ){
  139243. int rc; /* Return code */
  139244. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  139245. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  139246. if( rc==SQLITE_OK ){
  139247. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  139248. sqlite3_bind_int(pDelete, 2, iIdx);
  139249. sqlite3_step(pDelete);
  139250. rc = sqlite3_reset(pDelete);
  139251. }
  139252. return rc;
  139253. }
  139254. /*
  139255. ** One or more segments have just been removed from absolute level iAbsLevel.
  139256. ** Update the 'idx' values of the remaining segments in the level so that
  139257. ** the idx values are a contiguous sequence starting from 0.
  139258. */
  139259. static int fts3RepackSegdirLevel(
  139260. Fts3Table *p, /* FTS3 table handle */
  139261. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  139262. ){
  139263. int rc; /* Return code */
  139264. int *aIdx = 0; /* Array of remaining idx values */
  139265. int nIdx = 0; /* Valid entries in aIdx[] */
  139266. int nAlloc = 0; /* Allocated size of aIdx[] */
  139267. int i; /* Iterator variable */
  139268. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  139269. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  139270. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  139271. if( rc==SQLITE_OK ){
  139272. int rc2;
  139273. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  139274. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  139275. if( nIdx>=nAlloc ){
  139276. int *aNew;
  139277. nAlloc += 16;
  139278. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  139279. if( !aNew ){
  139280. rc = SQLITE_NOMEM;
  139281. break;
  139282. }
  139283. aIdx = aNew;
  139284. }
  139285. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  139286. }
  139287. rc2 = sqlite3_reset(pSelect);
  139288. if( rc==SQLITE_OK ) rc = rc2;
  139289. }
  139290. if( rc==SQLITE_OK ){
  139291. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  139292. }
  139293. if( rc==SQLITE_OK ){
  139294. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  139295. }
  139296. assert( p->bIgnoreSavepoint==0 );
  139297. p->bIgnoreSavepoint = 1;
  139298. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  139299. if( aIdx[i]!=i ){
  139300. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  139301. sqlite3_bind_int(pUpdate, 1, i);
  139302. sqlite3_step(pUpdate);
  139303. rc = sqlite3_reset(pUpdate);
  139304. }
  139305. }
  139306. p->bIgnoreSavepoint = 0;
  139307. sqlite3_free(aIdx);
  139308. return rc;
  139309. }
  139310. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  139311. pNode->a[0] = (char)iHeight;
  139312. if( iChild ){
  139313. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  139314. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  139315. }else{
  139316. assert( pNode->nAlloc>=1 );
  139317. pNode->n = 1;
  139318. }
  139319. }
  139320. /*
  139321. ** The first two arguments are a pointer to and the size of a segment b-tree
  139322. ** node. The node may be a leaf or an internal node.
  139323. **
  139324. ** This function creates a new node image in blob object *pNew by copying
  139325. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  139326. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  139327. */
  139328. static int fts3TruncateNode(
  139329. const char *aNode, /* Current node image */
  139330. int nNode, /* Size of aNode in bytes */
  139331. Blob *pNew, /* OUT: Write new node image here */
  139332. const char *zTerm, /* Omit all terms smaller than this */
  139333. int nTerm, /* Size of zTerm in bytes */
  139334. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  139335. ){
  139336. NodeReader reader; /* Reader object */
  139337. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  139338. int rc = SQLITE_OK; /* Return code */
  139339. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  139340. /* Allocate required output space */
  139341. blobGrowBuffer(pNew, nNode, &rc);
  139342. if( rc!=SQLITE_OK ) return rc;
  139343. pNew->n = 0;
  139344. /* Populate new node buffer */
  139345. for(rc = nodeReaderInit(&reader, aNode, nNode);
  139346. rc==SQLITE_OK && reader.aNode;
  139347. rc = nodeReaderNext(&reader)
  139348. ){
  139349. if( pNew->n==0 ){
  139350. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  139351. if( res<0 || (bLeaf==0 && res==0) ) continue;
  139352. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  139353. *piBlock = reader.iChild;
  139354. }
  139355. rc = fts3AppendToNode(
  139356. pNew, &prev, reader.term.a, reader.term.n,
  139357. reader.aDoclist, reader.nDoclist
  139358. );
  139359. if( rc!=SQLITE_OK ) break;
  139360. }
  139361. if( pNew->n==0 ){
  139362. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  139363. *piBlock = reader.iChild;
  139364. }
  139365. assert( pNew->n<=pNew->nAlloc );
  139366. nodeReaderRelease(&reader);
  139367. sqlite3_free(prev.a);
  139368. return rc;
  139369. }
  139370. /*
  139371. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  139372. ** level iAbsLevel. This may involve deleting entries from the %_segments
  139373. ** table, and modifying existing entries in both the %_segments and %_segdir
  139374. ** tables.
  139375. **
  139376. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  139377. ** SQLite error code otherwise.
  139378. */
  139379. static int fts3TruncateSegment(
  139380. Fts3Table *p, /* FTS3 table handle */
  139381. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  139382. int iIdx, /* Index within level of segment to modify */
  139383. const char *zTerm, /* Remove terms smaller than this */
  139384. int nTerm /* Number of bytes in buffer zTerm */
  139385. ){
  139386. int rc = SQLITE_OK; /* Return code */
  139387. Blob root = {0,0,0}; /* New root page image */
  139388. Blob block = {0,0,0}; /* Buffer used for any other block */
  139389. sqlite3_int64 iBlock = 0; /* Block id */
  139390. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  139391. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  139392. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  139393. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  139394. if( rc==SQLITE_OK ){
  139395. int rc2; /* sqlite3_reset() return code */
  139396. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  139397. sqlite3_bind_int(pFetch, 2, iIdx);
  139398. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  139399. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  139400. int nRoot = sqlite3_column_bytes(pFetch, 4);
  139401. iOldStart = sqlite3_column_int64(pFetch, 1);
  139402. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  139403. }
  139404. rc2 = sqlite3_reset(pFetch);
  139405. if( rc==SQLITE_OK ) rc = rc2;
  139406. }
  139407. while( rc==SQLITE_OK && iBlock ){
  139408. char *aBlock = 0;
  139409. int nBlock = 0;
  139410. iNewStart = iBlock;
  139411. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  139412. if( rc==SQLITE_OK ){
  139413. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  139414. }
  139415. if( rc==SQLITE_OK ){
  139416. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  139417. }
  139418. sqlite3_free(aBlock);
  139419. }
  139420. /* Variable iNewStart now contains the first valid leaf node. */
  139421. if( rc==SQLITE_OK && iNewStart ){
  139422. sqlite3_stmt *pDel = 0;
  139423. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  139424. if( rc==SQLITE_OK ){
  139425. sqlite3_bind_int64(pDel, 1, iOldStart);
  139426. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  139427. sqlite3_step(pDel);
  139428. rc = sqlite3_reset(pDel);
  139429. }
  139430. }
  139431. if( rc==SQLITE_OK ){
  139432. sqlite3_stmt *pChomp = 0;
  139433. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  139434. if( rc==SQLITE_OK ){
  139435. sqlite3_bind_int64(pChomp, 1, iNewStart);
  139436. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  139437. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  139438. sqlite3_bind_int(pChomp, 4, iIdx);
  139439. sqlite3_step(pChomp);
  139440. rc = sqlite3_reset(pChomp);
  139441. }
  139442. }
  139443. sqlite3_free(root.a);
  139444. sqlite3_free(block.a);
  139445. return rc;
  139446. }
  139447. /*
  139448. ** This function is called after an incrmental-merge operation has run to
  139449. ** merge (or partially merge) two or more segments from absolute level
  139450. ** iAbsLevel.
  139451. **
  139452. ** Each input segment is either removed from the db completely (if all of
  139453. ** its data was copied to the output segment by the incrmerge operation)
  139454. ** or modified in place so that it no longer contains those entries that
  139455. ** have been duplicated in the output segment.
  139456. */
  139457. static int fts3IncrmergeChomp(
  139458. Fts3Table *p, /* FTS table handle */
  139459. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  139460. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  139461. int *pnRem /* Number of segments not deleted */
  139462. ){
  139463. int i;
  139464. int nRem = 0;
  139465. int rc = SQLITE_OK;
  139466. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  139467. Fts3SegReader *pSeg = 0;
  139468. int j;
  139469. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  139470. ** somewhere in the pCsr->apSegment[] array. */
  139471. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  139472. pSeg = pCsr->apSegment[j];
  139473. if( pSeg->iIdx==i ) break;
  139474. }
  139475. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  139476. if( pSeg->aNode==0 ){
  139477. /* Seg-reader is at EOF. Remove the entire input segment. */
  139478. rc = fts3DeleteSegment(p, pSeg);
  139479. if( rc==SQLITE_OK ){
  139480. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  139481. }
  139482. *pnRem = 0;
  139483. }else{
  139484. /* The incremental merge did not copy all the data from this
  139485. ** segment to the upper level. The segment is modified in place
  139486. ** so that it contains no keys smaller than zTerm/nTerm. */
  139487. const char *zTerm = pSeg->zTerm;
  139488. int nTerm = pSeg->nTerm;
  139489. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  139490. nRem++;
  139491. }
  139492. }
  139493. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  139494. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  139495. }
  139496. *pnRem = nRem;
  139497. return rc;
  139498. }
  139499. /*
  139500. ** Store an incr-merge hint in the database.
  139501. */
  139502. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  139503. sqlite3_stmt *pReplace = 0;
  139504. int rc; /* Return code */
  139505. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  139506. if( rc==SQLITE_OK ){
  139507. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  139508. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  139509. sqlite3_step(pReplace);
  139510. rc = sqlite3_reset(pReplace);
  139511. }
  139512. return rc;
  139513. }
  139514. /*
  139515. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  139516. ** exists, is stored in the rowid==1 row of the %_stat table.
  139517. **
  139518. ** If successful, populate blob *pHint with the value read from the %_stat
  139519. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  139520. ** SQLite error code.
  139521. */
  139522. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  139523. sqlite3_stmt *pSelect = 0;
  139524. int rc;
  139525. pHint->n = 0;
  139526. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  139527. if( rc==SQLITE_OK ){
  139528. int rc2;
  139529. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  139530. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  139531. const char *aHint = sqlite3_column_blob(pSelect, 0);
  139532. int nHint = sqlite3_column_bytes(pSelect, 0);
  139533. if( aHint ){
  139534. blobGrowBuffer(pHint, nHint, &rc);
  139535. if( rc==SQLITE_OK ){
  139536. memcpy(pHint->a, aHint, nHint);
  139537. pHint->n = nHint;
  139538. }
  139539. }
  139540. }
  139541. rc2 = sqlite3_reset(pSelect);
  139542. if( rc==SQLITE_OK ) rc = rc2;
  139543. }
  139544. return rc;
  139545. }
  139546. /*
  139547. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  139548. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  139549. ** consists of two varints, the absolute level number of the input segments
  139550. ** and the number of input segments.
  139551. **
  139552. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  139553. ** set *pRc to an SQLite error code before returning.
  139554. */
  139555. static void fts3IncrmergeHintPush(
  139556. Blob *pHint, /* Hint blob to append to */
  139557. i64 iAbsLevel, /* First varint to store in hint */
  139558. int nInput, /* Second varint to store in hint */
  139559. int *pRc /* IN/OUT: Error code */
  139560. ){
  139561. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  139562. if( *pRc==SQLITE_OK ){
  139563. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  139564. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  139565. }
  139566. }
  139567. /*
  139568. ** Read the last entry (most recently pushed) from the hint blob *pHint
  139569. ** and then remove the entry. Write the two values read to *piAbsLevel and
  139570. ** *pnInput before returning.
  139571. **
  139572. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  139573. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  139574. */
  139575. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  139576. const int nHint = pHint->n;
  139577. int i;
  139578. i = pHint->n-2;
  139579. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  139580. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  139581. pHint->n = i;
  139582. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  139583. i += fts3GetVarint32(&pHint->a[i], pnInput);
  139584. if( i!=nHint ) return FTS_CORRUPT_VTAB;
  139585. return SQLITE_OK;
  139586. }
  139587. /*
  139588. ** Attempt an incremental merge that writes nMerge leaf blocks.
  139589. **
  139590. ** Incremental merges happen nMin segments at a time. The segments
  139591. ** to be merged are the nMin oldest segments (the ones with the smallest
  139592. ** values for the _segdir.idx field) in the highest level that contains
  139593. ** at least nMin segments. Multiple merges might occur in an attempt to
  139594. ** write the quota of nMerge leaf blocks.
  139595. */
  139596. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  139597. int rc; /* Return code */
  139598. int nRem = nMerge; /* Number of leaf pages yet to be written */
  139599. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  139600. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  139601. IncrmergeWriter *pWriter; /* Writer object */
  139602. int nSeg = 0; /* Number of input segments */
  139603. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  139604. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  139605. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  139606. /* Allocate space for the cursor, filter and writer objects */
  139607. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  139608. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  139609. if( !pWriter ) return SQLITE_NOMEM;
  139610. pFilter = (Fts3SegFilter *)&pWriter[1];
  139611. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  139612. rc = fts3IncrmergeHintLoad(p, &hint);
  139613. while( rc==SQLITE_OK && nRem>0 ){
  139614. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  139615. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  139616. int bUseHint = 0; /* True if attempting to append */
  139617. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  139618. /* Search the %_segdir table for the absolute level with the smallest
  139619. ** relative level number that contains at least nMin segments, if any.
  139620. ** If one is found, set iAbsLevel to the absolute level number and
  139621. ** nSeg to nMin. If no level with at least nMin segments can be found,
  139622. ** set nSeg to -1.
  139623. */
  139624. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  139625. sqlite3_bind_int(pFindLevel, 1, nMin);
  139626. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  139627. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  139628. nSeg = nMin;
  139629. }else{
  139630. nSeg = -1;
  139631. }
  139632. rc = sqlite3_reset(pFindLevel);
  139633. /* If the hint read from the %_stat table is not empty, check if the
  139634. ** last entry in it specifies a relative level smaller than or equal
  139635. ** to the level identified by the block above (if any). If so, this
  139636. ** iteration of the loop will work on merging at the hinted level.
  139637. */
  139638. if( rc==SQLITE_OK && hint.n ){
  139639. int nHint = hint.n;
  139640. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  139641. int nHintSeg = 0; /* Hint number of segments */
  139642. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  139643. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  139644. iAbsLevel = iHintAbsLevel;
  139645. nSeg = nHintSeg;
  139646. bUseHint = 1;
  139647. bDirtyHint = 1;
  139648. }else{
  139649. /* This undoes the effect of the HintPop() above - so that no entry
  139650. ** is removed from the hint blob. */
  139651. hint.n = nHint;
  139652. }
  139653. }
  139654. /* If nSeg is less that zero, then there is no level with at least
  139655. ** nMin segments and no hint in the %_stat table. No work to do.
  139656. ** Exit early in this case. */
  139657. if( nSeg<0 ) break;
  139658. /* Open a cursor to iterate through the contents of the oldest nSeg
  139659. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  139660. ** the 'hint' parameters, it is possible that there are less than nSeg
  139661. ** segments available in level iAbsLevel. In this case, no work is
  139662. ** done on iAbsLevel - fall through to the next iteration of the loop
  139663. ** to start work on some other level. */
  139664. memset(pWriter, 0, nAlloc);
  139665. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  139666. if( rc==SQLITE_OK ){
  139667. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  139668. assert( bUseHint==1 || bUseHint==0 );
  139669. if( iIdx==0 || (bUseHint && iIdx==1) ){
  139670. int bIgnore = 0;
  139671. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  139672. if( bIgnore ){
  139673. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  139674. }
  139675. }
  139676. }
  139677. if( rc==SQLITE_OK ){
  139678. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  139679. }
  139680. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  139681. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  139682. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  139683. ){
  139684. if( bUseHint && iIdx>0 ){
  139685. const char *zKey = pCsr->zTerm;
  139686. int nKey = pCsr->nTerm;
  139687. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  139688. }else{
  139689. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  139690. }
  139691. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  139692. fts3LogMerge(nSeg, iAbsLevel);
  139693. do {
  139694. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  139695. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  139696. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  139697. }while( rc==SQLITE_ROW );
  139698. /* Update or delete the input segments */
  139699. if( rc==SQLITE_OK ){
  139700. nRem -= (1 + pWriter->nWork);
  139701. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  139702. if( nSeg!=0 ){
  139703. bDirtyHint = 1;
  139704. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  139705. }
  139706. }
  139707. }
  139708. if( nSeg!=0 ){
  139709. pWriter->nLeafData = pWriter->nLeafData * -1;
  139710. }
  139711. fts3IncrmergeRelease(p, pWriter, &rc);
  139712. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  139713. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  139714. }
  139715. }
  139716. sqlite3Fts3SegReaderFinish(pCsr);
  139717. }
  139718. /* Write the hint values into the %_stat table for the next incr-merger */
  139719. if( bDirtyHint && rc==SQLITE_OK ){
  139720. rc = fts3IncrmergeHintStore(p, &hint);
  139721. }
  139722. sqlite3_free(pWriter);
  139723. sqlite3_free(hint.a);
  139724. return rc;
  139725. }
  139726. /*
  139727. ** Convert the text beginning at *pz into an integer and return
  139728. ** its value. Advance *pz to point to the first character past
  139729. ** the integer.
  139730. */
  139731. static int fts3Getint(const char **pz){
  139732. const char *z = *pz;
  139733. int i = 0;
  139734. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  139735. *pz = z;
  139736. return i;
  139737. }
  139738. /*
  139739. ** Process statements of the form:
  139740. **
  139741. ** INSERT INTO table(table) VALUES('merge=A,B');
  139742. **
  139743. ** A and B are integers that decode to be the number of leaf pages
  139744. ** written for the merge, and the minimum number of segments on a level
  139745. ** before it will be selected for a merge, respectively.
  139746. */
  139747. static int fts3DoIncrmerge(
  139748. Fts3Table *p, /* FTS3 table handle */
  139749. const char *zParam /* Nul-terminated string containing "A,B" */
  139750. ){
  139751. int rc;
  139752. int nMin = (FTS3_MERGE_COUNT / 2);
  139753. int nMerge = 0;
  139754. const char *z = zParam;
  139755. /* Read the first integer value */
  139756. nMerge = fts3Getint(&z);
  139757. /* If the first integer value is followed by a ',', read the second
  139758. ** integer value. */
  139759. if( z[0]==',' && z[1]!='\0' ){
  139760. z++;
  139761. nMin = fts3Getint(&z);
  139762. }
  139763. if( z[0]!='\0' || nMin<2 ){
  139764. rc = SQLITE_ERROR;
  139765. }else{
  139766. rc = SQLITE_OK;
  139767. if( !p->bHasStat ){
  139768. assert( p->bFts4==0 );
  139769. sqlite3Fts3CreateStatTable(&rc, p);
  139770. }
  139771. if( rc==SQLITE_OK ){
  139772. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  139773. }
  139774. sqlite3Fts3SegmentsClose(p);
  139775. }
  139776. return rc;
  139777. }
  139778. /*
  139779. ** Process statements of the form:
  139780. **
  139781. ** INSERT INTO table(table) VALUES('automerge=X');
  139782. **
  139783. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  139784. ** turn it on. The setting is persistent.
  139785. */
  139786. static int fts3DoAutoincrmerge(
  139787. Fts3Table *p, /* FTS3 table handle */
  139788. const char *zParam /* Nul-terminated string containing boolean */
  139789. ){
  139790. int rc = SQLITE_OK;
  139791. sqlite3_stmt *pStmt = 0;
  139792. p->nAutoincrmerge = fts3Getint(&zParam);
  139793. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  139794. p->nAutoincrmerge = 8;
  139795. }
  139796. if( !p->bHasStat ){
  139797. assert( p->bFts4==0 );
  139798. sqlite3Fts3CreateStatTable(&rc, p);
  139799. if( rc ) return rc;
  139800. }
  139801. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  139802. if( rc ) return rc;
  139803. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  139804. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  139805. sqlite3_step(pStmt);
  139806. rc = sqlite3_reset(pStmt);
  139807. return rc;
  139808. }
  139809. /*
  139810. ** Return a 64-bit checksum for the FTS index entry specified by the
  139811. ** arguments to this function.
  139812. */
  139813. static u64 fts3ChecksumEntry(
  139814. const char *zTerm, /* Pointer to buffer containing term */
  139815. int nTerm, /* Size of zTerm in bytes */
  139816. int iLangid, /* Language id for current row */
  139817. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  139818. i64 iDocid, /* Docid for current row. */
  139819. int iCol, /* Column number */
  139820. int iPos /* Position */
  139821. ){
  139822. int i;
  139823. u64 ret = (u64)iDocid;
  139824. ret += (ret<<3) + iLangid;
  139825. ret += (ret<<3) + iIndex;
  139826. ret += (ret<<3) + iCol;
  139827. ret += (ret<<3) + iPos;
  139828. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  139829. return ret;
  139830. }
  139831. /*
  139832. ** Return a checksum of all entries in the FTS index that correspond to
  139833. ** language id iLangid. The checksum is calculated by XORing the checksums
  139834. ** of each individual entry (see fts3ChecksumEntry()) together.
  139835. **
  139836. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  139837. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  139838. ** return value is undefined in this case.
  139839. */
  139840. static u64 fts3ChecksumIndex(
  139841. Fts3Table *p, /* FTS3 table handle */
  139842. int iLangid, /* Language id to return cksum for */
  139843. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  139844. int *pRc /* OUT: Return code */
  139845. ){
  139846. Fts3SegFilter filter;
  139847. Fts3MultiSegReader csr;
  139848. int rc;
  139849. u64 cksum = 0;
  139850. assert( *pRc==SQLITE_OK );
  139851. memset(&filter, 0, sizeof(filter));
  139852. memset(&csr, 0, sizeof(csr));
  139853. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  139854. filter.flags |= FTS3_SEGMENT_SCAN;
  139855. rc = sqlite3Fts3SegReaderCursor(
  139856. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  139857. );
  139858. if( rc==SQLITE_OK ){
  139859. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  139860. }
  139861. if( rc==SQLITE_OK ){
  139862. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  139863. char *pCsr = csr.aDoclist;
  139864. char *pEnd = &pCsr[csr.nDoclist];
  139865. i64 iDocid = 0;
  139866. i64 iCol = 0;
  139867. i64 iPos = 0;
  139868. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  139869. while( pCsr<pEnd ){
  139870. i64 iVal = 0;
  139871. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  139872. if( pCsr<pEnd ){
  139873. if( iVal==0 || iVal==1 ){
  139874. iCol = 0;
  139875. iPos = 0;
  139876. if( iVal ){
  139877. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  139878. }else{
  139879. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  139880. iDocid += iVal;
  139881. }
  139882. }else{
  139883. iPos += (iVal - 2);
  139884. cksum = cksum ^ fts3ChecksumEntry(
  139885. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  139886. (int)iCol, (int)iPos
  139887. );
  139888. }
  139889. }
  139890. }
  139891. }
  139892. }
  139893. sqlite3Fts3SegReaderFinish(&csr);
  139894. *pRc = rc;
  139895. return cksum;
  139896. }
  139897. /*
  139898. ** Check if the contents of the FTS index match the current contents of the
  139899. ** content table. If no error occurs and the contents do match, set *pbOk
  139900. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  139901. ** to false before returning.
  139902. **
  139903. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  139904. ** code. The final value of *pbOk is undefined in this case.
  139905. */
  139906. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  139907. int rc = SQLITE_OK; /* Return code */
  139908. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  139909. u64 cksum2 = 0; /* Checksum based on %_content contents */
  139910. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  139911. /* This block calculates the checksum according to the FTS index. */
  139912. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  139913. if( rc==SQLITE_OK ){
  139914. int rc2;
  139915. sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
  139916. sqlite3_bind_int(pAllLangid, 2, p->nIndex);
  139917. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  139918. int iLangid = sqlite3_column_int(pAllLangid, 0);
  139919. int i;
  139920. for(i=0; i<p->nIndex; i++){
  139921. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  139922. }
  139923. }
  139924. rc2 = sqlite3_reset(pAllLangid);
  139925. if( rc==SQLITE_OK ) rc = rc2;
  139926. }
  139927. /* This block calculates the checksum according to the %_content table */
  139928. if( rc==SQLITE_OK ){
  139929. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  139930. sqlite3_stmt *pStmt = 0;
  139931. char *zSql;
  139932. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  139933. if( !zSql ){
  139934. rc = SQLITE_NOMEM;
  139935. }else{
  139936. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  139937. sqlite3_free(zSql);
  139938. }
  139939. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  139940. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  139941. int iLang = langidFromSelect(p, pStmt);
  139942. int iCol;
  139943. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  139944. if( p->abNotindexed[iCol]==0 ){
  139945. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  139946. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  139947. sqlite3_tokenizer_cursor *pT = 0;
  139948. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  139949. while( rc==SQLITE_OK ){
  139950. char const *zToken; /* Buffer containing token */
  139951. int nToken = 0; /* Number of bytes in token */
  139952. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  139953. int iPos = 0; /* Position of token in zText */
  139954. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  139955. if( rc==SQLITE_OK ){
  139956. int i;
  139957. cksum2 = cksum2 ^ fts3ChecksumEntry(
  139958. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  139959. );
  139960. for(i=1; i<p->nIndex; i++){
  139961. if( p->aIndex[i].nPrefix<=nToken ){
  139962. cksum2 = cksum2 ^ fts3ChecksumEntry(
  139963. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  139964. );
  139965. }
  139966. }
  139967. }
  139968. }
  139969. if( pT ) pModule->xClose(pT);
  139970. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  139971. }
  139972. }
  139973. }
  139974. sqlite3_finalize(pStmt);
  139975. }
  139976. *pbOk = (cksum1==cksum2);
  139977. return rc;
  139978. }
  139979. /*
  139980. ** Run the integrity-check. If no error occurs and the current contents of
  139981. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  139982. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  139983. **
  139984. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  139985. ** error code.
  139986. **
  139987. ** The integrity-check works as follows. For each token and indexed token
  139988. ** prefix in the document set, a 64-bit checksum is calculated (by code
  139989. ** in fts3ChecksumEntry()) based on the following:
  139990. **
  139991. ** + The index number (0 for the main index, 1 for the first prefix
  139992. ** index etc.),
  139993. ** + The token (or token prefix) text itself,
  139994. ** + The language-id of the row it appears in,
  139995. ** + The docid of the row it appears in,
  139996. ** + The column it appears in, and
  139997. ** + The tokens position within that column.
  139998. **
  139999. ** The checksums for all entries in the index are XORed together to create
  140000. ** a single checksum for the entire index.
  140001. **
  140002. ** The integrity-check code calculates the same checksum in two ways:
  140003. **
  140004. ** 1. By scanning the contents of the FTS index, and
  140005. ** 2. By scanning and tokenizing the content table.
  140006. **
  140007. ** If the two checksums are identical, the integrity-check is deemed to have
  140008. ** passed.
  140009. */
  140010. static int fts3DoIntegrityCheck(
  140011. Fts3Table *p /* FTS3 table handle */
  140012. ){
  140013. int rc;
  140014. int bOk = 0;
  140015. rc = fts3IntegrityCheck(p, &bOk);
  140016. if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
  140017. return rc;
  140018. }
  140019. /*
  140020. ** Handle a 'special' INSERT of the form:
  140021. **
  140022. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  140023. **
  140024. ** Argument pVal contains the result of <expr>. Currently the only
  140025. ** meaningful value to insert is the text 'optimize'.
  140026. */
  140027. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  140028. int rc; /* Return Code */
  140029. const char *zVal = (const char *)sqlite3_value_text(pVal);
  140030. int nVal = sqlite3_value_bytes(pVal);
  140031. if( !zVal ){
  140032. return SQLITE_NOMEM;
  140033. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  140034. rc = fts3DoOptimize(p, 0);
  140035. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  140036. rc = fts3DoRebuild(p);
  140037. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  140038. rc = fts3DoIntegrityCheck(p);
  140039. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  140040. rc = fts3DoIncrmerge(p, &zVal[6]);
  140041. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  140042. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  140043. #ifdef SQLITE_TEST
  140044. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  140045. p->nNodeSize = atoi(&zVal[9]);
  140046. rc = SQLITE_OK;
  140047. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  140048. p->nMaxPendingData = atoi(&zVal[11]);
  140049. rc = SQLITE_OK;
  140050. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  140051. p->bNoIncrDoclist = atoi(&zVal[21]);
  140052. rc = SQLITE_OK;
  140053. #endif
  140054. }else{
  140055. rc = SQLITE_ERROR;
  140056. }
  140057. return rc;
  140058. }
  140059. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  140060. /*
  140061. ** Delete all cached deferred doclists. Deferred doclists are cached
  140062. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  140063. */
  140064. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  140065. Fts3DeferredToken *pDef;
  140066. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  140067. fts3PendingListDelete(pDef->pList);
  140068. pDef->pList = 0;
  140069. }
  140070. }
  140071. /*
  140072. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  140073. ** this list using sqlite3Fts3DeferToken().
  140074. */
  140075. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  140076. Fts3DeferredToken *pDef;
  140077. Fts3DeferredToken *pNext;
  140078. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  140079. pNext = pDef->pNext;
  140080. fts3PendingListDelete(pDef->pList);
  140081. sqlite3_free(pDef);
  140082. }
  140083. pCsr->pDeferred = 0;
  140084. }
  140085. /*
  140086. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  140087. ** based on the row that pCsr currently points to.
  140088. **
  140089. ** A deferred-doclist is like any other doclist with position information
  140090. ** included, except that it only contains entries for a single row of the
  140091. ** table, not for all rows.
  140092. */
  140093. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  140094. int rc = SQLITE_OK; /* Return code */
  140095. if( pCsr->pDeferred ){
  140096. int i; /* Used to iterate through table columns */
  140097. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  140098. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  140099. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  140100. sqlite3_tokenizer *pT = p->pTokenizer;
  140101. sqlite3_tokenizer_module const *pModule = pT->pModule;
  140102. assert( pCsr->isRequireSeek==0 );
  140103. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  140104. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  140105. if( p->abNotindexed[i]==0 ){
  140106. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  140107. sqlite3_tokenizer_cursor *pTC = 0;
  140108. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  140109. while( rc==SQLITE_OK ){
  140110. char const *zToken; /* Buffer containing token */
  140111. int nToken = 0; /* Number of bytes in token */
  140112. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  140113. int iPos = 0; /* Position of token in zText */
  140114. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  140115. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  140116. Fts3PhraseToken *pPT = pDef->pToken;
  140117. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  140118. && (pPT->bFirst==0 || iPos==0)
  140119. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  140120. && (0==memcmp(zToken, pPT->z, pPT->n))
  140121. ){
  140122. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  140123. }
  140124. }
  140125. }
  140126. if( pTC ) pModule->xClose(pTC);
  140127. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  140128. }
  140129. }
  140130. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  140131. if( pDef->pList ){
  140132. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  140133. }
  140134. }
  140135. }
  140136. return rc;
  140137. }
  140138. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  140139. Fts3DeferredToken *p,
  140140. char **ppData,
  140141. int *pnData
  140142. ){
  140143. char *pRet;
  140144. int nSkip;
  140145. sqlite3_int64 dummy;
  140146. *ppData = 0;
  140147. *pnData = 0;
  140148. if( p->pList==0 ){
  140149. return SQLITE_OK;
  140150. }
  140151. pRet = (char *)sqlite3_malloc(p->pList->nData);
  140152. if( !pRet ) return SQLITE_NOMEM;
  140153. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  140154. *pnData = p->pList->nData - nSkip;
  140155. *ppData = pRet;
  140156. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  140157. return SQLITE_OK;
  140158. }
  140159. /*
  140160. ** Add an entry for token pToken to the pCsr->pDeferred list.
  140161. */
  140162. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  140163. Fts3Cursor *pCsr, /* Fts3 table cursor */
  140164. Fts3PhraseToken *pToken, /* Token to defer */
  140165. int iCol /* Column that token must appear in (or -1) */
  140166. ){
  140167. Fts3DeferredToken *pDeferred;
  140168. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  140169. if( !pDeferred ){
  140170. return SQLITE_NOMEM;
  140171. }
  140172. memset(pDeferred, 0, sizeof(*pDeferred));
  140173. pDeferred->pToken = pToken;
  140174. pDeferred->pNext = pCsr->pDeferred;
  140175. pDeferred->iCol = iCol;
  140176. pCsr->pDeferred = pDeferred;
  140177. assert( pToken->pDeferred==0 );
  140178. pToken->pDeferred = pDeferred;
  140179. return SQLITE_OK;
  140180. }
  140181. #endif
  140182. /*
  140183. ** SQLite value pRowid contains the rowid of a row that may or may not be
  140184. ** present in the FTS3 table. If it is, delete it and adjust the contents
  140185. ** of subsiduary data structures accordingly.
  140186. */
  140187. static int fts3DeleteByRowid(
  140188. Fts3Table *p,
  140189. sqlite3_value *pRowid,
  140190. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  140191. u32 *aSzDel
  140192. ){
  140193. int rc = SQLITE_OK; /* Return code */
  140194. int bFound = 0; /* True if *pRowid really is in the table */
  140195. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  140196. if( bFound && rc==SQLITE_OK ){
  140197. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  140198. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  140199. if( rc==SQLITE_OK ){
  140200. if( isEmpty ){
  140201. /* Deleting this row means the whole table is empty. In this case
  140202. ** delete the contents of all three tables and throw away any
  140203. ** data in the pendingTerms hash table. */
  140204. rc = fts3DeleteAll(p, 1);
  140205. *pnChng = 0;
  140206. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  140207. }else{
  140208. *pnChng = *pnChng - 1;
  140209. if( p->zContentTbl==0 ){
  140210. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  140211. }
  140212. if( p->bHasDocsize ){
  140213. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  140214. }
  140215. }
  140216. }
  140217. }
  140218. return rc;
  140219. }
  140220. /*
  140221. ** This function does the work for the xUpdate method of FTS3 virtual
  140222. ** tables. The schema of the virtual table being:
  140223. **
  140224. ** CREATE TABLE <table name>(
  140225. ** <user columns>,
  140226. ** <table name> HIDDEN,
  140227. ** docid HIDDEN,
  140228. ** <langid> HIDDEN
  140229. ** );
  140230. **
  140231. **
  140232. */
  140233. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  140234. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  140235. int nArg, /* Size of argument array */
  140236. sqlite3_value **apVal, /* Array of arguments */
  140237. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  140238. ){
  140239. Fts3Table *p = (Fts3Table *)pVtab;
  140240. int rc = SQLITE_OK; /* Return Code */
  140241. int isRemove = 0; /* True for an UPDATE or DELETE */
  140242. u32 *aSzIns = 0; /* Sizes of inserted documents */
  140243. u32 *aSzDel = 0; /* Sizes of deleted documents */
  140244. int nChng = 0; /* Net change in number of documents */
  140245. int bInsertDone = 0;
  140246. /* At this point it must be known if the %_stat table exists or not.
  140247. ** So bHasStat may not be 2. */
  140248. assert( p->bHasStat==0 || p->bHasStat==1 );
  140249. assert( p->pSegments==0 );
  140250. assert(
  140251. nArg==1 /* DELETE operations */
  140252. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  140253. );
  140254. /* Check for a "special" INSERT operation. One of the form:
  140255. **
  140256. ** INSERT INTO xyz(xyz) VALUES('command');
  140257. */
  140258. if( nArg>1
  140259. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  140260. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  140261. ){
  140262. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  140263. goto update_out;
  140264. }
  140265. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  140266. rc = SQLITE_CONSTRAINT;
  140267. goto update_out;
  140268. }
  140269. /* Allocate space to hold the change in document sizes */
  140270. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  140271. if( aSzDel==0 ){
  140272. rc = SQLITE_NOMEM;
  140273. goto update_out;
  140274. }
  140275. aSzIns = &aSzDel[p->nColumn+1];
  140276. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  140277. rc = fts3Writelock(p);
  140278. if( rc!=SQLITE_OK ) goto update_out;
  140279. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  140280. ** value, then this operation requires constraint handling.
  140281. **
  140282. ** If the on-conflict mode is REPLACE, this means that the existing row
  140283. ** should be deleted from the database before inserting the new row. Or,
  140284. ** if the on-conflict mode is other than REPLACE, then this method must
  140285. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  140286. ** modify the database file.
  140287. */
  140288. if( nArg>1 && p->zContentTbl==0 ){
  140289. /* Find the value object that holds the new rowid value. */
  140290. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  140291. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  140292. pNewRowid = apVal[1];
  140293. }
  140294. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  140295. sqlite3_value_type(apVal[0])==SQLITE_NULL
  140296. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  140297. )){
  140298. /* The new rowid is not NULL (in this case the rowid will be
  140299. ** automatically assigned and there is no chance of a conflict), and
  140300. ** the statement is either an INSERT or an UPDATE that modifies the
  140301. ** rowid column. So if the conflict mode is REPLACE, then delete any
  140302. ** existing row with rowid=pNewRowid.
  140303. **
  140304. ** Or, if the conflict mode is not REPLACE, insert the new record into
  140305. ** the %_content table. If we hit the duplicate rowid constraint (or any
  140306. ** other error) while doing so, return immediately.
  140307. **
  140308. ** This branch may also run if pNewRowid contains a value that cannot
  140309. ** be losslessly converted to an integer. In this case, the eventual
  140310. ** call to fts3InsertData() (either just below or further on in this
  140311. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  140312. ** invoked, it will delete zero rows (since no row will have
  140313. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  140314. */
  140315. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  140316. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  140317. }else{
  140318. rc = fts3InsertData(p, apVal, pRowid);
  140319. bInsertDone = 1;
  140320. }
  140321. }
  140322. }
  140323. if( rc!=SQLITE_OK ){
  140324. goto update_out;
  140325. }
  140326. /* If this is a DELETE or UPDATE operation, remove the old record. */
  140327. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  140328. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  140329. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  140330. isRemove = 1;
  140331. }
  140332. /* If this is an INSERT or UPDATE operation, insert the new record. */
  140333. if( nArg>1 && rc==SQLITE_OK ){
  140334. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  140335. if( bInsertDone==0 ){
  140336. rc = fts3InsertData(p, apVal, pRowid);
  140337. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  140338. rc = FTS_CORRUPT_VTAB;
  140339. }
  140340. }
  140341. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  140342. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  140343. }
  140344. if( rc==SQLITE_OK ){
  140345. assert( p->iPrevDocid==*pRowid );
  140346. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  140347. }
  140348. if( p->bHasDocsize ){
  140349. fts3InsertDocsize(&rc, p, aSzIns);
  140350. }
  140351. nChng++;
  140352. }
  140353. if( p->bFts4 ){
  140354. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  140355. }
  140356. update_out:
  140357. sqlite3_free(aSzDel);
  140358. sqlite3Fts3SegmentsClose(p);
  140359. return rc;
  140360. }
  140361. /*
  140362. ** Flush any data in the pending-terms hash table to disk. If successful,
  140363. ** merge all segments in the database (including the new segment, if
  140364. ** there was any data to flush) into a single segment.
  140365. */
  140366. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  140367. int rc;
  140368. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  140369. if( rc==SQLITE_OK ){
  140370. rc = fts3DoOptimize(p, 1);
  140371. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  140372. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  140373. if( rc2!=SQLITE_OK ) rc = rc2;
  140374. }else{
  140375. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  140376. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  140377. }
  140378. }
  140379. sqlite3Fts3SegmentsClose(p);
  140380. return rc;
  140381. }
  140382. #endif
  140383. /************** End of fts3_write.c ******************************************/
  140384. /************** Begin file fts3_snippet.c ************************************/
  140385. /*
  140386. ** 2009 Oct 23
  140387. **
  140388. ** The author disclaims copyright to this source code. In place of
  140389. ** a legal notice, here is a blessing:
  140390. **
  140391. ** May you do good and not evil.
  140392. ** May you find forgiveness for yourself and forgive others.
  140393. ** May you share freely, never taking more than you give.
  140394. **
  140395. ******************************************************************************
  140396. */
  140397. /* #include "fts3Int.h" */
  140398. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  140399. /* #include <string.h> */
  140400. /* #include <assert.h> */
  140401. /*
  140402. ** Characters that may appear in the second argument to matchinfo().
  140403. */
  140404. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  140405. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  140406. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  140407. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  140408. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  140409. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  140410. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  140411. #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
  140412. #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
  140413. /*
  140414. ** The default value for the second argument to matchinfo().
  140415. */
  140416. #define FTS3_MATCHINFO_DEFAULT "pcx"
  140417. /*
  140418. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  140419. ** Fts3Expr.aDoclist[]/nDoclist.
  140420. */
  140421. typedef struct LoadDoclistCtx LoadDoclistCtx;
  140422. struct LoadDoclistCtx {
  140423. Fts3Cursor *pCsr; /* FTS3 Cursor */
  140424. int nPhrase; /* Number of phrases seen so far */
  140425. int nToken; /* Number of tokens seen so far */
  140426. };
  140427. /*
  140428. ** The following types are used as part of the implementation of the
  140429. ** fts3BestSnippet() routine.
  140430. */
  140431. typedef struct SnippetIter SnippetIter;
  140432. typedef struct SnippetPhrase SnippetPhrase;
  140433. typedef struct SnippetFragment SnippetFragment;
  140434. struct SnippetIter {
  140435. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  140436. int iCol; /* Extract snippet from this column */
  140437. int nSnippet; /* Requested snippet length (in tokens) */
  140438. int nPhrase; /* Number of phrases in query */
  140439. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  140440. int iCurrent; /* First token of current snippet */
  140441. };
  140442. struct SnippetPhrase {
  140443. int nToken; /* Number of tokens in phrase */
  140444. char *pList; /* Pointer to start of phrase position list */
  140445. int iHead; /* Next value in position list */
  140446. char *pHead; /* Position list data following iHead */
  140447. int iTail; /* Next value in trailing position list */
  140448. char *pTail; /* Position list data following iTail */
  140449. };
  140450. struct SnippetFragment {
  140451. int iCol; /* Column snippet is extracted from */
  140452. int iPos; /* Index of first token in snippet */
  140453. u64 covered; /* Mask of query phrases covered */
  140454. u64 hlmask; /* Mask of snippet terms to highlight */
  140455. };
  140456. /*
  140457. ** This type is used as an fts3ExprIterate() context object while
  140458. ** accumulating the data returned by the matchinfo() function.
  140459. */
  140460. typedef struct MatchInfo MatchInfo;
  140461. struct MatchInfo {
  140462. Fts3Cursor *pCursor; /* FTS3 Cursor */
  140463. int nCol; /* Number of columns in table */
  140464. int nPhrase; /* Number of matchable phrases in query */
  140465. sqlite3_int64 nDoc; /* Number of docs in database */
  140466. char flag;
  140467. u32 *aMatchinfo; /* Pre-allocated buffer */
  140468. };
  140469. /*
  140470. ** An instance of this structure is used to manage a pair of buffers, each
  140471. ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
  140472. ** for details.
  140473. */
  140474. struct MatchinfoBuffer {
  140475. u8 aRef[3];
  140476. int nElem;
  140477. int bGlobal; /* Set if global data is loaded */
  140478. char *zMatchinfo;
  140479. u32 aMatchinfo[1];
  140480. };
  140481. /*
  140482. ** The snippet() and offsets() functions both return text values. An instance
  140483. ** of the following structure is used to accumulate those values while the
  140484. ** functions are running. See fts3StringAppend() for details.
  140485. */
  140486. typedef struct StrBuffer StrBuffer;
  140487. struct StrBuffer {
  140488. char *z; /* Pointer to buffer containing string */
  140489. int n; /* Length of z in bytes (excl. nul-term) */
  140490. int nAlloc; /* Allocated size of buffer z in bytes */
  140491. };
  140492. /*************************************************************************
  140493. ** Start of MatchinfoBuffer code.
  140494. */
  140495. /*
  140496. ** Allocate a two-slot MatchinfoBuffer object.
  140497. */
  140498. static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
  140499. MatchinfoBuffer *pRet;
  140500. int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
  140501. int nStr = (int)strlen(zMatchinfo);
  140502. pRet = sqlite3_malloc(nByte + nStr+1);
  140503. if( pRet ){
  140504. memset(pRet, 0, nByte);
  140505. pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
  140506. pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
  140507. pRet->nElem = nElem;
  140508. pRet->zMatchinfo = ((char*)pRet) + nByte;
  140509. memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
  140510. pRet->aRef[0] = 1;
  140511. }
  140512. return pRet;
  140513. }
  140514. static void fts3MIBufferFree(void *p){
  140515. MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
  140516. assert( (u32*)p==&pBuf->aMatchinfo[1]
  140517. || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
  140518. );
  140519. if( (u32*)p==&pBuf->aMatchinfo[1] ){
  140520. pBuf->aRef[1] = 0;
  140521. }else{
  140522. pBuf->aRef[2] = 0;
  140523. }
  140524. if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
  140525. sqlite3_free(pBuf);
  140526. }
  140527. }
  140528. static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
  140529. void (*xRet)(void*) = 0;
  140530. u32 *aOut = 0;
  140531. if( p->aRef[1]==0 ){
  140532. p->aRef[1] = 1;
  140533. aOut = &p->aMatchinfo[1];
  140534. xRet = fts3MIBufferFree;
  140535. }
  140536. else if( p->aRef[2]==0 ){
  140537. p->aRef[2] = 1;
  140538. aOut = &p->aMatchinfo[p->nElem+2];
  140539. xRet = fts3MIBufferFree;
  140540. }else{
  140541. aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
  140542. if( aOut ){
  140543. xRet = sqlite3_free;
  140544. if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
  140545. }
  140546. }
  140547. *paOut = aOut;
  140548. return xRet;
  140549. }
  140550. static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
  140551. p->bGlobal = 1;
  140552. memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
  140553. }
  140554. /*
  140555. ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
  140556. */
  140557. SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
  140558. if( p ){
  140559. assert( p->aRef[0]==1 );
  140560. p->aRef[0] = 0;
  140561. if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
  140562. sqlite3_free(p);
  140563. }
  140564. }
  140565. }
  140566. /*
  140567. ** End of MatchinfoBuffer code.
  140568. *************************************************************************/
  140569. /*
  140570. ** This function is used to help iterate through a position-list. A position
  140571. ** list is a list of unique integers, sorted from smallest to largest. Each
  140572. ** element of the list is represented by an FTS3 varint that takes the value
  140573. ** of the difference between the current element and the previous one plus
  140574. ** two. For example, to store the position-list:
  140575. **
  140576. ** 4 9 113
  140577. **
  140578. ** the three varints:
  140579. **
  140580. ** 6 7 106
  140581. **
  140582. ** are encoded.
  140583. **
  140584. ** When this function is called, *pp points to the start of an element of
  140585. ** the list. *piPos contains the value of the previous entry in the list.
  140586. ** After it returns, *piPos contains the value of the next element of the
  140587. ** list and *pp is advanced to the following varint.
  140588. */
  140589. static void fts3GetDeltaPosition(char **pp, int *piPos){
  140590. int iVal;
  140591. *pp += fts3GetVarint32(*pp, &iVal);
  140592. *piPos += (iVal-2);
  140593. }
  140594. /*
  140595. ** Helper function for fts3ExprIterate() (see below).
  140596. */
  140597. static int fts3ExprIterate2(
  140598. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  140599. int *piPhrase, /* Pointer to phrase counter */
  140600. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  140601. void *pCtx /* Second argument to pass to callback */
  140602. ){
  140603. int rc; /* Return code */
  140604. int eType = pExpr->eType; /* Type of expression node pExpr */
  140605. if( eType!=FTSQUERY_PHRASE ){
  140606. assert( pExpr->pLeft && pExpr->pRight );
  140607. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  140608. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  140609. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  140610. }
  140611. }else{
  140612. rc = x(pExpr, *piPhrase, pCtx);
  140613. (*piPhrase)++;
  140614. }
  140615. return rc;
  140616. }
  140617. /*
  140618. ** Iterate through all phrase nodes in an FTS3 query, except those that
  140619. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  140620. ** For each phrase node found, the supplied callback function is invoked.
  140621. **
  140622. ** If the callback function returns anything other than SQLITE_OK,
  140623. ** the iteration is abandoned and the error code returned immediately.
  140624. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  140625. ** all eligible phrase nodes.
  140626. */
  140627. static int fts3ExprIterate(
  140628. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  140629. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  140630. void *pCtx /* Second argument to pass to callback */
  140631. ){
  140632. int iPhrase = 0; /* Variable used as the phrase counter */
  140633. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  140634. }
  140635. /*
  140636. ** This is an fts3ExprIterate() callback used while loading the doclists
  140637. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  140638. ** fts3ExprLoadDoclists().
  140639. */
  140640. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  140641. int rc = SQLITE_OK;
  140642. Fts3Phrase *pPhrase = pExpr->pPhrase;
  140643. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  140644. UNUSED_PARAMETER(iPhrase);
  140645. p->nPhrase++;
  140646. p->nToken += pPhrase->nToken;
  140647. return rc;
  140648. }
  140649. /*
  140650. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  140651. ** pCsr.
  140652. **
  140653. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  140654. ** phrases in the expression (all phrases except those directly or
  140655. ** indirectly descended from the right-hand-side of a NOT operator). If
  140656. ** pnToken is not NULL, then it is set to the number of tokens in all
  140657. ** matchable phrases of the expression.
  140658. */
  140659. static int fts3ExprLoadDoclists(
  140660. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  140661. int *pnPhrase, /* OUT: Number of phrases in query */
  140662. int *pnToken /* OUT: Number of tokens in query */
  140663. ){
  140664. int rc; /* Return Code */
  140665. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  140666. sCtx.pCsr = pCsr;
  140667. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  140668. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  140669. if( pnToken ) *pnToken = sCtx.nToken;
  140670. return rc;
  140671. }
  140672. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  140673. (*(int *)ctx)++;
  140674. pExpr->iPhrase = iPhrase;
  140675. return SQLITE_OK;
  140676. }
  140677. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  140678. int nPhrase = 0;
  140679. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  140680. return nPhrase;
  140681. }
  140682. /*
  140683. ** Advance the position list iterator specified by the first two
  140684. ** arguments so that it points to the first element with a value greater
  140685. ** than or equal to parameter iNext.
  140686. */
  140687. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  140688. char *pIter = *ppIter;
  140689. if( pIter ){
  140690. int iIter = *piIter;
  140691. while( iIter<iNext ){
  140692. if( 0==(*pIter & 0xFE) ){
  140693. iIter = -1;
  140694. pIter = 0;
  140695. break;
  140696. }
  140697. fts3GetDeltaPosition(&pIter, &iIter);
  140698. }
  140699. *piIter = iIter;
  140700. *ppIter = pIter;
  140701. }
  140702. }
  140703. /*
  140704. ** Advance the snippet iterator to the next candidate snippet.
  140705. */
  140706. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  140707. int i; /* Loop counter */
  140708. if( pIter->iCurrent<0 ){
  140709. /* The SnippetIter object has just been initialized. The first snippet
  140710. ** candidate always starts at offset 0 (even if this candidate has a
  140711. ** score of 0.0).
  140712. */
  140713. pIter->iCurrent = 0;
  140714. /* Advance the 'head' iterator of each phrase to the first offset that
  140715. ** is greater than or equal to (iNext+nSnippet).
  140716. */
  140717. for(i=0; i<pIter->nPhrase; i++){
  140718. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  140719. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  140720. }
  140721. }else{
  140722. int iStart;
  140723. int iEnd = 0x7FFFFFFF;
  140724. for(i=0; i<pIter->nPhrase; i++){
  140725. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  140726. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  140727. iEnd = pPhrase->iHead;
  140728. }
  140729. }
  140730. if( iEnd==0x7FFFFFFF ){
  140731. return 1;
  140732. }
  140733. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  140734. for(i=0; i<pIter->nPhrase; i++){
  140735. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  140736. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  140737. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  140738. }
  140739. }
  140740. return 0;
  140741. }
  140742. /*
  140743. ** Retrieve information about the current candidate snippet of snippet
  140744. ** iterator pIter.
  140745. */
  140746. static void fts3SnippetDetails(
  140747. SnippetIter *pIter, /* Snippet iterator */
  140748. u64 mCovered, /* Bitmask of phrases already covered */
  140749. int *piToken, /* OUT: First token of proposed snippet */
  140750. int *piScore, /* OUT: "Score" for this snippet */
  140751. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  140752. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  140753. ){
  140754. int iStart = pIter->iCurrent; /* First token of snippet */
  140755. int iScore = 0; /* Score of this snippet */
  140756. int i; /* Loop counter */
  140757. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  140758. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  140759. for(i=0; i<pIter->nPhrase; i++){
  140760. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  140761. if( pPhrase->pTail ){
  140762. char *pCsr = pPhrase->pTail;
  140763. int iCsr = pPhrase->iTail;
  140764. while( iCsr<(iStart+pIter->nSnippet) ){
  140765. int j;
  140766. u64 mPhrase = (u64)1 << i;
  140767. u64 mPos = (u64)1 << (iCsr - iStart);
  140768. assert( iCsr>=iStart );
  140769. if( (mCover|mCovered)&mPhrase ){
  140770. iScore++;
  140771. }else{
  140772. iScore += 1000;
  140773. }
  140774. mCover |= mPhrase;
  140775. for(j=0; j<pPhrase->nToken; j++){
  140776. mHighlight |= (mPos>>j);
  140777. }
  140778. if( 0==(*pCsr & 0x0FE) ) break;
  140779. fts3GetDeltaPosition(&pCsr, &iCsr);
  140780. }
  140781. }
  140782. }
  140783. /* Set the output variables before returning. */
  140784. *piToken = iStart;
  140785. *piScore = iScore;
  140786. *pmCover = mCover;
  140787. *pmHighlight = mHighlight;
  140788. }
  140789. /*
  140790. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  140791. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  140792. */
  140793. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  140794. SnippetIter *p = (SnippetIter *)ctx;
  140795. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  140796. char *pCsr;
  140797. int rc;
  140798. pPhrase->nToken = pExpr->pPhrase->nToken;
  140799. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  140800. assert( rc==SQLITE_OK || pCsr==0 );
  140801. if( pCsr ){
  140802. int iFirst = 0;
  140803. pPhrase->pList = pCsr;
  140804. fts3GetDeltaPosition(&pCsr, &iFirst);
  140805. assert( iFirst>=0 );
  140806. pPhrase->pHead = pCsr;
  140807. pPhrase->pTail = pCsr;
  140808. pPhrase->iHead = iFirst;
  140809. pPhrase->iTail = iFirst;
  140810. }else{
  140811. assert( rc!=SQLITE_OK || (
  140812. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  140813. ));
  140814. }
  140815. return rc;
  140816. }
  140817. /*
  140818. ** Select the fragment of text consisting of nFragment contiguous tokens
  140819. ** from column iCol that represent the "best" snippet. The best snippet
  140820. ** is the snippet with the highest score, where scores are calculated
  140821. ** by adding:
  140822. **
  140823. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  140824. **
  140825. ** (b) +1000 points for the first occurrence of each matchable phrase in
  140826. ** the snippet for which the corresponding mCovered bit is not set.
  140827. **
  140828. ** The selected snippet parameters are stored in structure *pFragment before
  140829. ** returning. The score of the selected snippet is stored in *piScore
  140830. ** before returning.
  140831. */
  140832. static int fts3BestSnippet(
  140833. int nSnippet, /* Desired snippet length */
  140834. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  140835. int iCol, /* Index of column to create snippet from */
  140836. u64 mCovered, /* Mask of phrases already covered */
  140837. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  140838. SnippetFragment *pFragment, /* OUT: Best snippet found */
  140839. int *piScore /* OUT: Score of snippet pFragment */
  140840. ){
  140841. int rc; /* Return Code */
  140842. int nList; /* Number of phrases in expression */
  140843. SnippetIter sIter; /* Iterates through snippet candidates */
  140844. int nByte; /* Number of bytes of space to allocate */
  140845. int iBestScore = -1; /* Best snippet score found so far */
  140846. int i; /* Loop counter */
  140847. memset(&sIter, 0, sizeof(sIter));
  140848. /* Iterate through the phrases in the expression to count them. The same
  140849. ** callback makes sure the doclists are loaded for each phrase.
  140850. */
  140851. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  140852. if( rc!=SQLITE_OK ){
  140853. return rc;
  140854. }
  140855. /* Now that it is known how many phrases there are, allocate and zero
  140856. ** the required space using malloc().
  140857. */
  140858. nByte = sizeof(SnippetPhrase) * nList;
  140859. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  140860. if( !sIter.aPhrase ){
  140861. return SQLITE_NOMEM;
  140862. }
  140863. memset(sIter.aPhrase, 0, nByte);
  140864. /* Initialize the contents of the SnippetIter object. Then iterate through
  140865. ** the set of phrases in the expression to populate the aPhrase[] array.
  140866. */
  140867. sIter.pCsr = pCsr;
  140868. sIter.iCol = iCol;
  140869. sIter.nSnippet = nSnippet;
  140870. sIter.nPhrase = nList;
  140871. sIter.iCurrent = -1;
  140872. rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
  140873. if( rc==SQLITE_OK ){
  140874. /* Set the *pmSeen output variable. */
  140875. for(i=0; i<nList; i++){
  140876. if( sIter.aPhrase[i].pHead ){
  140877. *pmSeen |= (u64)1 << i;
  140878. }
  140879. }
  140880. /* Loop through all candidate snippets. Store the best snippet in
  140881. ** *pFragment. Store its associated 'score' in iBestScore.
  140882. */
  140883. pFragment->iCol = iCol;
  140884. while( !fts3SnippetNextCandidate(&sIter) ){
  140885. int iPos;
  140886. int iScore;
  140887. u64 mCover;
  140888. u64 mHighlite;
  140889. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
  140890. assert( iScore>=0 );
  140891. if( iScore>iBestScore ){
  140892. pFragment->iPos = iPos;
  140893. pFragment->hlmask = mHighlite;
  140894. pFragment->covered = mCover;
  140895. iBestScore = iScore;
  140896. }
  140897. }
  140898. *piScore = iBestScore;
  140899. }
  140900. sqlite3_free(sIter.aPhrase);
  140901. return rc;
  140902. }
  140903. /*
  140904. ** Append a string to the string-buffer passed as the first argument.
  140905. **
  140906. ** If nAppend is negative, then the length of the string zAppend is
  140907. ** determined using strlen().
  140908. */
  140909. static int fts3StringAppend(
  140910. StrBuffer *pStr, /* Buffer to append to */
  140911. const char *zAppend, /* Pointer to data to append to buffer */
  140912. int nAppend /* Size of zAppend in bytes (or -1) */
  140913. ){
  140914. if( nAppend<0 ){
  140915. nAppend = (int)strlen(zAppend);
  140916. }
  140917. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  140918. ** to grow the buffer until so that it is big enough to accomadate the
  140919. ** appended data.
  140920. */
  140921. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  140922. int nAlloc = pStr->nAlloc+nAppend+100;
  140923. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  140924. if( !zNew ){
  140925. return SQLITE_NOMEM;
  140926. }
  140927. pStr->z = zNew;
  140928. pStr->nAlloc = nAlloc;
  140929. }
  140930. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  140931. /* Append the data to the string buffer. */
  140932. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  140933. pStr->n += nAppend;
  140934. pStr->z[pStr->n] = '\0';
  140935. return SQLITE_OK;
  140936. }
  140937. /*
  140938. ** The fts3BestSnippet() function often selects snippets that end with a
  140939. ** query term. That is, the final term of the snippet is always a term
  140940. ** that requires highlighting. For example, if 'X' is a highlighted term
  140941. ** and '.' is a non-highlighted term, BestSnippet() may select:
  140942. **
  140943. ** ........X.....X
  140944. **
  140945. ** This function "shifts" the beginning of the snippet forward in the
  140946. ** document so that there are approximately the same number of
  140947. ** non-highlighted terms to the right of the final highlighted term as there
  140948. ** are to the left of the first highlighted term. For example, to this:
  140949. **
  140950. ** ....X.....X....
  140951. **
  140952. ** This is done as part of extracting the snippet text, not when selecting
  140953. ** the snippet. Snippet selection is done based on doclists only, so there
  140954. ** is no way for fts3BestSnippet() to know whether or not the document
  140955. ** actually contains terms that follow the final highlighted term.
  140956. */
  140957. static int fts3SnippetShift(
  140958. Fts3Table *pTab, /* FTS3 table snippet comes from */
  140959. int iLangid, /* Language id to use in tokenizing */
  140960. int nSnippet, /* Number of tokens desired for snippet */
  140961. const char *zDoc, /* Document text to extract snippet from */
  140962. int nDoc, /* Size of buffer zDoc in bytes */
  140963. int *piPos, /* IN/OUT: First token of snippet */
  140964. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  140965. ){
  140966. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  140967. if( hlmask ){
  140968. int nLeft; /* Tokens to the left of first highlight */
  140969. int nRight; /* Tokens to the right of last highlight */
  140970. int nDesired; /* Ideal number of tokens to shift forward */
  140971. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  140972. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  140973. nDesired = (nLeft-nRight)/2;
  140974. /* Ideally, the start of the snippet should be pushed forward in the
  140975. ** document nDesired tokens. This block checks if there are actually
  140976. ** nDesired tokens to the right of the snippet. If so, *piPos and
  140977. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  140978. ** right. Otherwise, the snippet is shifted by the number of tokens
  140979. ** available.
  140980. */
  140981. if( nDesired>0 ){
  140982. int nShift; /* Number of tokens to shift snippet by */
  140983. int iCurrent = 0; /* Token counter */
  140984. int rc; /* Return Code */
  140985. sqlite3_tokenizer_module *pMod;
  140986. sqlite3_tokenizer_cursor *pC;
  140987. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  140988. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  140989. ** or more tokens in zDoc/nDoc.
  140990. */
  140991. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  140992. if( rc!=SQLITE_OK ){
  140993. return rc;
  140994. }
  140995. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  140996. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  140997. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  140998. }
  140999. pMod->xClose(pC);
  141000. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  141001. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  141002. assert( nShift<=nDesired );
  141003. if( nShift>0 ){
  141004. *piPos += nShift;
  141005. *pHlmask = hlmask >> nShift;
  141006. }
  141007. }
  141008. }
  141009. return SQLITE_OK;
  141010. }
  141011. /*
  141012. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  141013. ** append it to string buffer pOut.
  141014. */
  141015. static int fts3SnippetText(
  141016. Fts3Cursor *pCsr, /* FTS3 Cursor */
  141017. SnippetFragment *pFragment, /* Snippet to extract */
  141018. int iFragment, /* Fragment number */
  141019. int isLast, /* True for final fragment in snippet */
  141020. int nSnippet, /* Number of tokens in extracted snippet */
  141021. const char *zOpen, /* String inserted before highlighted term */
  141022. const char *zClose, /* String inserted after highlighted term */
  141023. const char *zEllipsis, /* String inserted between snippets */
  141024. StrBuffer *pOut /* Write output here */
  141025. ){
  141026. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141027. int rc; /* Return code */
  141028. const char *zDoc; /* Document text to extract snippet from */
  141029. int nDoc; /* Size of zDoc in bytes */
  141030. int iCurrent = 0; /* Current token number of document */
  141031. int iEnd = 0; /* Byte offset of end of current token */
  141032. int isShiftDone = 0; /* True after snippet is shifted */
  141033. int iPos = pFragment->iPos; /* First token of snippet */
  141034. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  141035. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  141036. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  141037. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  141038. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  141039. if( zDoc==0 ){
  141040. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  141041. return SQLITE_NOMEM;
  141042. }
  141043. return SQLITE_OK;
  141044. }
  141045. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  141046. /* Open a token cursor on the document. */
  141047. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  141048. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  141049. if( rc!=SQLITE_OK ){
  141050. return rc;
  141051. }
  141052. while( rc==SQLITE_OK ){
  141053. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  141054. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  141055. int iBegin = 0; /* Offset in zDoc of start of token */
  141056. int iFin = 0; /* Offset in zDoc of end of token */
  141057. int isHighlight = 0; /* True for highlighted terms */
  141058. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  141059. ** in the FTS code the variable that the third argument to xNext points to
  141060. ** is initialized to zero before the first (*but not necessarily
  141061. ** subsequent*) call to xNext(). This is done for a particular application
  141062. ** that needs to know whether or not the tokenizer is being used for
  141063. ** snippet generation or for some other purpose.
  141064. **
  141065. ** Extreme care is required when writing code to depend on this
  141066. ** initialization. It is not a documented part of the tokenizer interface.
  141067. ** If a tokenizer is used directly by any code outside of FTS, this
  141068. ** convention might not be respected. */
  141069. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  141070. if( rc!=SQLITE_OK ){
  141071. if( rc==SQLITE_DONE ){
  141072. /* Special case - the last token of the snippet is also the last token
  141073. ** of the column. Append any punctuation that occurred between the end
  141074. ** of the previous token and the end of the document to the output.
  141075. ** Then break out of the loop. */
  141076. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  141077. }
  141078. break;
  141079. }
  141080. if( iCurrent<iPos ){ continue; }
  141081. if( !isShiftDone ){
  141082. int n = nDoc - iBegin;
  141083. rc = fts3SnippetShift(
  141084. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  141085. );
  141086. isShiftDone = 1;
  141087. /* Now that the shift has been done, check if the initial "..." are
  141088. ** required. They are required if (a) this is not the first fragment,
  141089. ** or (b) this fragment does not begin at position 0 of its column.
  141090. */
  141091. if( rc==SQLITE_OK ){
  141092. if( iPos>0 || iFragment>0 ){
  141093. rc = fts3StringAppend(pOut, zEllipsis, -1);
  141094. }else if( iBegin ){
  141095. rc = fts3StringAppend(pOut, zDoc, iBegin);
  141096. }
  141097. }
  141098. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  141099. }
  141100. if( iCurrent>=(iPos+nSnippet) ){
  141101. if( isLast ){
  141102. rc = fts3StringAppend(pOut, zEllipsis, -1);
  141103. }
  141104. break;
  141105. }
  141106. /* Set isHighlight to true if this term should be highlighted. */
  141107. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  141108. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  141109. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  141110. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  141111. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  141112. iEnd = iFin;
  141113. }
  141114. pMod->xClose(pC);
  141115. return rc;
  141116. }
  141117. /*
  141118. ** This function is used to count the entries in a column-list (a
  141119. ** delta-encoded list of term offsets within a single column of a single
  141120. ** row). When this function is called, *ppCollist should point to the
  141121. ** beginning of the first varint in the column-list (the varint that
  141122. ** contains the position of the first matching term in the column data).
  141123. ** Before returning, *ppCollist is set to point to the first byte after
  141124. ** the last varint in the column-list (either the 0x00 signifying the end
  141125. ** of the position-list, or the 0x01 that precedes the column number of
  141126. ** the next column in the position-list).
  141127. **
  141128. ** The number of elements in the column-list is returned.
  141129. */
  141130. static int fts3ColumnlistCount(char **ppCollist){
  141131. char *pEnd = *ppCollist;
  141132. char c = 0;
  141133. int nEntry = 0;
  141134. /* A column-list is terminated by either a 0x01 or 0x00. */
  141135. while( 0xFE & (*pEnd | c) ){
  141136. c = *pEnd++ & 0x80;
  141137. if( !c ) nEntry++;
  141138. }
  141139. *ppCollist = pEnd;
  141140. return nEntry;
  141141. }
  141142. /*
  141143. ** This function gathers 'y' or 'b' data for a single phrase.
  141144. */
  141145. static void fts3ExprLHits(
  141146. Fts3Expr *pExpr, /* Phrase expression node */
  141147. MatchInfo *p /* Matchinfo context */
  141148. ){
  141149. Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
  141150. int iStart;
  141151. Fts3Phrase *pPhrase = pExpr->pPhrase;
  141152. char *pIter = pPhrase->doclist.pList;
  141153. int iCol = 0;
  141154. assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
  141155. if( p->flag==FTS3_MATCHINFO_LHITS ){
  141156. iStart = pExpr->iPhrase * p->nCol;
  141157. }else{
  141158. iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
  141159. }
  141160. while( 1 ){
  141161. int nHit = fts3ColumnlistCount(&pIter);
  141162. if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
  141163. if( p->flag==FTS3_MATCHINFO_LHITS ){
  141164. p->aMatchinfo[iStart + iCol] = (u32)nHit;
  141165. }else if( nHit ){
  141166. p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
  141167. }
  141168. }
  141169. assert( *pIter==0x00 || *pIter==0x01 );
  141170. if( *pIter!=0x01 ) break;
  141171. pIter++;
  141172. pIter += fts3GetVarint32(pIter, &iCol);
  141173. }
  141174. }
  141175. /*
  141176. ** Gather the results for matchinfo directives 'y' and 'b'.
  141177. */
  141178. static void fts3ExprLHitGather(
  141179. Fts3Expr *pExpr,
  141180. MatchInfo *p
  141181. ){
  141182. assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
  141183. if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
  141184. if( pExpr->pLeft ){
  141185. fts3ExprLHitGather(pExpr->pLeft, p);
  141186. fts3ExprLHitGather(pExpr->pRight, p);
  141187. }else{
  141188. fts3ExprLHits(pExpr, p);
  141189. }
  141190. }
  141191. }
  141192. /*
  141193. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  141194. ** for a single query.
  141195. **
  141196. ** fts3ExprIterate() callback to load the 'global' elements of a
  141197. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  141198. ** of the matchinfo array that are constant for all rows returned by the
  141199. ** current query.
  141200. **
  141201. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  141202. ** function populates Matchinfo.aMatchinfo[] as follows:
  141203. **
  141204. ** for(iCol=0; iCol<nCol; iCol++){
  141205. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  141206. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  141207. ** }
  141208. **
  141209. ** where X is the number of matches for phrase iPhrase is column iCol of all
  141210. ** rows of the table. Y is the number of rows for which column iCol contains
  141211. ** at least one instance of phrase iPhrase.
  141212. **
  141213. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  141214. ** Y values are set to nDoc, where nDoc is the number of documents in the
  141215. ** file system. This is done because the full-text index doclist is required
  141216. ** to calculate these values properly, and the full-text index doclist is
  141217. ** not available for deferred tokens.
  141218. */
  141219. static int fts3ExprGlobalHitsCb(
  141220. Fts3Expr *pExpr, /* Phrase expression node */
  141221. int iPhrase, /* Phrase number (numbered from zero) */
  141222. void *pCtx /* Pointer to MatchInfo structure */
  141223. ){
  141224. MatchInfo *p = (MatchInfo *)pCtx;
  141225. return sqlite3Fts3EvalPhraseStats(
  141226. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  141227. );
  141228. }
  141229. /*
  141230. ** fts3ExprIterate() callback used to collect the "local" part of the
  141231. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  141232. ** array that are different for each row returned by the query.
  141233. */
  141234. static int fts3ExprLocalHitsCb(
  141235. Fts3Expr *pExpr, /* Phrase expression node */
  141236. int iPhrase, /* Phrase number */
  141237. void *pCtx /* Pointer to MatchInfo structure */
  141238. ){
  141239. int rc = SQLITE_OK;
  141240. MatchInfo *p = (MatchInfo *)pCtx;
  141241. int iStart = iPhrase * p->nCol * 3;
  141242. int i;
  141243. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  141244. char *pCsr;
  141245. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  141246. if( pCsr ){
  141247. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  141248. }else{
  141249. p->aMatchinfo[iStart+i*3] = 0;
  141250. }
  141251. }
  141252. return rc;
  141253. }
  141254. static int fts3MatchinfoCheck(
  141255. Fts3Table *pTab,
  141256. char cArg,
  141257. char **pzErr
  141258. ){
  141259. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  141260. || (cArg==FTS3_MATCHINFO_NCOL)
  141261. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  141262. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  141263. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  141264. || (cArg==FTS3_MATCHINFO_LCS)
  141265. || (cArg==FTS3_MATCHINFO_HITS)
  141266. || (cArg==FTS3_MATCHINFO_LHITS)
  141267. || (cArg==FTS3_MATCHINFO_LHITS_BM)
  141268. ){
  141269. return SQLITE_OK;
  141270. }
  141271. sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
  141272. return SQLITE_ERROR;
  141273. }
  141274. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  141275. int nVal; /* Number of integers output by cArg */
  141276. switch( cArg ){
  141277. case FTS3_MATCHINFO_NDOC:
  141278. case FTS3_MATCHINFO_NPHRASE:
  141279. case FTS3_MATCHINFO_NCOL:
  141280. nVal = 1;
  141281. break;
  141282. case FTS3_MATCHINFO_AVGLENGTH:
  141283. case FTS3_MATCHINFO_LENGTH:
  141284. case FTS3_MATCHINFO_LCS:
  141285. nVal = pInfo->nCol;
  141286. break;
  141287. case FTS3_MATCHINFO_LHITS:
  141288. nVal = pInfo->nCol * pInfo->nPhrase;
  141289. break;
  141290. case FTS3_MATCHINFO_LHITS_BM:
  141291. nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
  141292. break;
  141293. default:
  141294. assert( cArg==FTS3_MATCHINFO_HITS );
  141295. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  141296. break;
  141297. }
  141298. return nVal;
  141299. }
  141300. static int fts3MatchinfoSelectDoctotal(
  141301. Fts3Table *pTab,
  141302. sqlite3_stmt **ppStmt,
  141303. sqlite3_int64 *pnDoc,
  141304. const char **paLen
  141305. ){
  141306. sqlite3_stmt *pStmt;
  141307. const char *a;
  141308. sqlite3_int64 nDoc;
  141309. if( !*ppStmt ){
  141310. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  141311. if( rc!=SQLITE_OK ) return rc;
  141312. }
  141313. pStmt = *ppStmt;
  141314. assert( sqlite3_data_count(pStmt)==1 );
  141315. a = sqlite3_column_blob(pStmt, 0);
  141316. a += sqlite3Fts3GetVarint(a, &nDoc);
  141317. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  141318. *pnDoc = (u32)nDoc;
  141319. if( paLen ) *paLen = a;
  141320. return SQLITE_OK;
  141321. }
  141322. /*
  141323. ** An instance of the following structure is used to store state while
  141324. ** iterating through a multi-column position-list corresponding to the
  141325. ** hits for a single phrase on a single row in order to calculate the
  141326. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  141327. */
  141328. typedef struct LcsIterator LcsIterator;
  141329. struct LcsIterator {
  141330. Fts3Expr *pExpr; /* Pointer to phrase expression */
  141331. int iPosOffset; /* Tokens count up to end of this phrase */
  141332. char *pRead; /* Cursor used to iterate through aDoclist */
  141333. int iPos; /* Current position */
  141334. };
  141335. /*
  141336. ** If LcsIterator.iCol is set to the following value, the iterator has
  141337. ** finished iterating through all offsets for all columns.
  141338. */
  141339. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  141340. static int fts3MatchinfoLcsCb(
  141341. Fts3Expr *pExpr, /* Phrase expression node */
  141342. int iPhrase, /* Phrase number (numbered from zero) */
  141343. void *pCtx /* Pointer to MatchInfo structure */
  141344. ){
  141345. LcsIterator *aIter = (LcsIterator *)pCtx;
  141346. aIter[iPhrase].pExpr = pExpr;
  141347. return SQLITE_OK;
  141348. }
  141349. /*
  141350. ** Advance the iterator passed as an argument to the next position. Return
  141351. ** 1 if the iterator is at EOF or if it now points to the start of the
  141352. ** position list for the next column.
  141353. */
  141354. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  141355. char *pRead = pIter->pRead;
  141356. sqlite3_int64 iRead;
  141357. int rc = 0;
  141358. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  141359. if( iRead==0 || iRead==1 ){
  141360. pRead = 0;
  141361. rc = 1;
  141362. }else{
  141363. pIter->iPos += (int)(iRead-2);
  141364. }
  141365. pIter->pRead = pRead;
  141366. return rc;
  141367. }
  141368. /*
  141369. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  141370. **
  141371. ** If the call is successful, the longest-common-substring lengths for each
  141372. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  141373. ** array before returning. SQLITE_OK is returned in this case.
  141374. **
  141375. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  141376. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  141377. ** undefined.
  141378. */
  141379. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  141380. LcsIterator *aIter;
  141381. int i;
  141382. int iCol;
  141383. int nToken = 0;
  141384. /* Allocate and populate the array of LcsIterator objects. The array
  141385. ** contains one element for each matchable phrase in the query.
  141386. **/
  141387. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  141388. if( !aIter ) return SQLITE_NOMEM;
  141389. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  141390. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  141391. for(i=0; i<pInfo->nPhrase; i++){
  141392. LcsIterator *pIter = &aIter[i];
  141393. nToken -= pIter->pExpr->pPhrase->nToken;
  141394. pIter->iPosOffset = nToken;
  141395. }
  141396. for(iCol=0; iCol<pInfo->nCol; iCol++){
  141397. int nLcs = 0; /* LCS value for this column */
  141398. int nLive = 0; /* Number of iterators in aIter not at EOF */
  141399. for(i=0; i<pInfo->nPhrase; i++){
  141400. int rc;
  141401. LcsIterator *pIt = &aIter[i];
  141402. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  141403. if( rc!=SQLITE_OK ) return rc;
  141404. if( pIt->pRead ){
  141405. pIt->iPos = pIt->iPosOffset;
  141406. fts3LcsIteratorAdvance(&aIter[i]);
  141407. nLive++;
  141408. }
  141409. }
  141410. while( nLive>0 ){
  141411. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  141412. int nThisLcs = 0; /* LCS for the current iterator positions */
  141413. for(i=0; i<pInfo->nPhrase; i++){
  141414. LcsIterator *pIter = &aIter[i];
  141415. if( pIter->pRead==0 ){
  141416. /* This iterator is already at EOF for this column. */
  141417. nThisLcs = 0;
  141418. }else{
  141419. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  141420. pAdv = pIter;
  141421. }
  141422. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  141423. nThisLcs++;
  141424. }else{
  141425. nThisLcs = 1;
  141426. }
  141427. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  141428. }
  141429. }
  141430. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  141431. }
  141432. pInfo->aMatchinfo[iCol] = nLcs;
  141433. }
  141434. sqlite3_free(aIter);
  141435. return SQLITE_OK;
  141436. }
  141437. /*
  141438. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  141439. ** be returned by the matchinfo() function. Argument zArg contains the
  141440. ** format string passed as the second argument to matchinfo (or the
  141441. ** default value "pcx" if no second argument was specified). The format
  141442. ** string has already been validated and the pInfo->aMatchinfo[] array
  141443. ** is guaranteed to be large enough for the output.
  141444. **
  141445. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  141446. ** If it is false, then assume that those fields that do not change between
  141447. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  141448. ** have already been populated.
  141449. **
  141450. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  141451. ** occurs. If a value other than SQLITE_OK is returned, the state the
  141452. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  141453. */
  141454. static int fts3MatchinfoValues(
  141455. Fts3Cursor *pCsr, /* FTS3 cursor object */
  141456. int bGlobal, /* True to grab the global stats */
  141457. MatchInfo *pInfo, /* Matchinfo context object */
  141458. const char *zArg /* Matchinfo format string */
  141459. ){
  141460. int rc = SQLITE_OK;
  141461. int i;
  141462. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141463. sqlite3_stmt *pSelect = 0;
  141464. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  141465. pInfo->flag = zArg[i];
  141466. switch( zArg[i] ){
  141467. case FTS3_MATCHINFO_NPHRASE:
  141468. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  141469. break;
  141470. case FTS3_MATCHINFO_NCOL:
  141471. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  141472. break;
  141473. case FTS3_MATCHINFO_NDOC:
  141474. if( bGlobal ){
  141475. sqlite3_int64 nDoc = 0;
  141476. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  141477. pInfo->aMatchinfo[0] = (u32)nDoc;
  141478. }
  141479. break;
  141480. case FTS3_MATCHINFO_AVGLENGTH:
  141481. if( bGlobal ){
  141482. sqlite3_int64 nDoc; /* Number of rows in table */
  141483. const char *a; /* Aggregate column length array */
  141484. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  141485. if( rc==SQLITE_OK ){
  141486. int iCol;
  141487. for(iCol=0; iCol<pInfo->nCol; iCol++){
  141488. u32 iVal;
  141489. sqlite3_int64 nToken;
  141490. a += sqlite3Fts3GetVarint(a, &nToken);
  141491. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  141492. pInfo->aMatchinfo[iCol] = iVal;
  141493. }
  141494. }
  141495. }
  141496. break;
  141497. case FTS3_MATCHINFO_LENGTH: {
  141498. sqlite3_stmt *pSelectDocsize = 0;
  141499. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  141500. if( rc==SQLITE_OK ){
  141501. int iCol;
  141502. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  141503. for(iCol=0; iCol<pInfo->nCol; iCol++){
  141504. sqlite3_int64 nToken;
  141505. a += sqlite3Fts3GetVarint(a, &nToken);
  141506. pInfo->aMatchinfo[iCol] = (u32)nToken;
  141507. }
  141508. }
  141509. sqlite3_reset(pSelectDocsize);
  141510. break;
  141511. }
  141512. case FTS3_MATCHINFO_LCS:
  141513. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  141514. if( rc==SQLITE_OK ){
  141515. rc = fts3MatchinfoLcs(pCsr, pInfo);
  141516. }
  141517. break;
  141518. case FTS3_MATCHINFO_LHITS_BM:
  141519. case FTS3_MATCHINFO_LHITS: {
  141520. int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
  141521. memset(pInfo->aMatchinfo, 0, nZero);
  141522. fts3ExprLHitGather(pCsr->pExpr, pInfo);
  141523. break;
  141524. }
  141525. default: {
  141526. Fts3Expr *pExpr;
  141527. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  141528. pExpr = pCsr->pExpr;
  141529. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  141530. if( rc!=SQLITE_OK ) break;
  141531. if( bGlobal ){
  141532. if( pCsr->pDeferred ){
  141533. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  141534. if( rc!=SQLITE_OK ) break;
  141535. }
  141536. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  141537. sqlite3Fts3EvalTestDeferred(pCsr, &rc);
  141538. if( rc!=SQLITE_OK ) break;
  141539. }
  141540. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  141541. break;
  141542. }
  141543. }
  141544. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  141545. }
  141546. sqlite3_reset(pSelect);
  141547. return rc;
  141548. }
  141549. /*
  141550. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  141551. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  141552. */
  141553. static void fts3GetMatchinfo(
  141554. sqlite3_context *pCtx, /* Return results here */
  141555. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  141556. const char *zArg /* Second argument to matchinfo() function */
  141557. ){
  141558. MatchInfo sInfo;
  141559. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141560. int rc = SQLITE_OK;
  141561. int bGlobal = 0; /* Collect 'global' stats as well as local */
  141562. u32 *aOut = 0;
  141563. void (*xDestroyOut)(void*) = 0;
  141564. memset(&sInfo, 0, sizeof(MatchInfo));
  141565. sInfo.pCursor = pCsr;
  141566. sInfo.nCol = pTab->nColumn;
  141567. /* If there is cached matchinfo() data, but the format string for the
  141568. ** cache does not match the format string for this request, discard
  141569. ** the cached data. */
  141570. if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
  141571. sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
  141572. pCsr->pMIBuffer = 0;
  141573. }
  141574. /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
  141575. ** matchinfo function has been called for this query. In this case
  141576. ** allocate the array used to accumulate the matchinfo data and
  141577. ** initialize those elements that are constant for every row.
  141578. */
  141579. if( pCsr->pMIBuffer==0 ){
  141580. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  141581. int i; /* Used to iterate through zArg */
  141582. /* Determine the number of phrases in the query */
  141583. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  141584. sInfo.nPhrase = pCsr->nPhrase;
  141585. /* Determine the number of integers in the buffer returned by this call. */
  141586. for(i=0; zArg[i]; i++){
  141587. char *zErr = 0;
  141588. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  141589. sqlite3_result_error(pCtx, zErr, -1);
  141590. sqlite3_free(zErr);
  141591. return;
  141592. }
  141593. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  141594. }
  141595. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  141596. pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
  141597. if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
  141598. pCsr->isMatchinfoNeeded = 1;
  141599. bGlobal = 1;
  141600. }
  141601. if( rc==SQLITE_OK ){
  141602. xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
  141603. if( xDestroyOut==0 ){
  141604. rc = SQLITE_NOMEM;
  141605. }
  141606. }
  141607. if( rc==SQLITE_OK ){
  141608. sInfo.aMatchinfo = aOut;
  141609. sInfo.nPhrase = pCsr->nPhrase;
  141610. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  141611. if( bGlobal ){
  141612. fts3MIBufferSetGlobal(pCsr->pMIBuffer);
  141613. }
  141614. }
  141615. if( rc!=SQLITE_OK ){
  141616. sqlite3_result_error_code(pCtx, rc);
  141617. if( xDestroyOut ) xDestroyOut(aOut);
  141618. }else{
  141619. int n = pCsr->pMIBuffer->nElem * sizeof(u32);
  141620. sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
  141621. }
  141622. }
  141623. /*
  141624. ** Implementation of snippet() function.
  141625. */
  141626. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  141627. sqlite3_context *pCtx, /* SQLite function call context */
  141628. Fts3Cursor *pCsr, /* Cursor object */
  141629. const char *zStart, /* Snippet start text - "<b>" */
  141630. const char *zEnd, /* Snippet end text - "</b>" */
  141631. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  141632. int iCol, /* Extract snippet from this column */
  141633. int nToken /* Approximate number of tokens in snippet */
  141634. ){
  141635. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141636. int rc = SQLITE_OK;
  141637. int i;
  141638. StrBuffer res = {0, 0, 0};
  141639. /* The returned text includes up to four fragments of text extracted from
  141640. ** the data in the current row. The first iteration of the for(...) loop
  141641. ** below attempts to locate a single fragment of text nToken tokens in
  141642. ** size that contains at least one instance of all phrases in the query
  141643. ** expression that appear in the current row. If such a fragment of text
  141644. ** cannot be found, the second iteration of the loop attempts to locate
  141645. ** a pair of fragments, and so on.
  141646. */
  141647. int nSnippet = 0; /* Number of fragments in this snippet */
  141648. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  141649. int nFToken = -1; /* Number of tokens in each fragment */
  141650. if( !pCsr->pExpr ){
  141651. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  141652. return;
  141653. }
  141654. for(nSnippet=1; 1; nSnippet++){
  141655. int iSnip; /* Loop counter 0..nSnippet-1 */
  141656. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  141657. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  141658. if( nToken>=0 ){
  141659. nFToken = (nToken+nSnippet-1) / nSnippet;
  141660. }else{
  141661. nFToken = -1 * nToken;
  141662. }
  141663. for(iSnip=0; iSnip<nSnippet; iSnip++){
  141664. int iBestScore = -1; /* Best score of columns checked so far */
  141665. int iRead; /* Used to iterate through columns */
  141666. SnippetFragment *pFragment = &aSnippet[iSnip];
  141667. memset(pFragment, 0, sizeof(*pFragment));
  141668. /* Loop through all columns of the table being considered for snippets.
  141669. ** If the iCol argument to this function was negative, this means all
  141670. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  141671. */
  141672. for(iRead=0; iRead<pTab->nColumn; iRead++){
  141673. SnippetFragment sF = {0, 0, 0, 0};
  141674. int iS = 0;
  141675. if( iCol>=0 && iRead!=iCol ) continue;
  141676. /* Find the best snippet of nFToken tokens in column iRead. */
  141677. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  141678. if( rc!=SQLITE_OK ){
  141679. goto snippet_out;
  141680. }
  141681. if( iS>iBestScore ){
  141682. *pFragment = sF;
  141683. iBestScore = iS;
  141684. }
  141685. }
  141686. mCovered |= pFragment->covered;
  141687. }
  141688. /* If all query phrases seen by fts3BestSnippet() are present in at least
  141689. ** one of the nSnippet snippet fragments, break out of the loop.
  141690. */
  141691. assert( (mCovered&mSeen)==mCovered );
  141692. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  141693. }
  141694. assert( nFToken>0 );
  141695. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  141696. rc = fts3SnippetText(pCsr, &aSnippet[i],
  141697. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  141698. );
  141699. }
  141700. snippet_out:
  141701. sqlite3Fts3SegmentsClose(pTab);
  141702. if( rc!=SQLITE_OK ){
  141703. sqlite3_result_error_code(pCtx, rc);
  141704. sqlite3_free(res.z);
  141705. }else{
  141706. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  141707. }
  141708. }
  141709. typedef struct TermOffset TermOffset;
  141710. typedef struct TermOffsetCtx TermOffsetCtx;
  141711. struct TermOffset {
  141712. char *pList; /* Position-list */
  141713. int iPos; /* Position just read from pList */
  141714. int iOff; /* Offset of this term from read positions */
  141715. };
  141716. struct TermOffsetCtx {
  141717. Fts3Cursor *pCsr;
  141718. int iCol; /* Column of table to populate aTerm for */
  141719. int iTerm;
  141720. sqlite3_int64 iDocid;
  141721. TermOffset *aTerm;
  141722. };
  141723. /*
  141724. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  141725. */
  141726. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  141727. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  141728. int nTerm; /* Number of tokens in phrase */
  141729. int iTerm; /* For looping through nTerm phrase terms */
  141730. char *pList; /* Pointer to position list for phrase */
  141731. int iPos = 0; /* First position in position-list */
  141732. int rc;
  141733. UNUSED_PARAMETER(iPhrase);
  141734. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  141735. nTerm = pExpr->pPhrase->nToken;
  141736. if( pList ){
  141737. fts3GetDeltaPosition(&pList, &iPos);
  141738. assert( iPos>=0 );
  141739. }
  141740. for(iTerm=0; iTerm<nTerm; iTerm++){
  141741. TermOffset *pT = &p->aTerm[p->iTerm++];
  141742. pT->iOff = nTerm-iTerm-1;
  141743. pT->pList = pList;
  141744. pT->iPos = iPos;
  141745. }
  141746. return rc;
  141747. }
  141748. /*
  141749. ** Implementation of offsets() function.
  141750. */
  141751. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  141752. sqlite3_context *pCtx, /* SQLite function call context */
  141753. Fts3Cursor *pCsr /* Cursor object */
  141754. ){
  141755. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141756. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  141757. int rc; /* Return Code */
  141758. int nToken; /* Number of tokens in query */
  141759. int iCol; /* Column currently being processed */
  141760. StrBuffer res = {0, 0, 0}; /* Result string */
  141761. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  141762. if( !pCsr->pExpr ){
  141763. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  141764. return;
  141765. }
  141766. memset(&sCtx, 0, sizeof(sCtx));
  141767. assert( pCsr->isRequireSeek==0 );
  141768. /* Count the number of terms in the query */
  141769. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  141770. if( rc!=SQLITE_OK ) goto offsets_out;
  141771. /* Allocate the array of TermOffset iterators. */
  141772. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  141773. if( 0==sCtx.aTerm ){
  141774. rc = SQLITE_NOMEM;
  141775. goto offsets_out;
  141776. }
  141777. sCtx.iDocid = pCsr->iPrevId;
  141778. sCtx.pCsr = pCsr;
  141779. /* Loop through the table columns, appending offset information to
  141780. ** string-buffer res for each column.
  141781. */
  141782. for(iCol=0; iCol<pTab->nColumn; iCol++){
  141783. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  141784. const char *ZDUMMY; /* Dummy argument used with xNext() */
  141785. int NDUMMY = 0; /* Dummy argument used with xNext() */
  141786. int iStart = 0;
  141787. int iEnd = 0;
  141788. int iCurrent = 0;
  141789. const char *zDoc;
  141790. int nDoc;
  141791. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  141792. ** no way that this operation can fail, so the return code from
  141793. ** fts3ExprIterate() can be discarded.
  141794. */
  141795. sCtx.iCol = iCol;
  141796. sCtx.iTerm = 0;
  141797. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
  141798. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  141799. ** in column iCol, jump immediately to the next iteration of the loop.
  141800. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  141801. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  141802. ** to the caller.
  141803. */
  141804. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  141805. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  141806. if( zDoc==0 ){
  141807. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  141808. continue;
  141809. }
  141810. rc = SQLITE_NOMEM;
  141811. goto offsets_out;
  141812. }
  141813. /* Initialize a tokenizer iterator to iterate through column iCol. */
  141814. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  141815. zDoc, nDoc, &pC
  141816. );
  141817. if( rc!=SQLITE_OK ) goto offsets_out;
  141818. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  141819. while( rc==SQLITE_OK ){
  141820. int i; /* Used to loop through terms */
  141821. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  141822. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  141823. for(i=0; i<nToken; i++){
  141824. TermOffset *pT = &sCtx.aTerm[i];
  141825. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  141826. iMinPos = pT->iPos-pT->iOff;
  141827. pTerm = pT;
  141828. }
  141829. }
  141830. if( !pTerm ){
  141831. /* All offsets for this column have been gathered. */
  141832. rc = SQLITE_DONE;
  141833. }else{
  141834. assert( iCurrent<=iMinPos );
  141835. if( 0==(0xFE&*pTerm->pList) ){
  141836. pTerm->pList = 0;
  141837. }else{
  141838. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  141839. }
  141840. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  141841. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  141842. }
  141843. if( rc==SQLITE_OK ){
  141844. char aBuffer[64];
  141845. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  141846. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  141847. );
  141848. rc = fts3StringAppend(&res, aBuffer, -1);
  141849. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  141850. rc = FTS_CORRUPT_VTAB;
  141851. }
  141852. }
  141853. }
  141854. if( rc==SQLITE_DONE ){
  141855. rc = SQLITE_OK;
  141856. }
  141857. pMod->xClose(pC);
  141858. if( rc!=SQLITE_OK ) goto offsets_out;
  141859. }
  141860. offsets_out:
  141861. sqlite3_free(sCtx.aTerm);
  141862. assert( rc!=SQLITE_DONE );
  141863. sqlite3Fts3SegmentsClose(pTab);
  141864. if( rc!=SQLITE_OK ){
  141865. sqlite3_result_error_code(pCtx, rc);
  141866. sqlite3_free(res.z);
  141867. }else{
  141868. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  141869. }
  141870. return;
  141871. }
  141872. /*
  141873. ** Implementation of matchinfo() function.
  141874. */
  141875. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  141876. sqlite3_context *pContext, /* Function call context */
  141877. Fts3Cursor *pCsr, /* FTS3 table cursor */
  141878. const char *zArg /* Second arg to matchinfo() function */
  141879. ){
  141880. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  141881. const char *zFormat;
  141882. if( zArg ){
  141883. zFormat = zArg;
  141884. }else{
  141885. zFormat = FTS3_MATCHINFO_DEFAULT;
  141886. }
  141887. if( !pCsr->pExpr ){
  141888. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  141889. return;
  141890. }else{
  141891. /* Retrieve matchinfo() data. */
  141892. fts3GetMatchinfo(pContext, pCsr, zFormat);
  141893. sqlite3Fts3SegmentsClose(pTab);
  141894. }
  141895. }
  141896. #endif
  141897. /************** End of fts3_snippet.c ****************************************/
  141898. /************** Begin file fts3_unicode.c ************************************/
  141899. /*
  141900. ** 2012 May 24
  141901. **
  141902. ** The author disclaims copyright to this source code. In place of
  141903. ** a legal notice, here is a blessing:
  141904. **
  141905. ** May you do good and not evil.
  141906. ** May you find forgiveness for yourself and forgive others.
  141907. ** May you share freely, never taking more than you give.
  141908. **
  141909. ******************************************************************************
  141910. **
  141911. ** Implementation of the "unicode" full-text-search tokenizer.
  141912. */
  141913. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  141914. /* #include "fts3Int.h" */
  141915. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  141916. /* #include <assert.h> */
  141917. /* #include <stdlib.h> */
  141918. /* #include <stdio.h> */
  141919. /* #include <string.h> */
  141920. /* #include "fts3_tokenizer.h" */
  141921. /*
  141922. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  141923. ** from the sqlite3 source file utf.c. If this file is compiled as part
  141924. ** of the amalgamation, they are not required.
  141925. */
  141926. #ifndef SQLITE_AMALGAMATION
  141927. static const unsigned char sqlite3Utf8Trans1[] = {
  141928. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  141929. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  141930. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  141931. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  141932. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  141933. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  141934. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  141935. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  141936. };
  141937. #define READ_UTF8(zIn, zTerm, c) \
  141938. c = *(zIn++); \
  141939. if( c>=0xc0 ){ \
  141940. c = sqlite3Utf8Trans1[c-0xc0]; \
  141941. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  141942. c = (c<<6) + (0x3f & *(zIn++)); \
  141943. } \
  141944. if( c<0x80 \
  141945. || (c&0xFFFFF800)==0xD800 \
  141946. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  141947. }
  141948. #define WRITE_UTF8(zOut, c) { \
  141949. if( c<0x00080 ){ \
  141950. *zOut++ = (u8)(c&0xFF); \
  141951. } \
  141952. else if( c<0x00800 ){ \
  141953. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  141954. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  141955. } \
  141956. else if( c<0x10000 ){ \
  141957. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  141958. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  141959. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  141960. }else{ \
  141961. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  141962. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  141963. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  141964. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  141965. } \
  141966. }
  141967. #endif /* ifndef SQLITE_AMALGAMATION */
  141968. typedef struct unicode_tokenizer unicode_tokenizer;
  141969. typedef struct unicode_cursor unicode_cursor;
  141970. struct unicode_tokenizer {
  141971. sqlite3_tokenizer base;
  141972. int bRemoveDiacritic;
  141973. int nException;
  141974. int *aiException;
  141975. };
  141976. struct unicode_cursor {
  141977. sqlite3_tokenizer_cursor base;
  141978. const unsigned char *aInput; /* Input text being tokenized */
  141979. int nInput; /* Size of aInput[] in bytes */
  141980. int iOff; /* Current offset within aInput[] */
  141981. int iToken; /* Index of next token to be returned */
  141982. char *zToken; /* storage for current token */
  141983. int nAlloc; /* space allocated at zToken */
  141984. };
  141985. /*
  141986. ** Destroy a tokenizer allocated by unicodeCreate().
  141987. */
  141988. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  141989. if( pTokenizer ){
  141990. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  141991. sqlite3_free(p->aiException);
  141992. sqlite3_free(p);
  141993. }
  141994. return SQLITE_OK;
  141995. }
  141996. /*
  141997. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  141998. ** statement has specified that the tokenizer for this table shall consider
  141999. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  142000. ** token characters (if bAlnum==1).
  142001. **
  142002. ** For each codepoint in the zIn/nIn string, this function checks if the
  142003. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  142004. ** If so, no action is taken. Otherwise, the codepoint is added to the
  142005. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  142006. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  142007. ** codepoints in the aiException[] array.
  142008. **
  142009. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  142010. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  142011. ** It is not possible to change the behavior of the tokenizer with respect
  142012. ** to these codepoints.
  142013. */
  142014. static int unicodeAddExceptions(
  142015. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  142016. int bAlnum, /* Replace Isalnum() return value with this */
  142017. const char *zIn, /* Array of characters to make exceptions */
  142018. int nIn /* Length of z in bytes */
  142019. ){
  142020. const unsigned char *z = (const unsigned char *)zIn;
  142021. const unsigned char *zTerm = &z[nIn];
  142022. int iCode;
  142023. int nEntry = 0;
  142024. assert( bAlnum==0 || bAlnum==1 );
  142025. while( z<zTerm ){
  142026. READ_UTF8(z, zTerm, iCode);
  142027. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  142028. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  142029. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  142030. ){
  142031. nEntry++;
  142032. }
  142033. }
  142034. if( nEntry ){
  142035. int *aNew; /* New aiException[] array */
  142036. int nNew; /* Number of valid entries in array aNew[] */
  142037. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  142038. if( aNew==0 ) return SQLITE_NOMEM;
  142039. nNew = p->nException;
  142040. z = (const unsigned char *)zIn;
  142041. while( z<zTerm ){
  142042. READ_UTF8(z, zTerm, iCode);
  142043. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  142044. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  142045. ){
  142046. int i, j;
  142047. for(i=0; i<nNew && aNew[i]<iCode; i++);
  142048. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  142049. aNew[i] = iCode;
  142050. nNew++;
  142051. }
  142052. }
  142053. p->aiException = aNew;
  142054. p->nException = nNew;
  142055. }
  142056. return SQLITE_OK;
  142057. }
  142058. /*
  142059. ** Return true if the p->aiException[] array contains the value iCode.
  142060. */
  142061. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  142062. if( p->nException>0 ){
  142063. int *a = p->aiException;
  142064. int iLo = 0;
  142065. int iHi = p->nException-1;
  142066. while( iHi>=iLo ){
  142067. int iTest = (iHi + iLo) / 2;
  142068. if( iCode==a[iTest] ){
  142069. return 1;
  142070. }else if( iCode>a[iTest] ){
  142071. iLo = iTest+1;
  142072. }else{
  142073. iHi = iTest-1;
  142074. }
  142075. }
  142076. }
  142077. return 0;
  142078. }
  142079. /*
  142080. ** Return true if, for the purposes of tokenization, codepoint iCode is
  142081. ** considered a token character (not a separator).
  142082. */
  142083. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  142084. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  142085. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  142086. }
  142087. /*
  142088. ** Create a new tokenizer instance.
  142089. */
  142090. static int unicodeCreate(
  142091. int nArg, /* Size of array argv[] */
  142092. const char * const *azArg, /* Tokenizer creation arguments */
  142093. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  142094. ){
  142095. unicode_tokenizer *pNew; /* New tokenizer object */
  142096. int i;
  142097. int rc = SQLITE_OK;
  142098. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  142099. if( pNew==NULL ) return SQLITE_NOMEM;
  142100. memset(pNew, 0, sizeof(unicode_tokenizer));
  142101. pNew->bRemoveDiacritic = 1;
  142102. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  142103. const char *z = azArg[i];
  142104. int n = (int)strlen(z);
  142105. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  142106. pNew->bRemoveDiacritic = 1;
  142107. }
  142108. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  142109. pNew->bRemoveDiacritic = 0;
  142110. }
  142111. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  142112. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  142113. }
  142114. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  142115. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  142116. }
  142117. else{
  142118. /* Unrecognized argument */
  142119. rc = SQLITE_ERROR;
  142120. }
  142121. }
  142122. if( rc!=SQLITE_OK ){
  142123. unicodeDestroy((sqlite3_tokenizer *)pNew);
  142124. pNew = 0;
  142125. }
  142126. *pp = (sqlite3_tokenizer *)pNew;
  142127. return rc;
  142128. }
  142129. /*
  142130. ** Prepare to begin tokenizing a particular string. The input
  142131. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  142132. ** used to incrementally tokenize this string is returned in
  142133. ** *ppCursor.
  142134. */
  142135. static int unicodeOpen(
  142136. sqlite3_tokenizer *p, /* The tokenizer */
  142137. const char *aInput, /* Input string */
  142138. int nInput, /* Size of string aInput in bytes */
  142139. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  142140. ){
  142141. unicode_cursor *pCsr;
  142142. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  142143. if( pCsr==0 ){
  142144. return SQLITE_NOMEM;
  142145. }
  142146. memset(pCsr, 0, sizeof(unicode_cursor));
  142147. pCsr->aInput = (const unsigned char *)aInput;
  142148. if( aInput==0 ){
  142149. pCsr->nInput = 0;
  142150. }else if( nInput<0 ){
  142151. pCsr->nInput = (int)strlen(aInput);
  142152. }else{
  142153. pCsr->nInput = nInput;
  142154. }
  142155. *pp = &pCsr->base;
  142156. UNUSED_PARAMETER(p);
  142157. return SQLITE_OK;
  142158. }
  142159. /*
  142160. ** Close a tokenization cursor previously opened by a call to
  142161. ** simpleOpen() above.
  142162. */
  142163. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  142164. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  142165. sqlite3_free(pCsr->zToken);
  142166. sqlite3_free(pCsr);
  142167. return SQLITE_OK;
  142168. }
  142169. /*
  142170. ** Extract the next token from a tokenization cursor. The cursor must
  142171. ** have been opened by a prior call to simpleOpen().
  142172. */
  142173. static int unicodeNext(
  142174. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  142175. const char **paToken, /* OUT: Token text */
  142176. int *pnToken, /* OUT: Number of bytes at *paToken */
  142177. int *piStart, /* OUT: Starting offset of token */
  142178. int *piEnd, /* OUT: Ending offset of token */
  142179. int *piPos /* OUT: Position integer of token */
  142180. ){
  142181. unicode_cursor *pCsr = (unicode_cursor *)pC;
  142182. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  142183. int iCode = 0;
  142184. char *zOut;
  142185. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  142186. const unsigned char *zStart = z;
  142187. const unsigned char *zEnd;
  142188. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  142189. /* Scan past any delimiter characters before the start of the next token.
  142190. ** Return SQLITE_DONE early if this takes us all the way to the end of
  142191. ** the input. */
  142192. while( z<zTerm ){
  142193. READ_UTF8(z, zTerm, iCode);
  142194. if( unicodeIsAlnum(p, iCode) ) break;
  142195. zStart = z;
  142196. }
  142197. if( zStart>=zTerm ) return SQLITE_DONE;
  142198. zOut = pCsr->zToken;
  142199. do {
  142200. int iOut;
  142201. /* Grow the output buffer if required. */
  142202. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  142203. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  142204. if( !zNew ) return SQLITE_NOMEM;
  142205. zOut = &zNew[zOut - pCsr->zToken];
  142206. pCsr->zToken = zNew;
  142207. pCsr->nAlloc += 64;
  142208. }
  142209. /* Write the folded case of the last character read to the output */
  142210. zEnd = z;
  142211. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  142212. if( iOut ){
  142213. WRITE_UTF8(zOut, iOut);
  142214. }
  142215. /* If the cursor is not at EOF, read the next character */
  142216. if( z>=zTerm ) break;
  142217. READ_UTF8(z, zTerm, iCode);
  142218. }while( unicodeIsAlnum(p, iCode)
  142219. || sqlite3FtsUnicodeIsdiacritic(iCode)
  142220. );
  142221. /* Set the output variables and return. */
  142222. pCsr->iOff = (int)(z - pCsr->aInput);
  142223. *paToken = pCsr->zToken;
  142224. *pnToken = (int)(zOut - pCsr->zToken);
  142225. *piStart = (int)(zStart - pCsr->aInput);
  142226. *piEnd = (int)(zEnd - pCsr->aInput);
  142227. *piPos = pCsr->iToken++;
  142228. return SQLITE_OK;
  142229. }
  142230. /*
  142231. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  142232. ** structure for the unicode tokenizer.
  142233. */
  142234. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  142235. static const sqlite3_tokenizer_module module = {
  142236. 0,
  142237. unicodeCreate,
  142238. unicodeDestroy,
  142239. unicodeOpen,
  142240. unicodeClose,
  142241. unicodeNext,
  142242. 0,
  142243. };
  142244. *ppModule = &module;
  142245. }
  142246. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  142247. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  142248. /************** End of fts3_unicode.c ****************************************/
  142249. /************** Begin file fts3_unicode2.c ***********************************/
  142250. /*
  142251. ** 2012 May 25
  142252. **
  142253. ** The author disclaims copyright to this source code. In place of
  142254. ** a legal notice, here is a blessing:
  142255. **
  142256. ** May you do good and not evil.
  142257. ** May you find forgiveness for yourself and forgive others.
  142258. ** May you share freely, never taking more than you give.
  142259. **
  142260. ******************************************************************************
  142261. */
  142262. /*
  142263. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  142264. */
  142265. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  142266. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  142267. /* #include <assert.h> */
  142268. /*
  142269. ** Return true if the argument corresponds to a unicode codepoint
  142270. ** classified as either a letter or a number. Otherwise false.
  142271. **
  142272. ** The results are undefined if the value passed to this function
  142273. ** is less than zero.
  142274. */
  142275. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  142276. /* Each unsigned integer in the following array corresponds to a contiguous
  142277. ** range of unicode codepoints that are not either letters or numbers (i.e.
  142278. ** codepoints for which this function should return 0).
  142279. **
  142280. ** The most significant 22 bits in each 32-bit value contain the first
  142281. ** codepoint in the range. The least significant 10 bits are used to store
  142282. ** the size of the range (always at least 1). In other words, the value
  142283. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  142284. ** C. It is not possible to represent a range larger than 1023 codepoints
  142285. ** using this format.
  142286. */
  142287. static const unsigned int aEntry[] = {
  142288. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  142289. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  142290. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  142291. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  142292. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  142293. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  142294. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  142295. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  142296. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  142297. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  142298. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  142299. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  142300. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  142301. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  142302. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  142303. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  142304. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  142305. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  142306. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  142307. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  142308. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  142309. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  142310. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  142311. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  142312. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  142313. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  142314. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  142315. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  142316. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  142317. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  142318. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  142319. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  142320. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  142321. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  142322. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  142323. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  142324. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  142325. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  142326. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  142327. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  142328. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  142329. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  142330. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  142331. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  142332. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  142333. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  142334. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  142335. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  142336. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  142337. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  142338. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  142339. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  142340. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  142341. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  142342. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  142343. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  142344. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  142345. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  142346. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  142347. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  142348. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  142349. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  142350. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  142351. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  142352. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  142353. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  142354. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  142355. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  142356. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  142357. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  142358. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  142359. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  142360. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  142361. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  142362. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  142363. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  142364. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  142365. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  142366. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  142367. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  142368. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  142369. 0x380400F0,
  142370. };
  142371. static const unsigned int aAscii[4] = {
  142372. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  142373. };
  142374. if( c<128 ){
  142375. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  142376. }else if( c<(1<<22) ){
  142377. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  142378. int iRes = 0;
  142379. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  142380. int iLo = 0;
  142381. while( iHi>=iLo ){
  142382. int iTest = (iHi + iLo) / 2;
  142383. if( key >= aEntry[iTest] ){
  142384. iRes = iTest;
  142385. iLo = iTest+1;
  142386. }else{
  142387. iHi = iTest-1;
  142388. }
  142389. }
  142390. assert( aEntry[0]<key );
  142391. assert( key>=aEntry[iRes] );
  142392. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  142393. }
  142394. return 1;
  142395. }
  142396. /*
  142397. ** If the argument is a codepoint corresponding to a lowercase letter
  142398. ** in the ASCII range with a diacritic added, return the codepoint
  142399. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  142400. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  142401. ** E"). The resuls of passing a codepoint that corresponds to an
  142402. ** uppercase letter are undefined.
  142403. */
  142404. static int remove_diacritic(int c){
  142405. unsigned short aDia[] = {
  142406. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  142407. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  142408. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  142409. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  142410. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  142411. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  142412. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  142413. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  142414. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  142415. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  142416. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  142417. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  142418. 62924, 63050, 63082, 63274, 63390,
  142419. };
  142420. char aChar[] = {
  142421. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  142422. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  142423. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  142424. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  142425. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  142426. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  142427. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  142428. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  142429. 'e', 'i', 'o', 'u', 'y',
  142430. };
  142431. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  142432. int iRes = 0;
  142433. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  142434. int iLo = 0;
  142435. while( iHi>=iLo ){
  142436. int iTest = (iHi + iLo) / 2;
  142437. if( key >= aDia[iTest] ){
  142438. iRes = iTest;
  142439. iLo = iTest+1;
  142440. }else{
  142441. iHi = iTest-1;
  142442. }
  142443. }
  142444. assert( key>=aDia[iRes] );
  142445. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  142446. }
  142447. /*
  142448. ** Return true if the argument interpreted as a unicode codepoint
  142449. ** is a diacritical modifier character.
  142450. */
  142451. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  142452. unsigned int mask0 = 0x08029FDF;
  142453. unsigned int mask1 = 0x000361F8;
  142454. if( c<768 || c>817 ) return 0;
  142455. return (c < 768+32) ?
  142456. (mask0 & (1 << (c-768))) :
  142457. (mask1 & (1 << (c-768-32)));
  142458. }
  142459. /*
  142460. ** Interpret the argument as a unicode codepoint. If the codepoint
  142461. ** is an upper case character that has a lower case equivalent,
  142462. ** return the codepoint corresponding to the lower case version.
  142463. ** Otherwise, return a copy of the argument.
  142464. **
  142465. ** The results are undefined if the value passed to this function
  142466. ** is less than zero.
  142467. */
  142468. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  142469. /* Each entry in the following array defines a rule for folding a range
  142470. ** of codepoints to lower case. The rule applies to a range of nRange
  142471. ** codepoints starting at codepoint iCode.
  142472. **
  142473. ** If the least significant bit in flags is clear, then the rule applies
  142474. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  142475. ** need to be folded). Or, if it is set, then the rule only applies to
  142476. ** every second codepoint in the range, starting with codepoint C.
  142477. **
  142478. ** The 7 most significant bits in flags are an index into the aiOff[]
  142479. ** array. If a specific codepoint C does require folding, then its lower
  142480. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  142481. **
  142482. ** The contents of this array are generated by parsing the CaseFolding.txt
  142483. ** file distributed as part of the "Unicode Character Database". See
  142484. ** http://www.unicode.org for details.
  142485. */
  142486. static const struct TableEntry {
  142487. unsigned short iCode;
  142488. unsigned char flags;
  142489. unsigned char nRange;
  142490. } aEntry[] = {
  142491. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  142492. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  142493. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  142494. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  142495. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  142496. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  142497. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  142498. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  142499. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  142500. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  142501. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  142502. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  142503. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  142504. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  142505. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  142506. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  142507. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  142508. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  142509. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  142510. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  142511. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  142512. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  142513. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  142514. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  142515. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  142516. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  142517. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  142518. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  142519. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  142520. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  142521. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  142522. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  142523. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  142524. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  142525. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  142526. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  142527. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  142528. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  142529. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  142530. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  142531. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  142532. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  142533. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  142534. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  142535. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  142536. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  142537. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  142538. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  142539. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  142540. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  142541. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  142542. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  142543. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  142544. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  142545. {65313, 14, 26},
  142546. };
  142547. static const unsigned short aiOff[] = {
  142548. 1, 2, 8, 15, 16, 26, 28, 32,
  142549. 37, 38, 40, 48, 63, 64, 69, 71,
  142550. 79, 80, 116, 202, 203, 205, 206, 207,
  142551. 209, 210, 211, 213, 214, 217, 218, 219,
  142552. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  142553. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  142554. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  142555. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  142556. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  142557. 65514, 65521, 65527, 65528, 65529,
  142558. };
  142559. int ret = c;
  142560. assert( c>=0 );
  142561. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  142562. if( c<128 ){
  142563. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  142564. }else if( c<65536 ){
  142565. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  142566. int iLo = 0;
  142567. int iRes = -1;
  142568. while( iHi>=iLo ){
  142569. int iTest = (iHi + iLo) / 2;
  142570. int cmp = (c - aEntry[iTest].iCode);
  142571. if( cmp>=0 ){
  142572. iRes = iTest;
  142573. iLo = iTest+1;
  142574. }else{
  142575. iHi = iTest-1;
  142576. }
  142577. }
  142578. assert( iRes<0 || c>=aEntry[iRes].iCode );
  142579. if( iRes>=0 ){
  142580. const struct TableEntry *p = &aEntry[iRes];
  142581. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  142582. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  142583. assert( ret>0 );
  142584. }
  142585. }
  142586. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  142587. }
  142588. else if( c>=66560 && c<66600 ){
  142589. ret = c + 40;
  142590. }
  142591. return ret;
  142592. }
  142593. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  142594. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  142595. /************** End of fts3_unicode2.c ***************************************/
  142596. /************** Begin file rtree.c *******************************************/
  142597. /*
  142598. ** 2001 September 15
  142599. **
  142600. ** The author disclaims copyright to this source code. In place of
  142601. ** a legal notice, here is a blessing:
  142602. **
  142603. ** May you do good and not evil.
  142604. ** May you find forgiveness for yourself and forgive others.
  142605. ** May you share freely, never taking more than you give.
  142606. **
  142607. *************************************************************************
  142608. ** This file contains code for implementations of the r-tree and r*-tree
  142609. ** algorithms packaged as an SQLite virtual table module.
  142610. */
  142611. /*
  142612. ** Database Format of R-Tree Tables
  142613. ** --------------------------------
  142614. **
  142615. ** The data structure for a single virtual r-tree table is stored in three
  142616. ** native SQLite tables declared as follows. In each case, the '%' character
  142617. ** in the table name is replaced with the user-supplied name of the r-tree
  142618. ** table.
  142619. **
  142620. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  142621. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  142622. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  142623. **
  142624. ** The data for each node of the r-tree structure is stored in the %_node
  142625. ** table. For each node that is not the root node of the r-tree, there is
  142626. ** an entry in the %_parent table associating the node with its parent.
  142627. ** And for each row of data in the table, there is an entry in the %_rowid
  142628. ** table that maps from the entries rowid to the id of the node that it
  142629. ** is stored on.
  142630. **
  142631. ** The root node of an r-tree always exists, even if the r-tree table is
  142632. ** empty. The nodeno of the root node is always 1. All other nodes in the
  142633. ** table must be the same size as the root node. The content of each node
  142634. ** is formatted as follows:
  142635. **
  142636. ** 1. If the node is the root node (node 1), then the first 2 bytes
  142637. ** of the node contain the tree depth as a big-endian integer.
  142638. ** For non-root nodes, the first 2 bytes are left unused.
  142639. **
  142640. ** 2. The next 2 bytes contain the number of entries currently
  142641. ** stored in the node.
  142642. **
  142643. ** 3. The remainder of the node contains the node entries. Each entry
  142644. ** consists of a single 8-byte integer followed by an even number
  142645. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  142646. ** of a record. For internal nodes it is the node number of a
  142647. ** child page.
  142648. */
  142649. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  142650. #ifndef SQLITE_CORE
  142651. /* #include "sqlite3ext.h" */
  142652. SQLITE_EXTENSION_INIT1
  142653. #else
  142654. /* #include "sqlite3.h" */
  142655. #endif
  142656. /* #include <string.h> */
  142657. /* #include <assert.h> */
  142658. /* #include <stdio.h> */
  142659. #ifndef SQLITE_AMALGAMATION
  142660. #include "sqlite3rtree.h"
  142661. typedef sqlite3_int64 i64;
  142662. typedef unsigned char u8;
  142663. typedef unsigned short u16;
  142664. typedef unsigned int u32;
  142665. #endif
  142666. /* The following macro is used to suppress compiler warnings.
  142667. */
  142668. #ifndef UNUSED_PARAMETER
  142669. # define UNUSED_PARAMETER(x) (void)(x)
  142670. #endif
  142671. typedef struct Rtree Rtree;
  142672. typedef struct RtreeCursor RtreeCursor;
  142673. typedef struct RtreeNode RtreeNode;
  142674. typedef struct RtreeCell RtreeCell;
  142675. typedef struct RtreeConstraint RtreeConstraint;
  142676. typedef struct RtreeMatchArg RtreeMatchArg;
  142677. typedef struct RtreeGeomCallback RtreeGeomCallback;
  142678. typedef union RtreeCoord RtreeCoord;
  142679. typedef struct RtreeSearchPoint RtreeSearchPoint;
  142680. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  142681. #define RTREE_MAX_DIMENSIONS 5
  142682. /* Size of hash table Rtree.aHash. This hash table is not expected to
  142683. ** ever contain very many entries, so a fixed number of buckets is
  142684. ** used.
  142685. */
  142686. #define HASHSIZE 97
  142687. /* The xBestIndex method of this virtual table requires an estimate of
  142688. ** the number of rows in the virtual table to calculate the costs of
  142689. ** various strategies. If possible, this estimate is loaded from the
  142690. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  142691. ** Otherwise, if no sqlite_stat1 entry is available, use
  142692. ** RTREE_DEFAULT_ROWEST.
  142693. */
  142694. #define RTREE_DEFAULT_ROWEST 1048576
  142695. #define RTREE_MIN_ROWEST 100
  142696. /*
  142697. ** An rtree virtual-table object.
  142698. */
  142699. struct Rtree {
  142700. sqlite3_vtab base; /* Base class. Must be first */
  142701. sqlite3 *db; /* Host database connection */
  142702. int iNodeSize; /* Size in bytes of each node in the node table */
  142703. u8 nDim; /* Number of dimensions */
  142704. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  142705. u8 nBytesPerCell; /* Bytes consumed per cell */
  142706. int iDepth; /* Current depth of the r-tree structure */
  142707. char *zDb; /* Name of database containing r-tree table */
  142708. char *zName; /* Name of r-tree table */
  142709. int nBusy; /* Current number of users of this structure */
  142710. i64 nRowEst; /* Estimated number of rows in this table */
  142711. /* List of nodes removed during a CondenseTree operation. List is
  142712. ** linked together via the pointer normally used for hash chains -
  142713. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  142714. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  142715. */
  142716. RtreeNode *pDeleted;
  142717. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  142718. /* Statements to read/write/delete a record from xxx_node */
  142719. sqlite3_stmt *pReadNode;
  142720. sqlite3_stmt *pWriteNode;
  142721. sqlite3_stmt *pDeleteNode;
  142722. /* Statements to read/write/delete a record from xxx_rowid */
  142723. sqlite3_stmt *pReadRowid;
  142724. sqlite3_stmt *pWriteRowid;
  142725. sqlite3_stmt *pDeleteRowid;
  142726. /* Statements to read/write/delete a record from xxx_parent */
  142727. sqlite3_stmt *pReadParent;
  142728. sqlite3_stmt *pWriteParent;
  142729. sqlite3_stmt *pDeleteParent;
  142730. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  142731. };
  142732. /* Possible values for Rtree.eCoordType: */
  142733. #define RTREE_COORD_REAL32 0
  142734. #define RTREE_COORD_INT32 1
  142735. /*
  142736. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  142737. ** only deal with integer coordinates. No floating point operations
  142738. ** will be done.
  142739. */
  142740. #ifdef SQLITE_RTREE_INT_ONLY
  142741. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  142742. typedef int RtreeValue; /* Low accuracy coordinate */
  142743. # define RTREE_ZERO 0
  142744. #else
  142745. typedef double RtreeDValue; /* High accuracy coordinate */
  142746. typedef float RtreeValue; /* Low accuracy coordinate */
  142747. # define RTREE_ZERO 0.0
  142748. #endif
  142749. /*
  142750. ** When doing a search of an r-tree, instances of the following structure
  142751. ** record intermediate results from the tree walk.
  142752. **
  142753. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  142754. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  142755. ** the id is of the parent node and the cell that RtreeSearchPoint
  142756. ** represents is the iCell-th entry in the parent node.
  142757. */
  142758. struct RtreeSearchPoint {
  142759. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  142760. sqlite3_int64 id; /* Node ID */
  142761. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  142762. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  142763. u8 iCell; /* Cell index within the node */
  142764. };
  142765. /*
  142766. ** The minimum number of cells allowed for a node is a third of the
  142767. ** maximum. In Gutman's notation:
  142768. **
  142769. ** m = M/3
  142770. **
  142771. ** If an R*-tree "Reinsert" operation is required, the same number of
  142772. ** cells are removed from the overfull node and reinserted into the tree.
  142773. */
  142774. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  142775. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  142776. #define RTREE_MAXCELLS 51
  142777. /*
  142778. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  142779. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  142780. ** Therefore all non-root nodes must contain at least 3 entries. Since
  142781. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  142782. ** 40 or less.
  142783. */
  142784. #define RTREE_MAX_DEPTH 40
  142785. /*
  142786. ** Number of entries in the cursor RtreeNode cache. The first entry is
  142787. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  142788. ** entries cache the RtreeNode for the first elements of the priority queue.
  142789. */
  142790. #define RTREE_CACHE_SZ 5
  142791. /*
  142792. ** An rtree cursor object.
  142793. */
  142794. struct RtreeCursor {
  142795. sqlite3_vtab_cursor base; /* Base class. Must be first */
  142796. u8 atEOF; /* True if at end of search */
  142797. u8 bPoint; /* True if sPoint is valid */
  142798. int iStrategy; /* Copy of idxNum search parameter */
  142799. int nConstraint; /* Number of entries in aConstraint */
  142800. RtreeConstraint *aConstraint; /* Search constraints. */
  142801. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  142802. int nPoint; /* Number of slots used in aPoint[] */
  142803. int mxLevel; /* iLevel value for root of the tree */
  142804. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  142805. RtreeSearchPoint sPoint; /* Cached next search point */
  142806. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  142807. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  142808. };
  142809. /* Return the Rtree of a RtreeCursor */
  142810. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  142811. /*
  142812. ** A coordinate can be either a floating point number or a integer. All
  142813. ** coordinates within a single R-Tree are always of the same time.
  142814. */
  142815. union RtreeCoord {
  142816. RtreeValue f; /* Floating point value */
  142817. int i; /* Integer value */
  142818. u32 u; /* Unsigned for byte-order conversions */
  142819. };
  142820. /*
  142821. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  142822. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  142823. ** variable pRtree points to the Rtree structure associated with the
  142824. ** RtreeCoord.
  142825. */
  142826. #ifdef SQLITE_RTREE_INT_ONLY
  142827. # define DCOORD(coord) ((RtreeDValue)coord.i)
  142828. #else
  142829. # define DCOORD(coord) ( \
  142830. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  142831. ((double)coord.f) : \
  142832. ((double)coord.i) \
  142833. )
  142834. #endif
  142835. /*
  142836. ** A search constraint.
  142837. */
  142838. struct RtreeConstraint {
  142839. int iCoord; /* Index of constrained coordinate */
  142840. int op; /* Constraining operation */
  142841. union {
  142842. RtreeDValue rValue; /* Constraint value. */
  142843. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  142844. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  142845. } u;
  142846. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  142847. };
  142848. /* Possible values for RtreeConstraint.op */
  142849. #define RTREE_EQ 0x41 /* A */
  142850. #define RTREE_LE 0x42 /* B */
  142851. #define RTREE_LT 0x43 /* C */
  142852. #define RTREE_GE 0x44 /* D */
  142853. #define RTREE_GT 0x45 /* E */
  142854. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  142855. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  142856. /*
  142857. ** An rtree structure node.
  142858. */
  142859. struct RtreeNode {
  142860. RtreeNode *pParent; /* Parent node */
  142861. i64 iNode; /* The node number */
  142862. int nRef; /* Number of references to this node */
  142863. int isDirty; /* True if the node needs to be written to disk */
  142864. u8 *zData; /* Content of the node, as should be on disk */
  142865. RtreeNode *pNext; /* Next node in this hash collision chain */
  142866. };
  142867. /* Return the number of cells in a node */
  142868. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  142869. /*
  142870. ** A single cell from a node, deserialized
  142871. */
  142872. struct RtreeCell {
  142873. i64 iRowid; /* Node or entry ID */
  142874. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  142875. };
  142876. /*
  142877. ** This object becomes the sqlite3_user_data() for the SQL functions
  142878. ** that are created by sqlite3_rtree_geometry_callback() and
  142879. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  142880. ** operators in order to constrain a search.
  142881. **
  142882. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  142883. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  142884. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  142885. ** sqlite3_rtree_query_callback().
  142886. **
  142887. ** This object is deleted automatically by the destructor mechanism in
  142888. ** sqlite3_create_function_v2().
  142889. */
  142890. struct RtreeGeomCallback {
  142891. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  142892. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  142893. void (*xDestructor)(void*);
  142894. void *pContext;
  142895. };
  142896. /*
  142897. ** Value for the first field of every RtreeMatchArg object. The MATCH
  142898. ** operator tests that the first field of a blob operand matches this
  142899. ** value to avoid operating on invalid blobs (which could cause a segfault).
  142900. */
  142901. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  142902. /*
  142903. ** An instance of this structure (in the form of a BLOB) is returned by
  142904. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  142905. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  142906. ** operand to the MATCH operator of an R-Tree.
  142907. */
  142908. struct RtreeMatchArg {
  142909. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  142910. RtreeGeomCallback cb; /* Info about the callback functions */
  142911. int nParam; /* Number of parameters to the SQL function */
  142912. sqlite3_value **apSqlParam; /* Original SQL parameter values */
  142913. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  142914. };
  142915. #ifndef MAX
  142916. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  142917. #endif
  142918. #ifndef MIN
  142919. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  142920. #endif
  142921. /*
  142922. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  142923. ** 64 bit integer. The deserialized value is returned.
  142924. */
  142925. static int readInt16(u8 *p){
  142926. return (p[0]<<8) + p[1];
  142927. }
  142928. static void readCoord(u8 *p, RtreeCoord *pCoord){
  142929. pCoord->u = (
  142930. (((u32)p[0]) << 24) +
  142931. (((u32)p[1]) << 16) +
  142932. (((u32)p[2]) << 8) +
  142933. (((u32)p[3]) << 0)
  142934. );
  142935. }
  142936. static i64 readInt64(u8 *p){
  142937. return (
  142938. (((i64)p[0]) << 56) +
  142939. (((i64)p[1]) << 48) +
  142940. (((i64)p[2]) << 40) +
  142941. (((i64)p[3]) << 32) +
  142942. (((i64)p[4]) << 24) +
  142943. (((i64)p[5]) << 16) +
  142944. (((i64)p[6]) << 8) +
  142945. (((i64)p[7]) << 0)
  142946. );
  142947. }
  142948. /*
  142949. ** Functions to serialize a 16 bit integer, 32 bit real number and
  142950. ** 64 bit integer. The value returned is the number of bytes written
  142951. ** to the argument buffer (always 2, 4 and 8 respectively).
  142952. */
  142953. static int writeInt16(u8 *p, int i){
  142954. p[0] = (i>> 8)&0xFF;
  142955. p[1] = (i>> 0)&0xFF;
  142956. return 2;
  142957. }
  142958. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  142959. u32 i;
  142960. assert( sizeof(RtreeCoord)==4 );
  142961. assert( sizeof(u32)==4 );
  142962. i = pCoord->u;
  142963. p[0] = (i>>24)&0xFF;
  142964. p[1] = (i>>16)&0xFF;
  142965. p[2] = (i>> 8)&0xFF;
  142966. p[3] = (i>> 0)&0xFF;
  142967. return 4;
  142968. }
  142969. static int writeInt64(u8 *p, i64 i){
  142970. p[0] = (i>>56)&0xFF;
  142971. p[1] = (i>>48)&0xFF;
  142972. p[2] = (i>>40)&0xFF;
  142973. p[3] = (i>>32)&0xFF;
  142974. p[4] = (i>>24)&0xFF;
  142975. p[5] = (i>>16)&0xFF;
  142976. p[6] = (i>> 8)&0xFF;
  142977. p[7] = (i>> 0)&0xFF;
  142978. return 8;
  142979. }
  142980. /*
  142981. ** Increment the reference count of node p.
  142982. */
  142983. static void nodeReference(RtreeNode *p){
  142984. if( p ){
  142985. p->nRef++;
  142986. }
  142987. }
  142988. /*
  142989. ** Clear the content of node p (set all bytes to 0x00).
  142990. */
  142991. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  142992. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  142993. p->isDirty = 1;
  142994. }
  142995. /*
  142996. ** Given a node number iNode, return the corresponding key to use
  142997. ** in the Rtree.aHash table.
  142998. */
  142999. static int nodeHash(i64 iNode){
  143000. return iNode % HASHSIZE;
  143001. }
  143002. /*
  143003. ** Search the node hash table for node iNode. If found, return a pointer
  143004. ** to it. Otherwise, return 0.
  143005. */
  143006. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  143007. RtreeNode *p;
  143008. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  143009. return p;
  143010. }
  143011. /*
  143012. ** Add node pNode to the node hash table.
  143013. */
  143014. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  143015. int iHash;
  143016. assert( pNode->pNext==0 );
  143017. iHash = nodeHash(pNode->iNode);
  143018. pNode->pNext = pRtree->aHash[iHash];
  143019. pRtree->aHash[iHash] = pNode;
  143020. }
  143021. /*
  143022. ** Remove node pNode from the node hash table.
  143023. */
  143024. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  143025. RtreeNode **pp;
  143026. if( pNode->iNode!=0 ){
  143027. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  143028. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  143029. *pp = pNode->pNext;
  143030. pNode->pNext = 0;
  143031. }
  143032. }
  143033. /*
  143034. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  143035. ** indicating that node has not yet been assigned a node number. It is
  143036. ** assigned a node number when nodeWrite() is called to write the
  143037. ** node contents out to the database.
  143038. */
  143039. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  143040. RtreeNode *pNode;
  143041. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  143042. if( pNode ){
  143043. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  143044. pNode->zData = (u8 *)&pNode[1];
  143045. pNode->nRef = 1;
  143046. pNode->pParent = pParent;
  143047. pNode->isDirty = 1;
  143048. nodeReference(pParent);
  143049. }
  143050. return pNode;
  143051. }
  143052. /*
  143053. ** Obtain a reference to an r-tree node.
  143054. */
  143055. static int nodeAcquire(
  143056. Rtree *pRtree, /* R-tree structure */
  143057. i64 iNode, /* Node number to load */
  143058. RtreeNode *pParent, /* Either the parent node or NULL */
  143059. RtreeNode **ppNode /* OUT: Acquired node */
  143060. ){
  143061. int rc;
  143062. int rc2 = SQLITE_OK;
  143063. RtreeNode *pNode;
  143064. /* Check if the requested node is already in the hash table. If so,
  143065. ** increase its reference count and return it.
  143066. */
  143067. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  143068. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  143069. if( pParent && !pNode->pParent ){
  143070. nodeReference(pParent);
  143071. pNode->pParent = pParent;
  143072. }
  143073. pNode->nRef++;
  143074. *ppNode = pNode;
  143075. return SQLITE_OK;
  143076. }
  143077. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  143078. rc = sqlite3_step(pRtree->pReadNode);
  143079. if( rc==SQLITE_ROW ){
  143080. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  143081. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  143082. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  143083. if( !pNode ){
  143084. rc2 = SQLITE_NOMEM;
  143085. }else{
  143086. pNode->pParent = pParent;
  143087. pNode->zData = (u8 *)&pNode[1];
  143088. pNode->nRef = 1;
  143089. pNode->iNode = iNode;
  143090. pNode->isDirty = 0;
  143091. pNode->pNext = 0;
  143092. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  143093. nodeReference(pParent);
  143094. }
  143095. }
  143096. }
  143097. rc = sqlite3_reset(pRtree->pReadNode);
  143098. if( rc==SQLITE_OK ) rc = rc2;
  143099. /* If the root node was just loaded, set pRtree->iDepth to the height
  143100. ** of the r-tree structure. A height of zero means all data is stored on
  143101. ** the root node. A height of one means the children of the root node
  143102. ** are the leaves, and so on. If the depth as specified on the root node
  143103. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  143104. */
  143105. if( pNode && iNode==1 ){
  143106. pRtree->iDepth = readInt16(pNode->zData);
  143107. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  143108. rc = SQLITE_CORRUPT_VTAB;
  143109. }
  143110. }
  143111. /* If no error has occurred so far, check if the "number of entries"
  143112. ** field on the node is too large. If so, set the return code to
  143113. ** SQLITE_CORRUPT_VTAB.
  143114. */
  143115. if( pNode && rc==SQLITE_OK ){
  143116. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  143117. rc = SQLITE_CORRUPT_VTAB;
  143118. }
  143119. }
  143120. if( rc==SQLITE_OK ){
  143121. if( pNode!=0 ){
  143122. nodeHashInsert(pRtree, pNode);
  143123. }else{
  143124. rc = SQLITE_CORRUPT_VTAB;
  143125. }
  143126. *ppNode = pNode;
  143127. }else{
  143128. sqlite3_free(pNode);
  143129. *ppNode = 0;
  143130. }
  143131. return rc;
  143132. }
  143133. /*
  143134. ** Overwrite cell iCell of node pNode with the contents of pCell.
  143135. */
  143136. static void nodeOverwriteCell(
  143137. Rtree *pRtree, /* The overall R-Tree */
  143138. RtreeNode *pNode, /* The node into which the cell is to be written */
  143139. RtreeCell *pCell, /* The cell to write */
  143140. int iCell /* Index into pNode into which pCell is written */
  143141. ){
  143142. int ii;
  143143. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  143144. p += writeInt64(p, pCell->iRowid);
  143145. for(ii=0; ii<(pRtree->nDim*2); ii++){
  143146. p += writeCoord(p, &pCell->aCoord[ii]);
  143147. }
  143148. pNode->isDirty = 1;
  143149. }
  143150. /*
  143151. ** Remove the cell with index iCell from node pNode.
  143152. */
  143153. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  143154. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  143155. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  143156. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  143157. memmove(pDst, pSrc, nByte);
  143158. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  143159. pNode->isDirty = 1;
  143160. }
  143161. /*
  143162. ** Insert the contents of cell pCell into node pNode. If the insert
  143163. ** is successful, return SQLITE_OK.
  143164. **
  143165. ** If there is not enough free space in pNode, return SQLITE_FULL.
  143166. */
  143167. static int nodeInsertCell(
  143168. Rtree *pRtree, /* The overall R-Tree */
  143169. RtreeNode *pNode, /* Write new cell into this node */
  143170. RtreeCell *pCell /* The cell to be inserted */
  143171. ){
  143172. int nCell; /* Current number of cells in pNode */
  143173. int nMaxCell; /* Maximum number of cells for pNode */
  143174. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  143175. nCell = NCELL(pNode);
  143176. assert( nCell<=nMaxCell );
  143177. if( nCell<nMaxCell ){
  143178. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  143179. writeInt16(&pNode->zData[2], nCell+1);
  143180. pNode->isDirty = 1;
  143181. }
  143182. return (nCell==nMaxCell);
  143183. }
  143184. /*
  143185. ** If the node is dirty, write it out to the database.
  143186. */
  143187. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  143188. int rc = SQLITE_OK;
  143189. if( pNode->isDirty ){
  143190. sqlite3_stmt *p = pRtree->pWriteNode;
  143191. if( pNode->iNode ){
  143192. sqlite3_bind_int64(p, 1, pNode->iNode);
  143193. }else{
  143194. sqlite3_bind_null(p, 1);
  143195. }
  143196. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  143197. sqlite3_step(p);
  143198. pNode->isDirty = 0;
  143199. rc = sqlite3_reset(p);
  143200. if( pNode->iNode==0 && rc==SQLITE_OK ){
  143201. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  143202. nodeHashInsert(pRtree, pNode);
  143203. }
  143204. }
  143205. return rc;
  143206. }
  143207. /*
  143208. ** Release a reference to a node. If the node is dirty and the reference
  143209. ** count drops to zero, the node data is written to the database.
  143210. */
  143211. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  143212. int rc = SQLITE_OK;
  143213. if( pNode ){
  143214. assert( pNode->nRef>0 );
  143215. pNode->nRef--;
  143216. if( pNode->nRef==0 ){
  143217. if( pNode->iNode==1 ){
  143218. pRtree->iDepth = -1;
  143219. }
  143220. if( pNode->pParent ){
  143221. rc = nodeRelease(pRtree, pNode->pParent);
  143222. }
  143223. if( rc==SQLITE_OK ){
  143224. rc = nodeWrite(pRtree, pNode);
  143225. }
  143226. nodeHashDelete(pRtree, pNode);
  143227. sqlite3_free(pNode);
  143228. }
  143229. }
  143230. return rc;
  143231. }
  143232. /*
  143233. ** Return the 64-bit integer value associated with cell iCell of
  143234. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  143235. ** an internal node, then the 64-bit integer is a child page number.
  143236. */
  143237. static i64 nodeGetRowid(
  143238. Rtree *pRtree, /* The overall R-Tree */
  143239. RtreeNode *pNode, /* The node from which to extract the ID */
  143240. int iCell /* The cell index from which to extract the ID */
  143241. ){
  143242. assert( iCell<NCELL(pNode) );
  143243. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  143244. }
  143245. /*
  143246. ** Return coordinate iCoord from cell iCell in node pNode.
  143247. */
  143248. static void nodeGetCoord(
  143249. Rtree *pRtree, /* The overall R-Tree */
  143250. RtreeNode *pNode, /* The node from which to extract a coordinate */
  143251. int iCell, /* The index of the cell within the node */
  143252. int iCoord, /* Which coordinate to extract */
  143253. RtreeCoord *pCoord /* OUT: Space to write result to */
  143254. ){
  143255. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  143256. }
  143257. /*
  143258. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  143259. ** to by pCell with the results.
  143260. */
  143261. static void nodeGetCell(
  143262. Rtree *pRtree, /* The overall R-Tree */
  143263. RtreeNode *pNode, /* The node containing the cell to be read */
  143264. int iCell, /* Index of the cell within the node */
  143265. RtreeCell *pCell /* OUT: Write the cell contents here */
  143266. ){
  143267. u8 *pData;
  143268. RtreeCoord *pCoord;
  143269. int ii;
  143270. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  143271. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  143272. pCoord = pCell->aCoord;
  143273. for(ii=0; ii<pRtree->nDim*2; ii++){
  143274. readCoord(&pData[ii*4], &pCoord[ii]);
  143275. }
  143276. }
  143277. /* Forward declaration for the function that does the work of
  143278. ** the virtual table module xCreate() and xConnect() methods.
  143279. */
  143280. static int rtreeInit(
  143281. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  143282. );
  143283. /*
  143284. ** Rtree virtual table module xCreate method.
  143285. */
  143286. static int rtreeCreate(
  143287. sqlite3 *db,
  143288. void *pAux,
  143289. int argc, const char *const*argv,
  143290. sqlite3_vtab **ppVtab,
  143291. char **pzErr
  143292. ){
  143293. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  143294. }
  143295. /*
  143296. ** Rtree virtual table module xConnect method.
  143297. */
  143298. static int rtreeConnect(
  143299. sqlite3 *db,
  143300. void *pAux,
  143301. int argc, const char *const*argv,
  143302. sqlite3_vtab **ppVtab,
  143303. char **pzErr
  143304. ){
  143305. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  143306. }
  143307. /*
  143308. ** Increment the r-tree reference count.
  143309. */
  143310. static void rtreeReference(Rtree *pRtree){
  143311. pRtree->nBusy++;
  143312. }
  143313. /*
  143314. ** Decrement the r-tree reference count. When the reference count reaches
  143315. ** zero the structure is deleted.
  143316. */
  143317. static void rtreeRelease(Rtree *pRtree){
  143318. pRtree->nBusy--;
  143319. if( pRtree->nBusy==0 ){
  143320. sqlite3_finalize(pRtree->pReadNode);
  143321. sqlite3_finalize(pRtree->pWriteNode);
  143322. sqlite3_finalize(pRtree->pDeleteNode);
  143323. sqlite3_finalize(pRtree->pReadRowid);
  143324. sqlite3_finalize(pRtree->pWriteRowid);
  143325. sqlite3_finalize(pRtree->pDeleteRowid);
  143326. sqlite3_finalize(pRtree->pReadParent);
  143327. sqlite3_finalize(pRtree->pWriteParent);
  143328. sqlite3_finalize(pRtree->pDeleteParent);
  143329. sqlite3_free(pRtree);
  143330. }
  143331. }
  143332. /*
  143333. ** Rtree virtual table module xDisconnect method.
  143334. */
  143335. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  143336. rtreeRelease((Rtree *)pVtab);
  143337. return SQLITE_OK;
  143338. }
  143339. /*
  143340. ** Rtree virtual table module xDestroy method.
  143341. */
  143342. static int rtreeDestroy(sqlite3_vtab *pVtab){
  143343. Rtree *pRtree = (Rtree *)pVtab;
  143344. int rc;
  143345. char *zCreate = sqlite3_mprintf(
  143346. "DROP TABLE '%q'.'%q_node';"
  143347. "DROP TABLE '%q'.'%q_rowid';"
  143348. "DROP TABLE '%q'.'%q_parent';",
  143349. pRtree->zDb, pRtree->zName,
  143350. pRtree->zDb, pRtree->zName,
  143351. pRtree->zDb, pRtree->zName
  143352. );
  143353. if( !zCreate ){
  143354. rc = SQLITE_NOMEM;
  143355. }else{
  143356. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  143357. sqlite3_free(zCreate);
  143358. }
  143359. if( rc==SQLITE_OK ){
  143360. rtreeRelease(pRtree);
  143361. }
  143362. return rc;
  143363. }
  143364. /*
  143365. ** Rtree virtual table module xOpen method.
  143366. */
  143367. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  143368. int rc = SQLITE_NOMEM;
  143369. RtreeCursor *pCsr;
  143370. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  143371. if( pCsr ){
  143372. memset(pCsr, 0, sizeof(RtreeCursor));
  143373. pCsr->base.pVtab = pVTab;
  143374. rc = SQLITE_OK;
  143375. }
  143376. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  143377. return rc;
  143378. }
  143379. /*
  143380. ** Free the RtreeCursor.aConstraint[] array and its contents.
  143381. */
  143382. static void freeCursorConstraints(RtreeCursor *pCsr){
  143383. if( pCsr->aConstraint ){
  143384. int i; /* Used to iterate through constraint array */
  143385. for(i=0; i<pCsr->nConstraint; i++){
  143386. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  143387. if( pInfo ){
  143388. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  143389. sqlite3_free(pInfo);
  143390. }
  143391. }
  143392. sqlite3_free(pCsr->aConstraint);
  143393. pCsr->aConstraint = 0;
  143394. }
  143395. }
  143396. /*
  143397. ** Rtree virtual table module xClose method.
  143398. */
  143399. static int rtreeClose(sqlite3_vtab_cursor *cur){
  143400. Rtree *pRtree = (Rtree *)(cur->pVtab);
  143401. int ii;
  143402. RtreeCursor *pCsr = (RtreeCursor *)cur;
  143403. freeCursorConstraints(pCsr);
  143404. sqlite3_free(pCsr->aPoint);
  143405. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  143406. sqlite3_free(pCsr);
  143407. return SQLITE_OK;
  143408. }
  143409. /*
  143410. ** Rtree virtual table module xEof method.
  143411. **
  143412. ** Return non-zero if the cursor does not currently point to a valid
  143413. ** record (i.e if the scan has finished), or zero otherwise.
  143414. */
  143415. static int rtreeEof(sqlite3_vtab_cursor *cur){
  143416. RtreeCursor *pCsr = (RtreeCursor *)cur;
  143417. return pCsr->atEOF;
  143418. }
  143419. /*
  143420. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  143421. ** The on-disk format is big-endian and needs to be converted for little-
  143422. ** endian platforms. The on-disk record stores integer coordinates if
  143423. ** eInt is true and it stores 32-bit floating point records if eInt is
  143424. ** false. a[] is the four bytes of the on-disk record to be decoded.
  143425. ** Store the results in "r".
  143426. **
  143427. ** There are three versions of this macro, one each for little-endian and
  143428. ** big-endian processors and a third generic implementation. The endian-
  143429. ** specific implementations are much faster and are preferred if the
  143430. ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
  143431. ** macro is part of sqliteInt.h and hence the endian-specific
  143432. ** implementation will only be used if this module is compiled as part
  143433. ** of the amalgamation.
  143434. */
  143435. #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
  143436. #define RTREE_DECODE_COORD(eInt, a, r) { \
  143437. RtreeCoord c; /* Coordinate decoded */ \
  143438. memcpy(&c.u,a,4); \
  143439. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  143440. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  143441. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  143442. }
  143443. #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
  143444. #define RTREE_DECODE_COORD(eInt, a, r) { \
  143445. RtreeCoord c; /* Coordinate decoded */ \
  143446. memcpy(&c.u,a,4); \
  143447. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  143448. }
  143449. #else
  143450. #define RTREE_DECODE_COORD(eInt, a, r) { \
  143451. RtreeCoord c; /* Coordinate decoded */ \
  143452. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  143453. +((u32)a[2]<<8) + a[3]; \
  143454. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  143455. }
  143456. #endif
  143457. /*
  143458. ** Check the RTree node or entry given by pCellData and p against the MATCH
  143459. ** constraint pConstraint.
  143460. */
  143461. static int rtreeCallbackConstraint(
  143462. RtreeConstraint *pConstraint, /* The constraint to test */
  143463. int eInt, /* True if RTree holding integer coordinates */
  143464. u8 *pCellData, /* Raw cell content */
  143465. RtreeSearchPoint *pSearch, /* Container of this cell */
  143466. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  143467. int *peWithin /* OUT: visibility of the cell */
  143468. ){
  143469. int i; /* Loop counter */
  143470. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  143471. int nCoord = pInfo->nCoord; /* No. of coordinates */
  143472. int rc; /* Callback return code */
  143473. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  143474. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  143475. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  143476. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  143477. pInfo->iRowid = readInt64(pCellData);
  143478. }
  143479. pCellData += 8;
  143480. for(i=0; i<nCoord; i++, pCellData += 4){
  143481. RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
  143482. }
  143483. if( pConstraint->op==RTREE_MATCH ){
  143484. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  143485. nCoord, aCoord, &i);
  143486. if( i==0 ) *peWithin = NOT_WITHIN;
  143487. *prScore = RTREE_ZERO;
  143488. }else{
  143489. pInfo->aCoord = aCoord;
  143490. pInfo->iLevel = pSearch->iLevel - 1;
  143491. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  143492. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  143493. rc = pConstraint->u.xQueryFunc(pInfo);
  143494. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  143495. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  143496. *prScore = pInfo->rScore;
  143497. }
  143498. }
  143499. return rc;
  143500. }
  143501. /*
  143502. ** Check the internal RTree node given by pCellData against constraint p.
  143503. ** If this constraint cannot be satisfied by any child within the node,
  143504. ** set *peWithin to NOT_WITHIN.
  143505. */
  143506. static void rtreeNonleafConstraint(
  143507. RtreeConstraint *p, /* The constraint to test */
  143508. int eInt, /* True if RTree holds integer coordinates */
  143509. u8 *pCellData, /* Raw cell content as appears on disk */
  143510. int *peWithin /* Adjust downward, as appropriate */
  143511. ){
  143512. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  143513. /* p->iCoord might point to either a lower or upper bound coordinate
  143514. ** in a coordinate pair. But make pCellData point to the lower bound.
  143515. */
  143516. pCellData += 8 + 4*(p->iCoord&0xfe);
  143517. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  143518. || p->op==RTREE_GT || p->op==RTREE_EQ );
  143519. switch( p->op ){
  143520. case RTREE_LE:
  143521. case RTREE_LT:
  143522. case RTREE_EQ:
  143523. RTREE_DECODE_COORD(eInt, pCellData, val);
  143524. /* val now holds the lower bound of the coordinate pair */
  143525. if( p->u.rValue>=val ) return;
  143526. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  143527. /* Fall through for the RTREE_EQ case */
  143528. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  143529. pCellData += 4;
  143530. RTREE_DECODE_COORD(eInt, pCellData, val);
  143531. /* val now holds the upper bound of the coordinate pair */
  143532. if( p->u.rValue<=val ) return;
  143533. }
  143534. *peWithin = NOT_WITHIN;
  143535. }
  143536. /*
  143537. ** Check the leaf RTree cell given by pCellData against constraint p.
  143538. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  143539. ** If the constraint is satisfied, leave *peWithin unchanged.
  143540. **
  143541. ** The constraint is of the form: xN op $val
  143542. **
  143543. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  143544. ** pCellData. $val is given by p->u.rValue.
  143545. */
  143546. static void rtreeLeafConstraint(
  143547. RtreeConstraint *p, /* The constraint to test */
  143548. int eInt, /* True if RTree holds integer coordinates */
  143549. u8 *pCellData, /* Raw cell content as appears on disk */
  143550. int *peWithin /* Adjust downward, as appropriate */
  143551. ){
  143552. RtreeDValue xN; /* Coordinate value converted to a double */
  143553. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  143554. || p->op==RTREE_GT || p->op==RTREE_EQ );
  143555. pCellData += 8 + p->iCoord*4;
  143556. RTREE_DECODE_COORD(eInt, pCellData, xN);
  143557. switch( p->op ){
  143558. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  143559. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  143560. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  143561. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  143562. default: if( xN == p->u.rValue ) return; break;
  143563. }
  143564. *peWithin = NOT_WITHIN;
  143565. }
  143566. /*
  143567. ** One of the cells in node pNode is guaranteed to have a 64-bit
  143568. ** integer value equal to iRowid. Return the index of this cell.
  143569. */
  143570. static int nodeRowidIndex(
  143571. Rtree *pRtree,
  143572. RtreeNode *pNode,
  143573. i64 iRowid,
  143574. int *piIndex
  143575. ){
  143576. int ii;
  143577. int nCell = NCELL(pNode);
  143578. assert( nCell<200 );
  143579. for(ii=0; ii<nCell; ii++){
  143580. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  143581. *piIndex = ii;
  143582. return SQLITE_OK;
  143583. }
  143584. }
  143585. return SQLITE_CORRUPT_VTAB;
  143586. }
  143587. /*
  143588. ** Return the index of the cell containing a pointer to node pNode
  143589. ** in its parent. If pNode is the root node, return -1.
  143590. */
  143591. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  143592. RtreeNode *pParent = pNode->pParent;
  143593. if( pParent ){
  143594. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  143595. }
  143596. *piIndex = -1;
  143597. return SQLITE_OK;
  143598. }
  143599. /*
  143600. ** Compare two search points. Return negative, zero, or positive if the first
  143601. ** is less than, equal to, or greater than the second.
  143602. **
  143603. ** The rScore is the primary key. Smaller rScore values come first.
  143604. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  143605. ** iLevel values coming first. In this way, if rScore is the same for all
  143606. ** SearchPoints, then iLevel becomes the deciding factor and the result
  143607. ** is a depth-first search, which is the desired default behavior.
  143608. */
  143609. static int rtreeSearchPointCompare(
  143610. const RtreeSearchPoint *pA,
  143611. const RtreeSearchPoint *pB
  143612. ){
  143613. if( pA->rScore<pB->rScore ) return -1;
  143614. if( pA->rScore>pB->rScore ) return +1;
  143615. if( pA->iLevel<pB->iLevel ) return -1;
  143616. if( pA->iLevel>pB->iLevel ) return +1;
  143617. return 0;
  143618. }
  143619. /*
  143620. ** Interchange to search points in a cursor.
  143621. */
  143622. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  143623. RtreeSearchPoint t = p->aPoint[i];
  143624. assert( i<j );
  143625. p->aPoint[i] = p->aPoint[j];
  143626. p->aPoint[j] = t;
  143627. i++; j++;
  143628. if( i<RTREE_CACHE_SZ ){
  143629. if( j>=RTREE_CACHE_SZ ){
  143630. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  143631. p->aNode[i] = 0;
  143632. }else{
  143633. RtreeNode *pTemp = p->aNode[i];
  143634. p->aNode[i] = p->aNode[j];
  143635. p->aNode[j] = pTemp;
  143636. }
  143637. }
  143638. }
  143639. /*
  143640. ** Return the search point with the lowest current score.
  143641. */
  143642. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  143643. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  143644. }
  143645. /*
  143646. ** Get the RtreeNode for the search point with the lowest score.
  143647. */
  143648. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  143649. sqlite3_int64 id;
  143650. int ii = 1 - pCur->bPoint;
  143651. assert( ii==0 || ii==1 );
  143652. assert( pCur->bPoint || pCur->nPoint );
  143653. if( pCur->aNode[ii]==0 ){
  143654. assert( pRC!=0 );
  143655. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  143656. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  143657. }
  143658. return pCur->aNode[ii];
  143659. }
  143660. /*
  143661. ** Push a new element onto the priority queue
  143662. */
  143663. static RtreeSearchPoint *rtreeEnqueue(
  143664. RtreeCursor *pCur, /* The cursor */
  143665. RtreeDValue rScore, /* Score for the new search point */
  143666. u8 iLevel /* Level for the new search point */
  143667. ){
  143668. int i, j;
  143669. RtreeSearchPoint *pNew;
  143670. if( pCur->nPoint>=pCur->nPointAlloc ){
  143671. int nNew = pCur->nPointAlloc*2 + 8;
  143672. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  143673. if( pNew==0 ) return 0;
  143674. pCur->aPoint = pNew;
  143675. pCur->nPointAlloc = nNew;
  143676. }
  143677. i = pCur->nPoint++;
  143678. pNew = pCur->aPoint + i;
  143679. pNew->rScore = rScore;
  143680. pNew->iLevel = iLevel;
  143681. assert( iLevel<=RTREE_MAX_DEPTH );
  143682. while( i>0 ){
  143683. RtreeSearchPoint *pParent;
  143684. j = (i-1)/2;
  143685. pParent = pCur->aPoint + j;
  143686. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  143687. rtreeSearchPointSwap(pCur, j, i);
  143688. i = j;
  143689. pNew = pParent;
  143690. }
  143691. return pNew;
  143692. }
  143693. /*
  143694. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  143695. ** NULL if malloc fails.
  143696. */
  143697. static RtreeSearchPoint *rtreeSearchPointNew(
  143698. RtreeCursor *pCur, /* The cursor */
  143699. RtreeDValue rScore, /* Score for the new search point */
  143700. u8 iLevel /* Level for the new search point */
  143701. ){
  143702. RtreeSearchPoint *pNew, *pFirst;
  143703. pFirst = rtreeSearchPointFirst(pCur);
  143704. pCur->anQueue[iLevel]++;
  143705. if( pFirst==0
  143706. || pFirst->rScore>rScore
  143707. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  143708. ){
  143709. if( pCur->bPoint ){
  143710. int ii;
  143711. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  143712. if( pNew==0 ) return 0;
  143713. ii = (int)(pNew - pCur->aPoint) + 1;
  143714. if( ii<RTREE_CACHE_SZ ){
  143715. assert( pCur->aNode[ii]==0 );
  143716. pCur->aNode[ii] = pCur->aNode[0];
  143717. }else{
  143718. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  143719. }
  143720. pCur->aNode[0] = 0;
  143721. *pNew = pCur->sPoint;
  143722. }
  143723. pCur->sPoint.rScore = rScore;
  143724. pCur->sPoint.iLevel = iLevel;
  143725. pCur->bPoint = 1;
  143726. return &pCur->sPoint;
  143727. }else{
  143728. return rtreeEnqueue(pCur, rScore, iLevel);
  143729. }
  143730. }
  143731. #if 0
  143732. /* Tracing routines for the RtreeSearchPoint queue */
  143733. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  143734. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  143735. printf(" %d.%05lld.%02d %g %d",
  143736. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  143737. );
  143738. idx++;
  143739. if( idx<RTREE_CACHE_SZ ){
  143740. printf(" %p\n", pCur->aNode[idx]);
  143741. }else{
  143742. printf("\n");
  143743. }
  143744. }
  143745. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  143746. int ii;
  143747. printf("=== %9s ", zPrefix);
  143748. if( pCur->bPoint ){
  143749. tracePoint(&pCur->sPoint, -1, pCur);
  143750. }
  143751. for(ii=0; ii<pCur->nPoint; ii++){
  143752. if( ii>0 || pCur->bPoint ) printf(" ");
  143753. tracePoint(&pCur->aPoint[ii], ii, pCur);
  143754. }
  143755. }
  143756. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  143757. #else
  143758. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  143759. #endif
  143760. /* Remove the search point with the lowest current score.
  143761. */
  143762. static void rtreeSearchPointPop(RtreeCursor *p){
  143763. int i, j, k, n;
  143764. i = 1 - p->bPoint;
  143765. assert( i==0 || i==1 );
  143766. if( p->aNode[i] ){
  143767. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  143768. p->aNode[i] = 0;
  143769. }
  143770. if( p->bPoint ){
  143771. p->anQueue[p->sPoint.iLevel]--;
  143772. p->bPoint = 0;
  143773. }else if( p->nPoint ){
  143774. p->anQueue[p->aPoint[0].iLevel]--;
  143775. n = --p->nPoint;
  143776. p->aPoint[0] = p->aPoint[n];
  143777. if( n<RTREE_CACHE_SZ-1 ){
  143778. p->aNode[1] = p->aNode[n+1];
  143779. p->aNode[n+1] = 0;
  143780. }
  143781. i = 0;
  143782. while( (j = i*2+1)<n ){
  143783. k = j+1;
  143784. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  143785. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  143786. rtreeSearchPointSwap(p, i, k);
  143787. i = k;
  143788. }else{
  143789. break;
  143790. }
  143791. }else{
  143792. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  143793. rtreeSearchPointSwap(p, i, j);
  143794. i = j;
  143795. }else{
  143796. break;
  143797. }
  143798. }
  143799. }
  143800. }
  143801. }
  143802. /*
  143803. ** Continue the search on cursor pCur until the front of the queue
  143804. ** contains an entry suitable for returning as a result-set row,
  143805. ** or until the RtreeSearchPoint queue is empty, indicating that the
  143806. ** query has completed.
  143807. */
  143808. static int rtreeStepToLeaf(RtreeCursor *pCur){
  143809. RtreeSearchPoint *p;
  143810. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  143811. RtreeNode *pNode;
  143812. int eWithin;
  143813. int rc = SQLITE_OK;
  143814. int nCell;
  143815. int nConstraint = pCur->nConstraint;
  143816. int ii;
  143817. int eInt;
  143818. RtreeSearchPoint x;
  143819. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  143820. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  143821. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  143822. if( rc ) return rc;
  143823. nCell = NCELL(pNode);
  143824. assert( nCell<200 );
  143825. while( p->iCell<nCell ){
  143826. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  143827. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  143828. eWithin = FULLY_WITHIN;
  143829. for(ii=0; ii<nConstraint; ii++){
  143830. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  143831. if( pConstraint->op>=RTREE_MATCH ){
  143832. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  143833. &rScore, &eWithin);
  143834. if( rc ) return rc;
  143835. }else if( p->iLevel==1 ){
  143836. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  143837. }else{
  143838. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  143839. }
  143840. if( eWithin==NOT_WITHIN ) break;
  143841. }
  143842. p->iCell++;
  143843. if( eWithin==NOT_WITHIN ) continue;
  143844. x.iLevel = p->iLevel - 1;
  143845. if( x.iLevel ){
  143846. x.id = readInt64(pCellData);
  143847. x.iCell = 0;
  143848. }else{
  143849. x.id = p->id;
  143850. x.iCell = p->iCell - 1;
  143851. }
  143852. if( p->iCell>=nCell ){
  143853. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  143854. rtreeSearchPointPop(pCur);
  143855. }
  143856. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  143857. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  143858. if( p==0 ) return SQLITE_NOMEM;
  143859. p->eWithin = eWithin;
  143860. p->id = x.id;
  143861. p->iCell = x.iCell;
  143862. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  143863. break;
  143864. }
  143865. if( p->iCell>=nCell ){
  143866. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  143867. rtreeSearchPointPop(pCur);
  143868. }
  143869. }
  143870. pCur->atEOF = p==0;
  143871. return SQLITE_OK;
  143872. }
  143873. /*
  143874. ** Rtree virtual table module xNext method.
  143875. */
  143876. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  143877. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  143878. int rc = SQLITE_OK;
  143879. /* Move to the next entry that matches the configured constraints. */
  143880. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  143881. rtreeSearchPointPop(pCsr);
  143882. rc = rtreeStepToLeaf(pCsr);
  143883. return rc;
  143884. }
  143885. /*
  143886. ** Rtree virtual table module xRowid method.
  143887. */
  143888. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  143889. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  143890. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  143891. int rc = SQLITE_OK;
  143892. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  143893. if( rc==SQLITE_OK && p ){
  143894. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  143895. }
  143896. return rc;
  143897. }
  143898. /*
  143899. ** Rtree virtual table module xColumn method.
  143900. */
  143901. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  143902. Rtree *pRtree = (Rtree *)cur->pVtab;
  143903. RtreeCursor *pCsr = (RtreeCursor *)cur;
  143904. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  143905. RtreeCoord c;
  143906. int rc = SQLITE_OK;
  143907. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  143908. if( rc ) return rc;
  143909. if( p==0 ) return SQLITE_OK;
  143910. if( i==0 ){
  143911. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  143912. }else{
  143913. if( rc ) return rc;
  143914. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  143915. #ifndef SQLITE_RTREE_INT_ONLY
  143916. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  143917. sqlite3_result_double(ctx, c.f);
  143918. }else
  143919. #endif
  143920. {
  143921. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  143922. sqlite3_result_int(ctx, c.i);
  143923. }
  143924. }
  143925. return SQLITE_OK;
  143926. }
  143927. /*
  143928. ** Use nodeAcquire() to obtain the leaf node containing the record with
  143929. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  143930. ** return SQLITE_OK. If there is no such record in the table, set
  143931. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  143932. ** to zero and return an SQLite error code.
  143933. */
  143934. static int findLeafNode(
  143935. Rtree *pRtree, /* RTree to search */
  143936. i64 iRowid, /* The rowid searching for */
  143937. RtreeNode **ppLeaf, /* Write the node here */
  143938. sqlite3_int64 *piNode /* Write the node-id here */
  143939. ){
  143940. int rc;
  143941. *ppLeaf = 0;
  143942. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  143943. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  143944. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  143945. if( piNode ) *piNode = iNode;
  143946. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  143947. sqlite3_reset(pRtree->pReadRowid);
  143948. }else{
  143949. rc = sqlite3_reset(pRtree->pReadRowid);
  143950. }
  143951. return rc;
  143952. }
  143953. /*
  143954. ** This function is called to configure the RtreeConstraint object passed
  143955. ** as the second argument for a MATCH constraint. The value passed as the
  143956. ** first argument to this function is the right-hand operand to the MATCH
  143957. ** operator.
  143958. */
  143959. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  143960. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  143961. sqlite3_rtree_query_info *pInfo; /* Callback information */
  143962. int nBlob; /* Size of the geometry function blob */
  143963. int nExpected; /* Expected size of the BLOB */
  143964. /* Check that value is actually a blob. */
  143965. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  143966. /* Check that the blob is roughly the right size. */
  143967. nBlob = sqlite3_value_bytes(pValue);
  143968. if( nBlob<(int)sizeof(RtreeMatchArg) ){
  143969. return SQLITE_ERROR;
  143970. }
  143971. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  143972. if( !pInfo ) return SQLITE_NOMEM;
  143973. memset(pInfo, 0, sizeof(*pInfo));
  143974. pBlob = (RtreeMatchArg*)&pInfo[1];
  143975. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  143976. nExpected = (int)(sizeof(RtreeMatchArg) +
  143977. pBlob->nParam*sizeof(sqlite3_value*) +
  143978. (pBlob->nParam-1)*sizeof(RtreeDValue));
  143979. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  143980. sqlite3_free(pInfo);
  143981. return SQLITE_ERROR;
  143982. }
  143983. pInfo->pContext = pBlob->cb.pContext;
  143984. pInfo->nParam = pBlob->nParam;
  143985. pInfo->aParam = pBlob->aParam;
  143986. pInfo->apSqlParam = pBlob->apSqlParam;
  143987. if( pBlob->cb.xGeom ){
  143988. pCons->u.xGeom = pBlob->cb.xGeom;
  143989. }else{
  143990. pCons->op = RTREE_QUERY;
  143991. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  143992. }
  143993. pCons->pInfo = pInfo;
  143994. return SQLITE_OK;
  143995. }
  143996. /*
  143997. ** Rtree virtual table module xFilter method.
  143998. */
  143999. static int rtreeFilter(
  144000. sqlite3_vtab_cursor *pVtabCursor,
  144001. int idxNum, const char *idxStr,
  144002. int argc, sqlite3_value **argv
  144003. ){
  144004. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  144005. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  144006. RtreeNode *pRoot = 0;
  144007. int ii;
  144008. int rc = SQLITE_OK;
  144009. int iCell = 0;
  144010. rtreeReference(pRtree);
  144011. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  144012. freeCursorConstraints(pCsr);
  144013. sqlite3_free(pCsr->aPoint);
  144014. memset(pCsr, 0, sizeof(RtreeCursor));
  144015. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  144016. pCsr->iStrategy = idxNum;
  144017. if( idxNum==1 ){
  144018. /* Special case - lookup by rowid. */
  144019. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  144020. RtreeSearchPoint *p; /* Search point for the the leaf */
  144021. i64 iRowid = sqlite3_value_int64(argv[0]);
  144022. i64 iNode = 0;
  144023. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  144024. if( rc==SQLITE_OK && pLeaf!=0 ){
  144025. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  144026. assert( p!=0 ); /* Always returns pCsr->sPoint */
  144027. pCsr->aNode[0] = pLeaf;
  144028. p->id = iNode;
  144029. p->eWithin = PARTLY_WITHIN;
  144030. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  144031. p->iCell = iCell;
  144032. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  144033. }else{
  144034. pCsr->atEOF = 1;
  144035. }
  144036. }else{
  144037. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  144038. ** with the configured constraints.
  144039. */
  144040. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  144041. if( rc==SQLITE_OK && argc>0 ){
  144042. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  144043. pCsr->nConstraint = argc;
  144044. if( !pCsr->aConstraint ){
  144045. rc = SQLITE_NOMEM;
  144046. }else{
  144047. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  144048. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  144049. assert( (idxStr==0 && argc==0)
  144050. || (idxStr && (int)strlen(idxStr)==argc*2) );
  144051. for(ii=0; ii<argc; ii++){
  144052. RtreeConstraint *p = &pCsr->aConstraint[ii];
  144053. p->op = idxStr[ii*2];
  144054. p->iCoord = idxStr[ii*2+1]-'0';
  144055. if( p->op>=RTREE_MATCH ){
  144056. /* A MATCH operator. The right-hand-side must be a blob that
  144057. ** can be cast into an RtreeMatchArg object. One created using
  144058. ** an sqlite3_rtree_geometry_callback() SQL user function.
  144059. */
  144060. rc = deserializeGeometry(argv[ii], p);
  144061. if( rc!=SQLITE_OK ){
  144062. break;
  144063. }
  144064. p->pInfo->nCoord = pRtree->nDim*2;
  144065. p->pInfo->anQueue = pCsr->anQueue;
  144066. p->pInfo->mxLevel = pRtree->iDepth + 1;
  144067. }else{
  144068. #ifdef SQLITE_RTREE_INT_ONLY
  144069. p->u.rValue = sqlite3_value_int64(argv[ii]);
  144070. #else
  144071. p->u.rValue = sqlite3_value_double(argv[ii]);
  144072. #endif
  144073. }
  144074. }
  144075. }
  144076. }
  144077. if( rc==SQLITE_OK ){
  144078. RtreeSearchPoint *pNew;
  144079. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
  144080. if( pNew==0 ) return SQLITE_NOMEM;
  144081. pNew->id = 1;
  144082. pNew->iCell = 0;
  144083. pNew->eWithin = PARTLY_WITHIN;
  144084. assert( pCsr->bPoint==1 );
  144085. pCsr->aNode[0] = pRoot;
  144086. pRoot = 0;
  144087. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  144088. rc = rtreeStepToLeaf(pCsr);
  144089. }
  144090. }
  144091. nodeRelease(pRtree, pRoot);
  144092. rtreeRelease(pRtree);
  144093. return rc;
  144094. }
  144095. /*
  144096. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  144097. ** extension is currently being used by a version of SQLite too old to
  144098. ** support estimatedRows. In that case this function is a no-op.
  144099. */
  144100. static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  144101. #if SQLITE_VERSION_NUMBER>=3008002
  144102. if( sqlite3_libversion_number()>=3008002 ){
  144103. pIdxInfo->estimatedRows = nRow;
  144104. }
  144105. #endif
  144106. }
  144107. /*
  144108. ** Rtree virtual table module xBestIndex method. There are three
  144109. ** table scan strategies to choose from (in order from most to
  144110. ** least desirable):
  144111. **
  144112. ** idxNum idxStr Strategy
  144113. ** ------------------------------------------------
  144114. ** 1 Unused Direct lookup by rowid.
  144115. ** 2 See below R-tree query or full-table scan.
  144116. ** ------------------------------------------------
  144117. **
  144118. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  144119. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  144120. ** constraint used. The first two bytes of idxStr correspond to
  144121. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  144122. ** (argvIndex==1) etc.
  144123. **
  144124. ** The first of each pair of bytes in idxStr identifies the constraint
  144125. ** operator as follows:
  144126. **
  144127. ** Operator Byte Value
  144128. ** ----------------------
  144129. ** = 0x41 ('A')
  144130. ** <= 0x42 ('B')
  144131. ** < 0x43 ('C')
  144132. ** >= 0x44 ('D')
  144133. ** > 0x45 ('E')
  144134. ** MATCH 0x46 ('F')
  144135. ** ----------------------
  144136. **
  144137. ** The second of each pair of bytes identifies the coordinate column
  144138. ** to which the constraint applies. The leftmost coordinate column
  144139. ** is 'a', the second from the left 'b' etc.
  144140. */
  144141. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  144142. Rtree *pRtree = (Rtree*)tab;
  144143. int rc = SQLITE_OK;
  144144. int ii;
  144145. int bMatch = 0; /* True if there exists a MATCH constraint */
  144146. i64 nRow; /* Estimated rows returned by this scan */
  144147. int iIdx = 0;
  144148. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  144149. memset(zIdxStr, 0, sizeof(zIdxStr));
  144150. /* Check if there exists a MATCH constraint - even an unusable one. If there
  144151. ** is, do not consider the lookup-by-rowid plan as using such a plan would
  144152. ** require the VDBE to evaluate the MATCH constraint, which is not currently
  144153. ** possible. */
  144154. for(ii=0; ii<pIdxInfo->nConstraint; ii++){
  144155. if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  144156. bMatch = 1;
  144157. }
  144158. }
  144159. assert( pIdxInfo->idxStr==0 );
  144160. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  144161. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  144162. if( bMatch==0 && p->usable
  144163. && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
  144164. ){
  144165. /* We have an equality constraint on the rowid. Use strategy 1. */
  144166. int jj;
  144167. for(jj=0; jj<ii; jj++){
  144168. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  144169. pIdxInfo->aConstraintUsage[jj].omit = 0;
  144170. }
  144171. pIdxInfo->idxNum = 1;
  144172. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  144173. pIdxInfo->aConstraintUsage[jj].omit = 1;
  144174. /* This strategy involves a two rowid lookups on an B-Tree structures
  144175. ** and then a linear search of an R-Tree node. This should be
  144176. ** considered almost as quick as a direct rowid lookup (for which
  144177. ** sqlite uses an internal cost of 0.0). It is expected to return
  144178. ** a single row.
  144179. */
  144180. pIdxInfo->estimatedCost = 30.0;
  144181. setEstimatedRows(pIdxInfo, 1);
  144182. return SQLITE_OK;
  144183. }
  144184. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  144185. u8 op;
  144186. switch( p->op ){
  144187. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  144188. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  144189. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  144190. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  144191. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  144192. default:
  144193. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  144194. op = RTREE_MATCH;
  144195. break;
  144196. }
  144197. zIdxStr[iIdx++] = op;
  144198. zIdxStr[iIdx++] = p->iColumn - 1 + '0';
  144199. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  144200. pIdxInfo->aConstraintUsage[ii].omit = 1;
  144201. }
  144202. }
  144203. pIdxInfo->idxNum = 2;
  144204. pIdxInfo->needToFreeIdxStr = 1;
  144205. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  144206. return SQLITE_NOMEM;
  144207. }
  144208. nRow = pRtree->nRowEst / (iIdx + 1);
  144209. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  144210. setEstimatedRows(pIdxInfo, nRow);
  144211. return rc;
  144212. }
  144213. /*
  144214. ** Return the N-dimensional volumn of the cell stored in *p.
  144215. */
  144216. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  144217. RtreeDValue area = (RtreeDValue)1;
  144218. int ii;
  144219. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  144220. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  144221. }
  144222. return area;
  144223. }
  144224. /*
  144225. ** Return the margin length of cell p. The margin length is the sum
  144226. ** of the objects size in each dimension.
  144227. */
  144228. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  144229. RtreeDValue margin = (RtreeDValue)0;
  144230. int ii;
  144231. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  144232. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  144233. }
  144234. return margin;
  144235. }
  144236. /*
  144237. ** Store the union of cells p1 and p2 in p1.
  144238. */
  144239. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  144240. int ii;
  144241. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  144242. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  144243. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  144244. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  144245. }
  144246. }else{
  144247. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  144248. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  144249. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  144250. }
  144251. }
  144252. }
  144253. /*
  144254. ** Return true if the area covered by p2 is a subset of the area covered
  144255. ** by p1. False otherwise.
  144256. */
  144257. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  144258. int ii;
  144259. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  144260. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  144261. RtreeCoord *a1 = &p1->aCoord[ii];
  144262. RtreeCoord *a2 = &p2->aCoord[ii];
  144263. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  144264. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  144265. ){
  144266. return 0;
  144267. }
  144268. }
  144269. return 1;
  144270. }
  144271. /*
  144272. ** Return the amount cell p would grow by if it were unioned with pCell.
  144273. */
  144274. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  144275. RtreeDValue area;
  144276. RtreeCell cell;
  144277. memcpy(&cell, p, sizeof(RtreeCell));
  144278. area = cellArea(pRtree, &cell);
  144279. cellUnion(pRtree, &cell, pCell);
  144280. return (cellArea(pRtree, &cell)-area);
  144281. }
  144282. static RtreeDValue cellOverlap(
  144283. Rtree *pRtree,
  144284. RtreeCell *p,
  144285. RtreeCell *aCell,
  144286. int nCell
  144287. ){
  144288. int ii;
  144289. RtreeDValue overlap = RTREE_ZERO;
  144290. for(ii=0; ii<nCell; ii++){
  144291. int jj;
  144292. RtreeDValue o = (RtreeDValue)1;
  144293. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  144294. RtreeDValue x1, x2;
  144295. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  144296. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  144297. if( x2<x1 ){
  144298. o = (RtreeDValue)0;
  144299. break;
  144300. }else{
  144301. o = o * (x2-x1);
  144302. }
  144303. }
  144304. overlap += o;
  144305. }
  144306. return overlap;
  144307. }
  144308. /*
  144309. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  144310. ** ChooseSubTree in r*tree terminology.
  144311. */
  144312. static int ChooseLeaf(
  144313. Rtree *pRtree, /* Rtree table */
  144314. RtreeCell *pCell, /* Cell to insert into rtree */
  144315. int iHeight, /* Height of sub-tree rooted at pCell */
  144316. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  144317. ){
  144318. int rc;
  144319. int ii;
  144320. RtreeNode *pNode;
  144321. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  144322. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  144323. int iCell;
  144324. sqlite3_int64 iBest = 0;
  144325. RtreeDValue fMinGrowth = RTREE_ZERO;
  144326. RtreeDValue fMinArea = RTREE_ZERO;
  144327. int nCell = NCELL(pNode);
  144328. RtreeCell cell;
  144329. RtreeNode *pChild;
  144330. RtreeCell *aCell = 0;
  144331. /* Select the child node which will be enlarged the least if pCell
  144332. ** is inserted into it. Resolve ties by choosing the entry with
  144333. ** the smallest area.
  144334. */
  144335. for(iCell=0; iCell<nCell; iCell++){
  144336. int bBest = 0;
  144337. RtreeDValue growth;
  144338. RtreeDValue area;
  144339. nodeGetCell(pRtree, pNode, iCell, &cell);
  144340. growth = cellGrowth(pRtree, &cell, pCell);
  144341. area = cellArea(pRtree, &cell);
  144342. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  144343. bBest = 1;
  144344. }
  144345. if( bBest ){
  144346. fMinGrowth = growth;
  144347. fMinArea = area;
  144348. iBest = cell.iRowid;
  144349. }
  144350. }
  144351. sqlite3_free(aCell);
  144352. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  144353. nodeRelease(pRtree, pNode);
  144354. pNode = pChild;
  144355. }
  144356. *ppLeaf = pNode;
  144357. return rc;
  144358. }
  144359. /*
  144360. ** A cell with the same content as pCell has just been inserted into
  144361. ** the node pNode. This function updates the bounding box cells in
  144362. ** all ancestor elements.
  144363. */
  144364. static int AdjustTree(
  144365. Rtree *pRtree, /* Rtree table */
  144366. RtreeNode *pNode, /* Adjust ancestry of this node. */
  144367. RtreeCell *pCell /* This cell was just inserted */
  144368. ){
  144369. RtreeNode *p = pNode;
  144370. while( p->pParent ){
  144371. RtreeNode *pParent = p->pParent;
  144372. RtreeCell cell;
  144373. int iCell;
  144374. if( nodeParentIndex(pRtree, p, &iCell) ){
  144375. return SQLITE_CORRUPT_VTAB;
  144376. }
  144377. nodeGetCell(pRtree, pParent, iCell, &cell);
  144378. if( !cellContains(pRtree, &cell, pCell) ){
  144379. cellUnion(pRtree, &cell, pCell);
  144380. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  144381. }
  144382. p = pParent;
  144383. }
  144384. return SQLITE_OK;
  144385. }
  144386. /*
  144387. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  144388. */
  144389. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  144390. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  144391. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  144392. sqlite3_step(pRtree->pWriteRowid);
  144393. return sqlite3_reset(pRtree->pWriteRowid);
  144394. }
  144395. /*
  144396. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  144397. */
  144398. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  144399. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  144400. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  144401. sqlite3_step(pRtree->pWriteParent);
  144402. return sqlite3_reset(pRtree->pWriteParent);
  144403. }
  144404. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  144405. /*
  144406. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  144407. ** nIdx. The aIdx array contains the set of integers from 0 to
  144408. ** (nIdx-1) in no particular order. This function sorts the values
  144409. ** in aIdx according to the indexed values in aDistance. For
  144410. ** example, assuming the inputs:
  144411. **
  144412. ** aIdx = { 0, 1, 2, 3 }
  144413. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  144414. **
  144415. ** this function sets the aIdx array to contain:
  144416. **
  144417. ** aIdx = { 0, 1, 2, 3 }
  144418. **
  144419. ** The aSpare array is used as temporary working space by the
  144420. ** sorting algorithm.
  144421. */
  144422. static void SortByDistance(
  144423. int *aIdx,
  144424. int nIdx,
  144425. RtreeDValue *aDistance,
  144426. int *aSpare
  144427. ){
  144428. if( nIdx>1 ){
  144429. int iLeft = 0;
  144430. int iRight = 0;
  144431. int nLeft = nIdx/2;
  144432. int nRight = nIdx-nLeft;
  144433. int *aLeft = aIdx;
  144434. int *aRight = &aIdx[nLeft];
  144435. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  144436. SortByDistance(aRight, nRight, aDistance, aSpare);
  144437. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  144438. aLeft = aSpare;
  144439. while( iLeft<nLeft || iRight<nRight ){
  144440. if( iLeft==nLeft ){
  144441. aIdx[iLeft+iRight] = aRight[iRight];
  144442. iRight++;
  144443. }else if( iRight==nRight ){
  144444. aIdx[iLeft+iRight] = aLeft[iLeft];
  144445. iLeft++;
  144446. }else{
  144447. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  144448. RtreeDValue fRight = aDistance[aRight[iRight]];
  144449. if( fLeft<fRight ){
  144450. aIdx[iLeft+iRight] = aLeft[iLeft];
  144451. iLeft++;
  144452. }else{
  144453. aIdx[iLeft+iRight] = aRight[iRight];
  144454. iRight++;
  144455. }
  144456. }
  144457. }
  144458. #if 0
  144459. /* Check that the sort worked */
  144460. {
  144461. int jj;
  144462. for(jj=1; jj<nIdx; jj++){
  144463. RtreeDValue left = aDistance[aIdx[jj-1]];
  144464. RtreeDValue right = aDistance[aIdx[jj]];
  144465. assert( left<=right );
  144466. }
  144467. }
  144468. #endif
  144469. }
  144470. }
  144471. /*
  144472. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  144473. ** nIdx. The aIdx array contains the set of integers from 0 to
  144474. ** (nIdx-1) in no particular order. This function sorts the values
  144475. ** in aIdx according to dimension iDim of the cells in aCell. The
  144476. ** minimum value of dimension iDim is considered first, the
  144477. ** maximum used to break ties.
  144478. **
  144479. ** The aSpare array is used as temporary working space by the
  144480. ** sorting algorithm.
  144481. */
  144482. static void SortByDimension(
  144483. Rtree *pRtree,
  144484. int *aIdx,
  144485. int nIdx,
  144486. int iDim,
  144487. RtreeCell *aCell,
  144488. int *aSpare
  144489. ){
  144490. if( nIdx>1 ){
  144491. int iLeft = 0;
  144492. int iRight = 0;
  144493. int nLeft = nIdx/2;
  144494. int nRight = nIdx-nLeft;
  144495. int *aLeft = aIdx;
  144496. int *aRight = &aIdx[nLeft];
  144497. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  144498. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  144499. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  144500. aLeft = aSpare;
  144501. while( iLeft<nLeft || iRight<nRight ){
  144502. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  144503. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  144504. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  144505. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  144506. if( (iLeft!=nLeft) && ((iRight==nRight)
  144507. || (xleft1<xright1)
  144508. || (xleft1==xright1 && xleft2<xright2)
  144509. )){
  144510. aIdx[iLeft+iRight] = aLeft[iLeft];
  144511. iLeft++;
  144512. }else{
  144513. aIdx[iLeft+iRight] = aRight[iRight];
  144514. iRight++;
  144515. }
  144516. }
  144517. #if 0
  144518. /* Check that the sort worked */
  144519. {
  144520. int jj;
  144521. for(jj=1; jj<nIdx; jj++){
  144522. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  144523. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  144524. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  144525. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  144526. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  144527. }
  144528. }
  144529. #endif
  144530. }
  144531. }
  144532. /*
  144533. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  144534. */
  144535. static int splitNodeStartree(
  144536. Rtree *pRtree,
  144537. RtreeCell *aCell,
  144538. int nCell,
  144539. RtreeNode *pLeft,
  144540. RtreeNode *pRight,
  144541. RtreeCell *pBboxLeft,
  144542. RtreeCell *pBboxRight
  144543. ){
  144544. int **aaSorted;
  144545. int *aSpare;
  144546. int ii;
  144547. int iBestDim = 0;
  144548. int iBestSplit = 0;
  144549. RtreeDValue fBestMargin = RTREE_ZERO;
  144550. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  144551. aaSorted = (int **)sqlite3_malloc(nByte);
  144552. if( !aaSorted ){
  144553. return SQLITE_NOMEM;
  144554. }
  144555. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  144556. memset(aaSorted, 0, nByte);
  144557. for(ii=0; ii<pRtree->nDim; ii++){
  144558. int jj;
  144559. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  144560. for(jj=0; jj<nCell; jj++){
  144561. aaSorted[ii][jj] = jj;
  144562. }
  144563. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  144564. }
  144565. for(ii=0; ii<pRtree->nDim; ii++){
  144566. RtreeDValue margin = RTREE_ZERO;
  144567. RtreeDValue fBestOverlap = RTREE_ZERO;
  144568. RtreeDValue fBestArea = RTREE_ZERO;
  144569. int iBestLeft = 0;
  144570. int nLeft;
  144571. for(
  144572. nLeft=RTREE_MINCELLS(pRtree);
  144573. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  144574. nLeft++
  144575. ){
  144576. RtreeCell left;
  144577. RtreeCell right;
  144578. int kk;
  144579. RtreeDValue overlap;
  144580. RtreeDValue area;
  144581. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  144582. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  144583. for(kk=1; kk<(nCell-1); kk++){
  144584. if( kk<nLeft ){
  144585. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  144586. }else{
  144587. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  144588. }
  144589. }
  144590. margin += cellMargin(pRtree, &left);
  144591. margin += cellMargin(pRtree, &right);
  144592. overlap = cellOverlap(pRtree, &left, &right, 1);
  144593. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  144594. if( (nLeft==RTREE_MINCELLS(pRtree))
  144595. || (overlap<fBestOverlap)
  144596. || (overlap==fBestOverlap && area<fBestArea)
  144597. ){
  144598. iBestLeft = nLeft;
  144599. fBestOverlap = overlap;
  144600. fBestArea = area;
  144601. }
  144602. }
  144603. if( ii==0 || margin<fBestMargin ){
  144604. iBestDim = ii;
  144605. fBestMargin = margin;
  144606. iBestSplit = iBestLeft;
  144607. }
  144608. }
  144609. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  144610. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  144611. for(ii=0; ii<nCell; ii++){
  144612. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  144613. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  144614. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  144615. nodeInsertCell(pRtree, pTarget, pCell);
  144616. cellUnion(pRtree, pBbox, pCell);
  144617. }
  144618. sqlite3_free(aaSorted);
  144619. return SQLITE_OK;
  144620. }
  144621. static int updateMapping(
  144622. Rtree *pRtree,
  144623. i64 iRowid,
  144624. RtreeNode *pNode,
  144625. int iHeight
  144626. ){
  144627. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  144628. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  144629. if( iHeight>0 ){
  144630. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  144631. if( pChild ){
  144632. nodeRelease(pRtree, pChild->pParent);
  144633. nodeReference(pNode);
  144634. pChild->pParent = pNode;
  144635. }
  144636. }
  144637. return xSetMapping(pRtree, iRowid, pNode->iNode);
  144638. }
  144639. static int SplitNode(
  144640. Rtree *pRtree,
  144641. RtreeNode *pNode,
  144642. RtreeCell *pCell,
  144643. int iHeight
  144644. ){
  144645. int i;
  144646. int newCellIsRight = 0;
  144647. int rc = SQLITE_OK;
  144648. int nCell = NCELL(pNode);
  144649. RtreeCell *aCell;
  144650. int *aiUsed;
  144651. RtreeNode *pLeft = 0;
  144652. RtreeNode *pRight = 0;
  144653. RtreeCell leftbbox;
  144654. RtreeCell rightbbox;
  144655. /* Allocate an array and populate it with a copy of pCell and
  144656. ** all cells from node pLeft. Then zero the original node.
  144657. */
  144658. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  144659. if( !aCell ){
  144660. rc = SQLITE_NOMEM;
  144661. goto splitnode_out;
  144662. }
  144663. aiUsed = (int *)&aCell[nCell+1];
  144664. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  144665. for(i=0; i<nCell; i++){
  144666. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  144667. }
  144668. nodeZero(pRtree, pNode);
  144669. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  144670. nCell++;
  144671. if( pNode->iNode==1 ){
  144672. pRight = nodeNew(pRtree, pNode);
  144673. pLeft = nodeNew(pRtree, pNode);
  144674. pRtree->iDepth++;
  144675. pNode->isDirty = 1;
  144676. writeInt16(pNode->zData, pRtree->iDepth);
  144677. }else{
  144678. pLeft = pNode;
  144679. pRight = nodeNew(pRtree, pLeft->pParent);
  144680. nodeReference(pLeft);
  144681. }
  144682. if( !pLeft || !pRight ){
  144683. rc = SQLITE_NOMEM;
  144684. goto splitnode_out;
  144685. }
  144686. memset(pLeft->zData, 0, pRtree->iNodeSize);
  144687. memset(pRight->zData, 0, pRtree->iNodeSize);
  144688. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  144689. &leftbbox, &rightbbox);
  144690. if( rc!=SQLITE_OK ){
  144691. goto splitnode_out;
  144692. }
  144693. /* Ensure both child nodes have node numbers assigned to them by calling
  144694. ** nodeWrite(). Node pRight always needs a node number, as it was created
  144695. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  144696. ** In this case avoid the all to nodeWrite().
  144697. */
  144698. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  144699. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  144700. ){
  144701. goto splitnode_out;
  144702. }
  144703. rightbbox.iRowid = pRight->iNode;
  144704. leftbbox.iRowid = pLeft->iNode;
  144705. if( pNode->iNode==1 ){
  144706. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  144707. if( rc!=SQLITE_OK ){
  144708. goto splitnode_out;
  144709. }
  144710. }else{
  144711. RtreeNode *pParent = pLeft->pParent;
  144712. int iCell;
  144713. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  144714. if( rc==SQLITE_OK ){
  144715. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  144716. rc = AdjustTree(pRtree, pParent, &leftbbox);
  144717. }
  144718. if( rc!=SQLITE_OK ){
  144719. goto splitnode_out;
  144720. }
  144721. }
  144722. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  144723. goto splitnode_out;
  144724. }
  144725. for(i=0; i<NCELL(pRight); i++){
  144726. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  144727. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  144728. if( iRowid==pCell->iRowid ){
  144729. newCellIsRight = 1;
  144730. }
  144731. if( rc!=SQLITE_OK ){
  144732. goto splitnode_out;
  144733. }
  144734. }
  144735. if( pNode->iNode==1 ){
  144736. for(i=0; i<NCELL(pLeft); i++){
  144737. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  144738. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  144739. if( rc!=SQLITE_OK ){
  144740. goto splitnode_out;
  144741. }
  144742. }
  144743. }else if( newCellIsRight==0 ){
  144744. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  144745. }
  144746. if( rc==SQLITE_OK ){
  144747. rc = nodeRelease(pRtree, pRight);
  144748. pRight = 0;
  144749. }
  144750. if( rc==SQLITE_OK ){
  144751. rc = nodeRelease(pRtree, pLeft);
  144752. pLeft = 0;
  144753. }
  144754. splitnode_out:
  144755. nodeRelease(pRtree, pRight);
  144756. nodeRelease(pRtree, pLeft);
  144757. sqlite3_free(aCell);
  144758. return rc;
  144759. }
  144760. /*
  144761. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  144762. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  144763. ** the pLeaf->pParent chain all the way up to the root node.
  144764. **
  144765. ** This operation is required when a row is deleted (or updated - an update
  144766. ** is implemented as a delete followed by an insert). SQLite provides the
  144767. ** rowid of the row to delete, which can be used to find the leaf on which
  144768. ** the entry resides (argument pLeaf). Once the leaf is located, this
  144769. ** function is called to determine its ancestry.
  144770. */
  144771. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  144772. int rc = SQLITE_OK;
  144773. RtreeNode *pChild = pLeaf;
  144774. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  144775. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  144776. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  144777. rc = sqlite3_step(pRtree->pReadParent);
  144778. if( rc==SQLITE_ROW ){
  144779. RtreeNode *pTest; /* Used to test for reference loops */
  144780. i64 iNode; /* Node number of parent node */
  144781. /* Before setting pChild->pParent, test that we are not creating a
  144782. ** loop of references (as we would if, say, pChild==pParent). We don't
  144783. ** want to do this as it leads to a memory leak when trying to delete
  144784. ** the referenced counted node structures.
  144785. */
  144786. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  144787. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  144788. if( !pTest ){
  144789. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  144790. }
  144791. }
  144792. rc = sqlite3_reset(pRtree->pReadParent);
  144793. if( rc==SQLITE_OK ) rc = rc2;
  144794. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  144795. pChild = pChild->pParent;
  144796. }
  144797. return rc;
  144798. }
  144799. static int deleteCell(Rtree *, RtreeNode *, int, int);
  144800. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  144801. int rc;
  144802. int rc2;
  144803. RtreeNode *pParent = 0;
  144804. int iCell;
  144805. assert( pNode->nRef==1 );
  144806. /* Remove the entry in the parent cell. */
  144807. rc = nodeParentIndex(pRtree, pNode, &iCell);
  144808. if( rc==SQLITE_OK ){
  144809. pParent = pNode->pParent;
  144810. pNode->pParent = 0;
  144811. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  144812. }
  144813. rc2 = nodeRelease(pRtree, pParent);
  144814. if( rc==SQLITE_OK ){
  144815. rc = rc2;
  144816. }
  144817. if( rc!=SQLITE_OK ){
  144818. return rc;
  144819. }
  144820. /* Remove the xxx_node entry. */
  144821. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  144822. sqlite3_step(pRtree->pDeleteNode);
  144823. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  144824. return rc;
  144825. }
  144826. /* Remove the xxx_parent entry. */
  144827. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  144828. sqlite3_step(pRtree->pDeleteParent);
  144829. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  144830. return rc;
  144831. }
  144832. /* Remove the node from the in-memory hash table and link it into
  144833. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  144834. */
  144835. nodeHashDelete(pRtree, pNode);
  144836. pNode->iNode = iHeight;
  144837. pNode->pNext = pRtree->pDeleted;
  144838. pNode->nRef++;
  144839. pRtree->pDeleted = pNode;
  144840. return SQLITE_OK;
  144841. }
  144842. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  144843. RtreeNode *pParent = pNode->pParent;
  144844. int rc = SQLITE_OK;
  144845. if( pParent ){
  144846. int ii;
  144847. int nCell = NCELL(pNode);
  144848. RtreeCell box; /* Bounding box for pNode */
  144849. nodeGetCell(pRtree, pNode, 0, &box);
  144850. for(ii=1; ii<nCell; ii++){
  144851. RtreeCell cell;
  144852. nodeGetCell(pRtree, pNode, ii, &cell);
  144853. cellUnion(pRtree, &box, &cell);
  144854. }
  144855. box.iRowid = pNode->iNode;
  144856. rc = nodeParentIndex(pRtree, pNode, &ii);
  144857. if( rc==SQLITE_OK ){
  144858. nodeOverwriteCell(pRtree, pParent, &box, ii);
  144859. rc = fixBoundingBox(pRtree, pParent);
  144860. }
  144861. }
  144862. return rc;
  144863. }
  144864. /*
  144865. ** Delete the cell at index iCell of node pNode. After removing the
  144866. ** cell, adjust the r-tree data structure if required.
  144867. */
  144868. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  144869. RtreeNode *pParent;
  144870. int rc;
  144871. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  144872. return rc;
  144873. }
  144874. /* Remove the cell from the node. This call just moves bytes around
  144875. ** the in-memory node image, so it cannot fail.
  144876. */
  144877. nodeDeleteCell(pRtree, pNode, iCell);
  144878. /* If the node is not the tree root and now has less than the minimum
  144879. ** number of cells, remove it from the tree. Otherwise, update the
  144880. ** cell in the parent node so that it tightly contains the updated
  144881. ** node.
  144882. */
  144883. pParent = pNode->pParent;
  144884. assert( pParent || pNode->iNode==1 );
  144885. if( pParent ){
  144886. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  144887. rc = removeNode(pRtree, pNode, iHeight);
  144888. }else{
  144889. rc = fixBoundingBox(pRtree, pNode);
  144890. }
  144891. }
  144892. return rc;
  144893. }
  144894. static int Reinsert(
  144895. Rtree *pRtree,
  144896. RtreeNode *pNode,
  144897. RtreeCell *pCell,
  144898. int iHeight
  144899. ){
  144900. int *aOrder;
  144901. int *aSpare;
  144902. RtreeCell *aCell;
  144903. RtreeDValue *aDistance;
  144904. int nCell;
  144905. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  144906. int iDim;
  144907. int ii;
  144908. int rc = SQLITE_OK;
  144909. int n;
  144910. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  144911. nCell = NCELL(pNode)+1;
  144912. n = (nCell+1)&(~1);
  144913. /* Allocate the buffers used by this operation. The allocation is
  144914. ** relinquished before this function returns.
  144915. */
  144916. aCell = (RtreeCell *)sqlite3_malloc(n * (
  144917. sizeof(RtreeCell) + /* aCell array */
  144918. sizeof(int) + /* aOrder array */
  144919. sizeof(int) + /* aSpare array */
  144920. sizeof(RtreeDValue) /* aDistance array */
  144921. ));
  144922. if( !aCell ){
  144923. return SQLITE_NOMEM;
  144924. }
  144925. aOrder = (int *)&aCell[n];
  144926. aSpare = (int *)&aOrder[n];
  144927. aDistance = (RtreeDValue *)&aSpare[n];
  144928. for(ii=0; ii<nCell; ii++){
  144929. if( ii==(nCell-1) ){
  144930. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  144931. }else{
  144932. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  144933. }
  144934. aOrder[ii] = ii;
  144935. for(iDim=0; iDim<pRtree->nDim; iDim++){
  144936. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  144937. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  144938. }
  144939. }
  144940. for(iDim=0; iDim<pRtree->nDim; iDim++){
  144941. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  144942. }
  144943. for(ii=0; ii<nCell; ii++){
  144944. aDistance[ii] = RTREE_ZERO;
  144945. for(iDim=0; iDim<pRtree->nDim; iDim++){
  144946. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  144947. DCOORD(aCell[ii].aCoord[iDim*2]));
  144948. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  144949. }
  144950. }
  144951. SortByDistance(aOrder, nCell, aDistance, aSpare);
  144952. nodeZero(pRtree, pNode);
  144953. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  144954. RtreeCell *p = &aCell[aOrder[ii]];
  144955. nodeInsertCell(pRtree, pNode, p);
  144956. if( p->iRowid==pCell->iRowid ){
  144957. if( iHeight==0 ){
  144958. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  144959. }else{
  144960. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  144961. }
  144962. }
  144963. }
  144964. if( rc==SQLITE_OK ){
  144965. rc = fixBoundingBox(pRtree, pNode);
  144966. }
  144967. for(; rc==SQLITE_OK && ii<nCell; ii++){
  144968. /* Find a node to store this cell in. pNode->iNode currently contains
  144969. ** the height of the sub-tree headed by the cell.
  144970. */
  144971. RtreeNode *pInsert;
  144972. RtreeCell *p = &aCell[aOrder[ii]];
  144973. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  144974. if( rc==SQLITE_OK ){
  144975. int rc2;
  144976. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  144977. rc2 = nodeRelease(pRtree, pInsert);
  144978. if( rc==SQLITE_OK ){
  144979. rc = rc2;
  144980. }
  144981. }
  144982. }
  144983. sqlite3_free(aCell);
  144984. return rc;
  144985. }
  144986. /*
  144987. ** Insert cell pCell into node pNode. Node pNode is the head of a
  144988. ** subtree iHeight high (leaf nodes have iHeight==0).
  144989. */
  144990. static int rtreeInsertCell(
  144991. Rtree *pRtree,
  144992. RtreeNode *pNode,
  144993. RtreeCell *pCell,
  144994. int iHeight
  144995. ){
  144996. int rc = SQLITE_OK;
  144997. if( iHeight>0 ){
  144998. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  144999. if( pChild ){
  145000. nodeRelease(pRtree, pChild->pParent);
  145001. nodeReference(pNode);
  145002. pChild->pParent = pNode;
  145003. }
  145004. }
  145005. if( nodeInsertCell(pRtree, pNode, pCell) ){
  145006. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  145007. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  145008. }else{
  145009. pRtree->iReinsertHeight = iHeight;
  145010. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  145011. }
  145012. }else{
  145013. rc = AdjustTree(pRtree, pNode, pCell);
  145014. if( rc==SQLITE_OK ){
  145015. if( iHeight==0 ){
  145016. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  145017. }else{
  145018. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  145019. }
  145020. }
  145021. }
  145022. return rc;
  145023. }
  145024. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  145025. int ii;
  145026. int rc = SQLITE_OK;
  145027. int nCell = NCELL(pNode);
  145028. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  145029. RtreeNode *pInsert;
  145030. RtreeCell cell;
  145031. nodeGetCell(pRtree, pNode, ii, &cell);
  145032. /* Find a node to store this cell in. pNode->iNode currently contains
  145033. ** the height of the sub-tree headed by the cell.
  145034. */
  145035. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  145036. if( rc==SQLITE_OK ){
  145037. int rc2;
  145038. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  145039. rc2 = nodeRelease(pRtree, pInsert);
  145040. if( rc==SQLITE_OK ){
  145041. rc = rc2;
  145042. }
  145043. }
  145044. }
  145045. return rc;
  145046. }
  145047. /*
  145048. ** Select a currently unused rowid for a new r-tree record.
  145049. */
  145050. static int newRowid(Rtree *pRtree, i64 *piRowid){
  145051. int rc;
  145052. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  145053. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  145054. sqlite3_step(pRtree->pWriteRowid);
  145055. rc = sqlite3_reset(pRtree->pWriteRowid);
  145056. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  145057. return rc;
  145058. }
  145059. /*
  145060. ** Remove the entry with rowid=iDelete from the r-tree structure.
  145061. */
  145062. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  145063. int rc; /* Return code */
  145064. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  145065. int iCell; /* Index of iDelete cell in pLeaf */
  145066. RtreeNode *pRoot; /* Root node of rtree structure */
  145067. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  145068. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  145069. /* Obtain a reference to the leaf node that contains the entry
  145070. ** about to be deleted.
  145071. */
  145072. if( rc==SQLITE_OK ){
  145073. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  145074. }
  145075. /* Delete the cell in question from the leaf node. */
  145076. if( rc==SQLITE_OK ){
  145077. int rc2;
  145078. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  145079. if( rc==SQLITE_OK ){
  145080. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  145081. }
  145082. rc2 = nodeRelease(pRtree, pLeaf);
  145083. if( rc==SQLITE_OK ){
  145084. rc = rc2;
  145085. }
  145086. }
  145087. /* Delete the corresponding entry in the <rtree>_rowid table. */
  145088. if( rc==SQLITE_OK ){
  145089. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  145090. sqlite3_step(pRtree->pDeleteRowid);
  145091. rc = sqlite3_reset(pRtree->pDeleteRowid);
  145092. }
  145093. /* Check if the root node now has exactly one child. If so, remove
  145094. ** it, schedule the contents of the child for reinsertion and
  145095. ** reduce the tree height by one.
  145096. **
  145097. ** This is equivalent to copying the contents of the child into
  145098. ** the root node (the operation that Gutman's paper says to perform
  145099. ** in this scenario).
  145100. */
  145101. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  145102. int rc2;
  145103. RtreeNode *pChild;
  145104. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  145105. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  145106. if( rc==SQLITE_OK ){
  145107. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  145108. }
  145109. rc2 = nodeRelease(pRtree, pChild);
  145110. if( rc==SQLITE_OK ) rc = rc2;
  145111. if( rc==SQLITE_OK ){
  145112. pRtree->iDepth--;
  145113. writeInt16(pRoot->zData, pRtree->iDepth);
  145114. pRoot->isDirty = 1;
  145115. }
  145116. }
  145117. /* Re-insert the contents of any underfull nodes removed from the tree. */
  145118. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  145119. if( rc==SQLITE_OK ){
  145120. rc = reinsertNodeContent(pRtree, pLeaf);
  145121. }
  145122. pRtree->pDeleted = pLeaf->pNext;
  145123. sqlite3_free(pLeaf);
  145124. }
  145125. /* Release the reference to the root node. */
  145126. if( rc==SQLITE_OK ){
  145127. rc = nodeRelease(pRtree, pRoot);
  145128. }else{
  145129. nodeRelease(pRtree, pRoot);
  145130. }
  145131. return rc;
  145132. }
  145133. /*
  145134. ** Rounding constants for float->double conversion.
  145135. */
  145136. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  145137. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  145138. #if !defined(SQLITE_RTREE_INT_ONLY)
  145139. /*
  145140. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  145141. ** while taking care to round toward negative or positive, respectively.
  145142. */
  145143. static RtreeValue rtreeValueDown(sqlite3_value *v){
  145144. double d = sqlite3_value_double(v);
  145145. float f = (float)d;
  145146. if( f>d ){
  145147. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  145148. }
  145149. return f;
  145150. }
  145151. static RtreeValue rtreeValueUp(sqlite3_value *v){
  145152. double d = sqlite3_value_double(v);
  145153. float f = (float)d;
  145154. if( f<d ){
  145155. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  145156. }
  145157. return f;
  145158. }
  145159. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  145160. /*
  145161. ** The xUpdate method for rtree module virtual tables.
  145162. */
  145163. static int rtreeUpdate(
  145164. sqlite3_vtab *pVtab,
  145165. int nData,
  145166. sqlite3_value **azData,
  145167. sqlite_int64 *pRowid
  145168. ){
  145169. Rtree *pRtree = (Rtree *)pVtab;
  145170. int rc = SQLITE_OK;
  145171. RtreeCell cell; /* New cell to insert if nData>1 */
  145172. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  145173. rtreeReference(pRtree);
  145174. assert(nData>=1);
  145175. cell.iRowid = 0; /* Used only to suppress a compiler warning */
  145176. /* Constraint handling. A write operation on an r-tree table may return
  145177. ** SQLITE_CONSTRAINT for two reasons:
  145178. **
  145179. ** 1. A duplicate rowid value, or
  145180. ** 2. The supplied data violates the "x2>=x1" constraint.
  145181. **
  145182. ** In the first case, if the conflict-handling mode is REPLACE, then
  145183. ** the conflicting row can be removed before proceeding. In the second
  145184. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  145185. ** conflict-handling mode specified by the user.
  145186. */
  145187. if( nData>1 ){
  145188. int ii;
  145189. /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
  145190. **
  145191. ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
  145192. ** with "column" that are interpreted as table constraints.
  145193. ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
  145194. ** This problem was discovered after years of use, so we silently ignore
  145195. ** these kinds of misdeclared tables to avoid breaking any legacy.
  145196. */
  145197. assert( nData<=(pRtree->nDim*2 + 3) );
  145198. #ifndef SQLITE_RTREE_INT_ONLY
  145199. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  145200. for(ii=0; ii<nData-4; ii+=2){
  145201. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  145202. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  145203. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  145204. rc = SQLITE_CONSTRAINT;
  145205. goto constraint;
  145206. }
  145207. }
  145208. }else
  145209. #endif
  145210. {
  145211. for(ii=0; ii<nData-4; ii+=2){
  145212. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  145213. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  145214. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  145215. rc = SQLITE_CONSTRAINT;
  145216. goto constraint;
  145217. }
  145218. }
  145219. }
  145220. /* If a rowid value was supplied, check if it is already present in
  145221. ** the table. If so, the constraint has failed. */
  145222. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  145223. cell.iRowid = sqlite3_value_int64(azData[2]);
  145224. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  145225. || sqlite3_value_int64(azData[0])!=cell.iRowid
  145226. ){
  145227. int steprc;
  145228. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  145229. steprc = sqlite3_step(pRtree->pReadRowid);
  145230. rc = sqlite3_reset(pRtree->pReadRowid);
  145231. if( SQLITE_ROW==steprc ){
  145232. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  145233. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  145234. }else{
  145235. rc = SQLITE_CONSTRAINT;
  145236. goto constraint;
  145237. }
  145238. }
  145239. }
  145240. bHaveRowid = 1;
  145241. }
  145242. }
  145243. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  145244. ** record to delete from the r-tree table. The following block does
  145245. ** just that.
  145246. */
  145247. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  145248. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  145249. }
  145250. /* If the azData[] array contains more than one element, elements
  145251. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  145252. ** the r-tree structure.
  145253. */
  145254. if( rc==SQLITE_OK && nData>1 ){
  145255. /* Insert the new record into the r-tree */
  145256. RtreeNode *pLeaf = 0;
  145257. /* Figure out the rowid of the new row. */
  145258. if( bHaveRowid==0 ){
  145259. rc = newRowid(pRtree, &cell.iRowid);
  145260. }
  145261. *pRowid = cell.iRowid;
  145262. if( rc==SQLITE_OK ){
  145263. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  145264. }
  145265. if( rc==SQLITE_OK ){
  145266. int rc2;
  145267. pRtree->iReinsertHeight = -1;
  145268. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  145269. rc2 = nodeRelease(pRtree, pLeaf);
  145270. if( rc==SQLITE_OK ){
  145271. rc = rc2;
  145272. }
  145273. }
  145274. }
  145275. constraint:
  145276. rtreeRelease(pRtree);
  145277. return rc;
  145278. }
  145279. /*
  145280. ** The xRename method for rtree module virtual tables.
  145281. */
  145282. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  145283. Rtree *pRtree = (Rtree *)pVtab;
  145284. int rc = SQLITE_NOMEM;
  145285. char *zSql = sqlite3_mprintf(
  145286. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  145287. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  145288. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  145289. , pRtree->zDb, pRtree->zName, zNewName
  145290. , pRtree->zDb, pRtree->zName, zNewName
  145291. , pRtree->zDb, pRtree->zName, zNewName
  145292. );
  145293. if( zSql ){
  145294. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  145295. sqlite3_free(zSql);
  145296. }
  145297. return rc;
  145298. }
  145299. /*
  145300. ** This function populates the pRtree->nRowEst variable with an estimate
  145301. ** of the number of rows in the virtual table. If possible, this is based
  145302. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  145303. */
  145304. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  145305. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  145306. char *zSql;
  145307. sqlite3_stmt *p;
  145308. int rc;
  145309. i64 nRow = 0;
  145310. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  145311. if( zSql==0 ){
  145312. rc = SQLITE_NOMEM;
  145313. }else{
  145314. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  145315. if( rc==SQLITE_OK ){
  145316. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  145317. rc = sqlite3_finalize(p);
  145318. }else if( rc!=SQLITE_NOMEM ){
  145319. rc = SQLITE_OK;
  145320. }
  145321. if( rc==SQLITE_OK ){
  145322. if( nRow==0 ){
  145323. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  145324. }else{
  145325. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  145326. }
  145327. }
  145328. sqlite3_free(zSql);
  145329. }
  145330. return rc;
  145331. }
  145332. static sqlite3_module rtreeModule = {
  145333. 0, /* iVersion */
  145334. rtreeCreate, /* xCreate - create a table */
  145335. rtreeConnect, /* xConnect - connect to an existing table */
  145336. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  145337. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  145338. rtreeDestroy, /* xDestroy - Drop a table */
  145339. rtreeOpen, /* xOpen - open a cursor */
  145340. rtreeClose, /* xClose - close a cursor */
  145341. rtreeFilter, /* xFilter - configure scan constraints */
  145342. rtreeNext, /* xNext - advance a cursor */
  145343. rtreeEof, /* xEof */
  145344. rtreeColumn, /* xColumn - read data */
  145345. rtreeRowid, /* xRowid - read data */
  145346. rtreeUpdate, /* xUpdate - write data */
  145347. 0, /* xBegin - begin transaction */
  145348. 0, /* xSync - sync transaction */
  145349. 0, /* xCommit - commit transaction */
  145350. 0, /* xRollback - rollback transaction */
  145351. 0, /* xFindFunction - function overloading */
  145352. rtreeRename, /* xRename - rename the table */
  145353. 0, /* xSavepoint */
  145354. 0, /* xRelease */
  145355. 0 /* xRollbackTo */
  145356. };
  145357. static int rtreeSqlInit(
  145358. Rtree *pRtree,
  145359. sqlite3 *db,
  145360. const char *zDb,
  145361. const char *zPrefix,
  145362. int isCreate
  145363. ){
  145364. int rc = SQLITE_OK;
  145365. #define N_STATEMENT 9
  145366. static const char *azSql[N_STATEMENT] = {
  145367. /* Read and write the xxx_node table */
  145368. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  145369. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  145370. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  145371. /* Read and write the xxx_rowid table */
  145372. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  145373. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  145374. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  145375. /* Read and write the xxx_parent table */
  145376. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  145377. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  145378. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  145379. };
  145380. sqlite3_stmt **appStmt[N_STATEMENT];
  145381. int i;
  145382. pRtree->db = db;
  145383. if( isCreate ){
  145384. char *zCreate = sqlite3_mprintf(
  145385. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  145386. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  145387. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  145388. " parentnode INTEGER);"
  145389. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  145390. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  145391. );
  145392. if( !zCreate ){
  145393. return SQLITE_NOMEM;
  145394. }
  145395. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  145396. sqlite3_free(zCreate);
  145397. if( rc!=SQLITE_OK ){
  145398. return rc;
  145399. }
  145400. }
  145401. appStmt[0] = &pRtree->pReadNode;
  145402. appStmt[1] = &pRtree->pWriteNode;
  145403. appStmt[2] = &pRtree->pDeleteNode;
  145404. appStmt[3] = &pRtree->pReadRowid;
  145405. appStmt[4] = &pRtree->pWriteRowid;
  145406. appStmt[5] = &pRtree->pDeleteRowid;
  145407. appStmt[6] = &pRtree->pReadParent;
  145408. appStmt[7] = &pRtree->pWriteParent;
  145409. appStmt[8] = &pRtree->pDeleteParent;
  145410. rc = rtreeQueryStat1(db, pRtree);
  145411. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  145412. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  145413. if( zSql ){
  145414. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  145415. }else{
  145416. rc = SQLITE_NOMEM;
  145417. }
  145418. sqlite3_free(zSql);
  145419. }
  145420. return rc;
  145421. }
  145422. /*
  145423. ** The second argument to this function contains the text of an SQL statement
  145424. ** that returns a single integer value. The statement is compiled and executed
  145425. ** using database connection db. If successful, the integer value returned
  145426. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  145427. ** code is returned and the value of *piVal after returning is not defined.
  145428. */
  145429. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  145430. int rc = SQLITE_NOMEM;
  145431. if( zSql ){
  145432. sqlite3_stmt *pStmt = 0;
  145433. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  145434. if( rc==SQLITE_OK ){
  145435. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  145436. *piVal = sqlite3_column_int(pStmt, 0);
  145437. }
  145438. rc = sqlite3_finalize(pStmt);
  145439. }
  145440. }
  145441. return rc;
  145442. }
  145443. /*
  145444. ** This function is called from within the xConnect() or xCreate() method to
  145445. ** determine the node-size used by the rtree table being created or connected
  145446. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  145447. ** Otherwise, an SQLite error code is returned.
  145448. **
  145449. ** If this function is being called as part of an xConnect(), then the rtree
  145450. ** table already exists. In this case the node-size is determined by inspecting
  145451. ** the root node of the tree.
  145452. **
  145453. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  145454. ** This ensures that each node is stored on a single database page. If the
  145455. ** database page-size is so large that more than RTREE_MAXCELLS entries
  145456. ** would fit in a single node, use a smaller node-size.
  145457. */
  145458. static int getNodeSize(
  145459. sqlite3 *db, /* Database handle */
  145460. Rtree *pRtree, /* Rtree handle */
  145461. int isCreate, /* True for xCreate, false for xConnect */
  145462. char **pzErr /* OUT: Error message, if any */
  145463. ){
  145464. int rc;
  145465. char *zSql;
  145466. if( isCreate ){
  145467. int iPageSize = 0;
  145468. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  145469. rc = getIntFromStmt(db, zSql, &iPageSize);
  145470. if( rc==SQLITE_OK ){
  145471. pRtree->iNodeSize = iPageSize-64;
  145472. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  145473. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  145474. }
  145475. }else{
  145476. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  145477. }
  145478. }else{
  145479. zSql = sqlite3_mprintf(
  145480. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  145481. pRtree->zDb, pRtree->zName
  145482. );
  145483. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  145484. if( rc!=SQLITE_OK ){
  145485. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  145486. }
  145487. }
  145488. sqlite3_free(zSql);
  145489. return rc;
  145490. }
  145491. /*
  145492. ** This function is the implementation of both the xConnect and xCreate
  145493. ** methods of the r-tree virtual table.
  145494. **
  145495. ** argv[0] -> module name
  145496. ** argv[1] -> database name
  145497. ** argv[2] -> table name
  145498. ** argv[...] -> column names...
  145499. */
  145500. static int rtreeInit(
  145501. sqlite3 *db, /* Database connection */
  145502. void *pAux, /* One of the RTREE_COORD_* constants */
  145503. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  145504. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  145505. char **pzErr, /* OUT: Error message, if any */
  145506. int isCreate /* True for xCreate, false for xConnect */
  145507. ){
  145508. int rc = SQLITE_OK;
  145509. Rtree *pRtree;
  145510. int nDb; /* Length of string argv[1] */
  145511. int nName; /* Length of string argv[2] */
  145512. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  145513. const char *aErrMsg[] = {
  145514. 0, /* 0 */
  145515. "Wrong number of columns for an rtree table", /* 1 */
  145516. "Too few columns for an rtree table", /* 2 */
  145517. "Too many columns for an rtree table" /* 3 */
  145518. };
  145519. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  145520. if( aErrMsg[iErr] ){
  145521. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  145522. return SQLITE_ERROR;
  145523. }
  145524. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  145525. /* Allocate the sqlite3_vtab structure */
  145526. nDb = (int)strlen(argv[1]);
  145527. nName = (int)strlen(argv[2]);
  145528. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  145529. if( !pRtree ){
  145530. return SQLITE_NOMEM;
  145531. }
  145532. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  145533. pRtree->nBusy = 1;
  145534. pRtree->base.pModule = &rtreeModule;
  145535. pRtree->zDb = (char *)&pRtree[1];
  145536. pRtree->zName = &pRtree->zDb[nDb+1];
  145537. pRtree->nDim = (argc-4)/2;
  145538. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  145539. pRtree->eCoordType = eCoordType;
  145540. memcpy(pRtree->zDb, argv[1], nDb);
  145541. memcpy(pRtree->zName, argv[2], nName);
  145542. /* Figure out the node size to use. */
  145543. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  145544. /* Create/Connect to the underlying relational database schema. If
  145545. ** that is successful, call sqlite3_declare_vtab() to configure
  145546. ** the r-tree table schema.
  145547. */
  145548. if( rc==SQLITE_OK ){
  145549. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  145550. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  145551. }else{
  145552. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  145553. char *zTmp;
  145554. int ii;
  145555. for(ii=4; zSql && ii<argc; ii++){
  145556. zTmp = zSql;
  145557. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  145558. sqlite3_free(zTmp);
  145559. }
  145560. if( zSql ){
  145561. zTmp = zSql;
  145562. zSql = sqlite3_mprintf("%s);", zTmp);
  145563. sqlite3_free(zTmp);
  145564. }
  145565. if( !zSql ){
  145566. rc = SQLITE_NOMEM;
  145567. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  145568. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  145569. }
  145570. sqlite3_free(zSql);
  145571. }
  145572. }
  145573. if( rc==SQLITE_OK ){
  145574. *ppVtab = (sqlite3_vtab *)pRtree;
  145575. }else{
  145576. assert( *ppVtab==0 );
  145577. assert( pRtree->nBusy==1 );
  145578. rtreeRelease(pRtree);
  145579. }
  145580. return rc;
  145581. }
  145582. /*
  145583. ** Implementation of a scalar function that decodes r-tree nodes to
  145584. ** human readable strings. This can be used for debugging and analysis.
  145585. **
  145586. ** The scalar function takes two arguments: (1) the number of dimensions
  145587. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  145588. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  145589. ** deserialize all nodes, a statement like:
  145590. **
  145591. ** SELECT rtreenode(2, data) FROM rt_node;
  145592. **
  145593. ** The human readable string takes the form of a Tcl list with one
  145594. ** entry for each cell in the r-tree node. Each entry is itself a
  145595. ** list, containing the 8-byte rowid/pageno followed by the
  145596. ** <num-dimension>*2 coordinates.
  145597. */
  145598. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  145599. char *zText = 0;
  145600. RtreeNode node;
  145601. Rtree tree;
  145602. int ii;
  145603. UNUSED_PARAMETER(nArg);
  145604. memset(&node, 0, sizeof(RtreeNode));
  145605. memset(&tree, 0, sizeof(Rtree));
  145606. tree.nDim = sqlite3_value_int(apArg[0]);
  145607. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  145608. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  145609. for(ii=0; ii<NCELL(&node); ii++){
  145610. char zCell[512];
  145611. int nCell = 0;
  145612. RtreeCell cell;
  145613. int jj;
  145614. nodeGetCell(&tree, &node, ii, &cell);
  145615. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  145616. nCell = (int)strlen(zCell);
  145617. for(jj=0; jj<tree.nDim*2; jj++){
  145618. #ifndef SQLITE_RTREE_INT_ONLY
  145619. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  145620. (double)cell.aCoord[jj].f);
  145621. #else
  145622. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  145623. cell.aCoord[jj].i);
  145624. #endif
  145625. nCell = (int)strlen(zCell);
  145626. }
  145627. if( zText ){
  145628. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  145629. sqlite3_free(zText);
  145630. zText = zTextNew;
  145631. }else{
  145632. zText = sqlite3_mprintf("{%s}", zCell);
  145633. }
  145634. }
  145635. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  145636. }
  145637. /* This routine implements an SQL function that returns the "depth" parameter
  145638. ** from the front of a blob that is an r-tree node. For example:
  145639. **
  145640. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  145641. **
  145642. ** The depth value is 0 for all nodes other than the root node, and the root
  145643. ** node always has nodeno=1, so the example above is the primary use for this
  145644. ** routine. This routine is intended for testing and analysis only.
  145645. */
  145646. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  145647. UNUSED_PARAMETER(nArg);
  145648. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  145649. || sqlite3_value_bytes(apArg[0])<2
  145650. ){
  145651. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  145652. }else{
  145653. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  145654. sqlite3_result_int(ctx, readInt16(zBlob));
  145655. }
  145656. }
  145657. /*
  145658. ** Register the r-tree module with database handle db. This creates the
  145659. ** virtual table module "rtree" and the debugging/analysis scalar
  145660. ** function "rtreenode".
  145661. */
  145662. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  145663. const int utf8 = SQLITE_UTF8;
  145664. int rc;
  145665. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  145666. if( rc==SQLITE_OK ){
  145667. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  145668. }
  145669. if( rc==SQLITE_OK ){
  145670. #ifdef SQLITE_RTREE_INT_ONLY
  145671. void *c = (void *)RTREE_COORD_INT32;
  145672. #else
  145673. void *c = (void *)RTREE_COORD_REAL32;
  145674. #endif
  145675. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  145676. }
  145677. if( rc==SQLITE_OK ){
  145678. void *c = (void *)RTREE_COORD_INT32;
  145679. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  145680. }
  145681. return rc;
  145682. }
  145683. /*
  145684. ** This routine deletes the RtreeGeomCallback object that was attached
  145685. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  145686. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  145687. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  145688. ** the corresponding SQL function is deleted.
  145689. */
  145690. static void rtreeFreeCallback(void *p){
  145691. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  145692. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  145693. sqlite3_free(p);
  145694. }
  145695. /*
  145696. ** This routine frees the BLOB that is returned by geomCallback().
  145697. */
  145698. static void rtreeMatchArgFree(void *pArg){
  145699. int i;
  145700. RtreeMatchArg *p = (RtreeMatchArg*)pArg;
  145701. for(i=0; i<p->nParam; i++){
  145702. sqlite3_value_free(p->apSqlParam[i]);
  145703. }
  145704. sqlite3_free(p);
  145705. }
  145706. /*
  145707. ** Each call to sqlite3_rtree_geometry_callback() or
  145708. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  145709. ** scalar function that is implemented by this routine.
  145710. **
  145711. ** All this function does is construct an RtreeMatchArg object that
  145712. ** contains the geometry-checking callback routines and a list of
  145713. ** parameters to this function, then return that RtreeMatchArg object
  145714. ** as a BLOB.
  145715. **
  145716. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  145717. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  145718. ** out which elements of the R-Tree should be returned by the query.
  145719. */
  145720. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  145721. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  145722. RtreeMatchArg *pBlob;
  145723. int nBlob;
  145724. int memErr = 0;
  145725. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
  145726. + nArg*sizeof(sqlite3_value*);
  145727. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  145728. if( !pBlob ){
  145729. sqlite3_result_error_nomem(ctx);
  145730. }else{
  145731. int i;
  145732. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  145733. pBlob->cb = pGeomCtx[0];
  145734. pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
  145735. pBlob->nParam = nArg;
  145736. for(i=0; i<nArg; i++){
  145737. pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
  145738. if( pBlob->apSqlParam[i]==0 ) memErr = 1;
  145739. #ifdef SQLITE_RTREE_INT_ONLY
  145740. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  145741. #else
  145742. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  145743. #endif
  145744. }
  145745. if( memErr ){
  145746. sqlite3_result_error_nomem(ctx);
  145747. rtreeMatchArgFree(pBlob);
  145748. }else{
  145749. sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
  145750. }
  145751. }
  145752. }
  145753. /*
  145754. ** Register a new geometry function for use with the r-tree MATCH operator.
  145755. */
  145756. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
  145757. sqlite3 *db, /* Register SQL function on this connection */
  145758. const char *zGeom, /* Name of the new SQL function */
  145759. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  145760. void *pContext /* Extra data associated with the callback */
  145761. ){
  145762. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  145763. /* Allocate and populate the context object. */
  145764. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  145765. if( !pGeomCtx ) return SQLITE_NOMEM;
  145766. pGeomCtx->xGeom = xGeom;
  145767. pGeomCtx->xQueryFunc = 0;
  145768. pGeomCtx->xDestructor = 0;
  145769. pGeomCtx->pContext = pContext;
  145770. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  145771. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  145772. );
  145773. }
  145774. /*
  145775. ** Register a new 2nd-generation geometry function for use with the
  145776. ** r-tree MATCH operator.
  145777. */
  145778. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
  145779. sqlite3 *db, /* Register SQL function on this connection */
  145780. const char *zQueryFunc, /* Name of new SQL function */
  145781. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  145782. void *pContext, /* Extra data passed into the callback */
  145783. void (*xDestructor)(void*) /* Destructor for the extra data */
  145784. ){
  145785. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  145786. /* Allocate and populate the context object. */
  145787. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  145788. if( !pGeomCtx ) return SQLITE_NOMEM;
  145789. pGeomCtx->xGeom = 0;
  145790. pGeomCtx->xQueryFunc = xQueryFunc;
  145791. pGeomCtx->xDestructor = xDestructor;
  145792. pGeomCtx->pContext = pContext;
  145793. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  145794. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  145795. );
  145796. }
  145797. #if !SQLITE_CORE
  145798. #ifdef _WIN32
  145799. __declspec(dllexport)
  145800. #endif
  145801. SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
  145802. sqlite3 *db,
  145803. char **pzErrMsg,
  145804. const sqlite3_api_routines *pApi
  145805. ){
  145806. SQLITE_EXTENSION_INIT2(pApi)
  145807. return sqlite3RtreeInit(db);
  145808. }
  145809. #endif
  145810. #endif
  145811. /************** End of rtree.c ***********************************************/
  145812. /************** Begin file icu.c *********************************************/
  145813. /*
  145814. ** 2007 May 6
  145815. **
  145816. ** The author disclaims copyright to this source code. In place of
  145817. ** a legal notice, here is a blessing:
  145818. **
  145819. ** May you do good and not evil.
  145820. ** May you find forgiveness for yourself and forgive others.
  145821. ** May you share freely, never taking more than you give.
  145822. **
  145823. *************************************************************************
  145824. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  145825. **
  145826. ** This file implements an integration between the ICU library
  145827. ** ("International Components for Unicode", an open-source library
  145828. ** for handling unicode data) and SQLite. The integration uses
  145829. ** ICU to provide the following to SQLite:
  145830. **
  145831. ** * An implementation of the SQL regexp() function (and hence REGEXP
  145832. ** operator) using the ICU uregex_XX() APIs.
  145833. **
  145834. ** * Implementations of the SQL scalar upper() and lower() functions
  145835. ** for case mapping.
  145836. **
  145837. ** * Integration of ICU and SQLite collation sequences.
  145838. **
  145839. ** * An implementation of the LIKE operator that uses ICU to
  145840. ** provide case-independent matching.
  145841. */
  145842. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  145843. /* Include ICU headers */
  145844. #include <unicode/utypes.h>
  145845. #include <unicode/uregex.h>
  145846. #include <unicode/ustring.h>
  145847. #include <unicode/ucol.h>
  145848. /* #include <assert.h> */
  145849. #ifndef SQLITE_CORE
  145850. /* #include "sqlite3ext.h" */
  145851. SQLITE_EXTENSION_INIT1
  145852. #else
  145853. /* #include "sqlite3.h" */
  145854. #endif
  145855. /*
  145856. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  145857. ** operator.
  145858. */
  145859. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  145860. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  145861. #endif
  145862. /*
  145863. ** Version of sqlite3_free() that is always a function, never a macro.
  145864. */
  145865. static void xFree(void *p){
  145866. sqlite3_free(p);
  145867. }
  145868. /*
  145869. ** Compare two UTF-8 strings for equality where the first string is
  145870. ** a "LIKE" expression. Return true (1) if they are the same and
  145871. ** false (0) if they are different.
  145872. */
  145873. static int icuLikeCompare(
  145874. const uint8_t *zPattern, /* LIKE pattern */
  145875. const uint8_t *zString, /* The UTF-8 string to compare against */
  145876. const UChar32 uEsc /* The escape character */
  145877. ){
  145878. static const int MATCH_ONE = (UChar32)'_';
  145879. static const int MATCH_ALL = (UChar32)'%';
  145880. int iPattern = 0; /* Current byte index in zPattern */
  145881. int iString = 0; /* Current byte index in zString */
  145882. int prevEscape = 0; /* True if the previous character was uEsc */
  145883. while( zPattern[iPattern]!=0 ){
  145884. /* Read (and consume) the next character from the input pattern. */
  145885. UChar32 uPattern;
  145886. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  145887. /* There are now 4 possibilities:
  145888. **
  145889. ** 1. uPattern is an unescaped match-all character "%",
  145890. ** 2. uPattern is an unescaped match-one character "_",
  145891. ** 3. uPattern is an unescaped escape character, or
  145892. ** 4. uPattern is to be handled as an ordinary character
  145893. */
  145894. if( !prevEscape && uPattern==MATCH_ALL ){
  145895. /* Case 1. */
  145896. uint8_t c;
  145897. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  145898. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  145899. ** test string.
  145900. */
  145901. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  145902. if( c==MATCH_ONE ){
  145903. if( zString[iString]==0 ) return 0;
  145904. U8_FWD_1_UNSAFE(zString, iString);
  145905. }
  145906. iPattern++;
  145907. }
  145908. if( zPattern[iPattern]==0 ) return 1;
  145909. while( zString[iString] ){
  145910. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  145911. return 1;
  145912. }
  145913. U8_FWD_1_UNSAFE(zString, iString);
  145914. }
  145915. return 0;
  145916. }else if( !prevEscape && uPattern==MATCH_ONE ){
  145917. /* Case 2. */
  145918. if( zString[iString]==0 ) return 0;
  145919. U8_FWD_1_UNSAFE(zString, iString);
  145920. }else if( !prevEscape && uPattern==uEsc){
  145921. /* Case 3. */
  145922. prevEscape = 1;
  145923. }else{
  145924. /* Case 4. */
  145925. UChar32 uString;
  145926. U8_NEXT_UNSAFE(zString, iString, uString);
  145927. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  145928. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  145929. if( uString!=uPattern ){
  145930. return 0;
  145931. }
  145932. prevEscape = 0;
  145933. }
  145934. }
  145935. return zString[iString]==0;
  145936. }
  145937. /*
  145938. ** Implementation of the like() SQL function. This function implements
  145939. ** the build-in LIKE operator. The first argument to the function is the
  145940. ** pattern and the second argument is the string. So, the SQL statements:
  145941. **
  145942. ** A LIKE B
  145943. **
  145944. ** is implemented as like(B, A). If there is an escape character E,
  145945. **
  145946. ** A LIKE B ESCAPE E
  145947. **
  145948. ** is mapped to like(B, A, E).
  145949. */
  145950. static void icuLikeFunc(
  145951. sqlite3_context *context,
  145952. int argc,
  145953. sqlite3_value **argv
  145954. ){
  145955. const unsigned char *zA = sqlite3_value_text(argv[0]);
  145956. const unsigned char *zB = sqlite3_value_text(argv[1]);
  145957. UChar32 uEsc = 0;
  145958. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  145959. ** of deep recursion and N*N behavior in patternCompare().
  145960. */
  145961. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  145962. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  145963. return;
  145964. }
  145965. if( argc==3 ){
  145966. /* The escape character string must consist of a single UTF-8 character.
  145967. ** Otherwise, return an error.
  145968. */
  145969. int nE= sqlite3_value_bytes(argv[2]);
  145970. const unsigned char *zE = sqlite3_value_text(argv[2]);
  145971. int i = 0;
  145972. if( zE==0 ) return;
  145973. U8_NEXT(zE, i, nE, uEsc);
  145974. if( i!=nE){
  145975. sqlite3_result_error(context,
  145976. "ESCAPE expression must be a single character", -1);
  145977. return;
  145978. }
  145979. }
  145980. if( zA && zB ){
  145981. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  145982. }
  145983. }
  145984. /*
  145985. ** This function is called when an ICU function called from within
  145986. ** the implementation of an SQL scalar function returns an error.
  145987. **
  145988. ** The scalar function context passed as the first argument is
  145989. ** loaded with an error message based on the following two args.
  145990. */
  145991. static void icuFunctionError(
  145992. sqlite3_context *pCtx, /* SQLite scalar function context */
  145993. const char *zName, /* Name of ICU function that failed */
  145994. UErrorCode e /* Error code returned by ICU function */
  145995. ){
  145996. char zBuf[128];
  145997. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  145998. zBuf[127] = '\0';
  145999. sqlite3_result_error(pCtx, zBuf, -1);
  146000. }
  146001. /*
  146002. ** Function to delete compiled regexp objects. Registered as
  146003. ** a destructor function with sqlite3_set_auxdata().
  146004. */
  146005. static void icuRegexpDelete(void *p){
  146006. URegularExpression *pExpr = (URegularExpression *)p;
  146007. uregex_close(pExpr);
  146008. }
  146009. /*
  146010. ** Implementation of SQLite REGEXP operator. This scalar function takes
  146011. ** two arguments. The first is a regular expression pattern to compile
  146012. ** the second is a string to match against that pattern. If either
  146013. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  146014. ** is 1 if the string matches the pattern, or 0 otherwise.
  146015. **
  146016. ** SQLite maps the regexp() function to the regexp() operator such
  146017. ** that the following two are equivalent:
  146018. **
  146019. ** zString REGEXP zPattern
  146020. ** regexp(zPattern, zString)
  146021. **
  146022. ** Uses the following ICU regexp APIs:
  146023. **
  146024. ** uregex_open()
  146025. ** uregex_matches()
  146026. ** uregex_close()
  146027. */
  146028. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  146029. UErrorCode status = U_ZERO_ERROR;
  146030. URegularExpression *pExpr;
  146031. UBool res;
  146032. const UChar *zString = sqlite3_value_text16(apArg[1]);
  146033. (void)nArg; /* Unused parameter */
  146034. /* If the left hand side of the regexp operator is NULL,
  146035. ** then the result is also NULL.
  146036. */
  146037. if( !zString ){
  146038. return;
  146039. }
  146040. pExpr = sqlite3_get_auxdata(p, 0);
  146041. if( !pExpr ){
  146042. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  146043. if( !zPattern ){
  146044. return;
  146045. }
  146046. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  146047. if( U_SUCCESS(status) ){
  146048. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  146049. }else{
  146050. assert(!pExpr);
  146051. icuFunctionError(p, "uregex_open", status);
  146052. return;
  146053. }
  146054. }
  146055. /* Configure the text that the regular expression operates on. */
  146056. uregex_setText(pExpr, zString, -1, &status);
  146057. if( !U_SUCCESS(status) ){
  146058. icuFunctionError(p, "uregex_setText", status);
  146059. return;
  146060. }
  146061. /* Attempt the match */
  146062. res = uregex_matches(pExpr, 0, &status);
  146063. if( !U_SUCCESS(status) ){
  146064. icuFunctionError(p, "uregex_matches", status);
  146065. return;
  146066. }
  146067. /* Set the text that the regular expression operates on to a NULL
  146068. ** pointer. This is not really necessary, but it is tidier than
  146069. ** leaving the regular expression object configured with an invalid
  146070. ** pointer after this function returns.
  146071. */
  146072. uregex_setText(pExpr, 0, 0, &status);
  146073. /* Return 1 or 0. */
  146074. sqlite3_result_int(p, res ? 1 : 0);
  146075. }
  146076. /*
  146077. ** Implementations of scalar functions for case mapping - upper() and
  146078. ** lower(). Function upper() converts its input to upper-case (ABC).
  146079. ** Function lower() converts to lower-case (abc).
  146080. **
  146081. ** ICU provides two types of case mapping, "general" case mapping and
  146082. ** "language specific". Refer to ICU documentation for the differences
  146083. ** between the two.
  146084. **
  146085. ** To utilise "general" case mapping, the upper() or lower() scalar
  146086. ** functions are invoked with one argument:
  146087. **
  146088. ** upper('ABC') -> 'abc'
  146089. ** lower('abc') -> 'ABC'
  146090. **
  146091. ** To access ICU "language specific" case mapping, upper() or lower()
  146092. ** should be invoked with two arguments. The second argument is the name
  146093. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  146094. ** as the second argument is the same as invoking the 1 argument version
  146095. ** of upper() or lower().
  146096. **
  146097. ** lower('I', 'en_us') -> 'i'
  146098. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  146099. **
  146100. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  146101. */
  146102. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  146103. const UChar *zInput;
  146104. UChar *zOutput;
  146105. int nInput;
  146106. int nOutput;
  146107. UErrorCode status = U_ZERO_ERROR;
  146108. const char *zLocale = 0;
  146109. assert(nArg==1 || nArg==2);
  146110. if( nArg==2 ){
  146111. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  146112. }
  146113. zInput = sqlite3_value_text16(apArg[0]);
  146114. if( !zInput ){
  146115. return;
  146116. }
  146117. nInput = sqlite3_value_bytes16(apArg[0]);
  146118. nOutput = nInput * 2 + 2;
  146119. zOutput = sqlite3_malloc(nOutput);
  146120. if( !zOutput ){
  146121. return;
  146122. }
  146123. if( sqlite3_user_data(p) ){
  146124. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  146125. }else{
  146126. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  146127. }
  146128. if( !U_SUCCESS(status) ){
  146129. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  146130. return;
  146131. }
  146132. sqlite3_result_text16(p, zOutput, -1, xFree);
  146133. }
  146134. /*
  146135. ** Collation sequence destructor function. The pCtx argument points to
  146136. ** a UCollator structure previously allocated using ucol_open().
  146137. */
  146138. static void icuCollationDel(void *pCtx){
  146139. UCollator *p = (UCollator *)pCtx;
  146140. ucol_close(p);
  146141. }
  146142. /*
  146143. ** Collation sequence comparison function. The pCtx argument points to
  146144. ** a UCollator structure previously allocated using ucol_open().
  146145. */
  146146. static int icuCollationColl(
  146147. void *pCtx,
  146148. int nLeft,
  146149. const void *zLeft,
  146150. int nRight,
  146151. const void *zRight
  146152. ){
  146153. UCollationResult res;
  146154. UCollator *p = (UCollator *)pCtx;
  146155. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  146156. switch( res ){
  146157. case UCOL_LESS: return -1;
  146158. case UCOL_GREATER: return +1;
  146159. case UCOL_EQUAL: return 0;
  146160. }
  146161. assert(!"Unexpected return value from ucol_strcoll()");
  146162. return 0;
  146163. }
  146164. /*
  146165. ** Implementation of the scalar function icu_load_collation().
  146166. **
  146167. ** This scalar function is used to add ICU collation based collation
  146168. ** types to an SQLite database connection. It is intended to be called
  146169. ** as follows:
  146170. **
  146171. ** SELECT icu_load_collation(<locale>, <collation-name>);
  146172. **
  146173. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  146174. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  146175. ** collation sequence to create.
  146176. */
  146177. static void icuLoadCollation(
  146178. sqlite3_context *p,
  146179. int nArg,
  146180. sqlite3_value **apArg
  146181. ){
  146182. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  146183. UErrorCode status = U_ZERO_ERROR;
  146184. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  146185. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  146186. UCollator *pUCollator; /* ICU library collation object */
  146187. int rc; /* Return code from sqlite3_create_collation_x() */
  146188. assert(nArg==2);
  146189. (void)nArg; /* Unused parameter */
  146190. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  146191. zName = (const char *)sqlite3_value_text(apArg[1]);
  146192. if( !zLocale || !zName ){
  146193. return;
  146194. }
  146195. pUCollator = ucol_open(zLocale, &status);
  146196. if( !U_SUCCESS(status) ){
  146197. icuFunctionError(p, "ucol_open", status);
  146198. return;
  146199. }
  146200. assert(p);
  146201. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  146202. icuCollationColl, icuCollationDel
  146203. );
  146204. if( rc!=SQLITE_OK ){
  146205. ucol_close(pUCollator);
  146206. sqlite3_result_error(p, "Error registering collation function", -1);
  146207. }
  146208. }
  146209. /*
  146210. ** Register the ICU extension functions with database db.
  146211. */
  146212. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  146213. struct IcuScalar {
  146214. const char *zName; /* Function name */
  146215. int nArg; /* Number of arguments */
  146216. int enc; /* Optimal text encoding */
  146217. void *pContext; /* sqlite3_user_data() context */
  146218. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  146219. } scalars[] = {
  146220. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  146221. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  146222. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  146223. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  146224. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  146225. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  146226. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  146227. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  146228. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  146229. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  146230. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  146231. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  146232. };
  146233. int rc = SQLITE_OK;
  146234. int i;
  146235. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  146236. struct IcuScalar *p = &scalars[i];
  146237. rc = sqlite3_create_function(
  146238. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  146239. );
  146240. }
  146241. return rc;
  146242. }
  146243. #if !SQLITE_CORE
  146244. #ifdef _WIN32
  146245. __declspec(dllexport)
  146246. #endif
  146247. SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
  146248. sqlite3 *db,
  146249. char **pzErrMsg,
  146250. const sqlite3_api_routines *pApi
  146251. ){
  146252. SQLITE_EXTENSION_INIT2(pApi)
  146253. return sqlite3IcuInit(db);
  146254. }
  146255. #endif
  146256. #endif
  146257. /************** End of icu.c *************************************************/
  146258. /************** Begin file fts3_icu.c ****************************************/
  146259. /*
  146260. ** 2007 June 22
  146261. **
  146262. ** The author disclaims copyright to this source code. In place of
  146263. ** a legal notice, here is a blessing:
  146264. **
  146265. ** May you do good and not evil.
  146266. ** May you find forgiveness for yourself and forgive others.
  146267. ** May you share freely, never taking more than you give.
  146268. **
  146269. *************************************************************************
  146270. ** This file implements a tokenizer for fts3 based on the ICU library.
  146271. */
  146272. /* #include "fts3Int.h" */
  146273. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  146274. #ifdef SQLITE_ENABLE_ICU
  146275. /* #include <assert.h> */
  146276. /* #include <string.h> */
  146277. /* #include "fts3_tokenizer.h" */
  146278. #include <unicode/ubrk.h>
  146279. /* #include <unicode/ucol.h> */
  146280. /* #include <unicode/ustring.h> */
  146281. #include <unicode/utf16.h>
  146282. typedef struct IcuTokenizer IcuTokenizer;
  146283. typedef struct IcuCursor IcuCursor;
  146284. struct IcuTokenizer {
  146285. sqlite3_tokenizer base;
  146286. char *zLocale;
  146287. };
  146288. struct IcuCursor {
  146289. sqlite3_tokenizer_cursor base;
  146290. UBreakIterator *pIter; /* ICU break-iterator object */
  146291. int nChar; /* Number of UChar elements in pInput */
  146292. UChar *aChar; /* Copy of input using utf-16 encoding */
  146293. int *aOffset; /* Offsets of each character in utf-8 input */
  146294. int nBuffer;
  146295. char *zBuffer;
  146296. int iToken;
  146297. };
  146298. /*
  146299. ** Create a new tokenizer instance.
  146300. */
  146301. static int icuCreate(
  146302. int argc, /* Number of entries in argv[] */
  146303. const char * const *argv, /* Tokenizer creation arguments */
  146304. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  146305. ){
  146306. IcuTokenizer *p;
  146307. int n = 0;
  146308. if( argc>0 ){
  146309. n = strlen(argv[0])+1;
  146310. }
  146311. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  146312. if( !p ){
  146313. return SQLITE_NOMEM;
  146314. }
  146315. memset(p, 0, sizeof(IcuTokenizer));
  146316. if( n ){
  146317. p->zLocale = (char *)&p[1];
  146318. memcpy(p->zLocale, argv[0], n);
  146319. }
  146320. *ppTokenizer = (sqlite3_tokenizer *)p;
  146321. return SQLITE_OK;
  146322. }
  146323. /*
  146324. ** Destroy a tokenizer
  146325. */
  146326. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  146327. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  146328. sqlite3_free(p);
  146329. return SQLITE_OK;
  146330. }
  146331. /*
  146332. ** Prepare to begin tokenizing a particular string. The input
  146333. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  146334. ** used to incrementally tokenize this string is returned in
  146335. ** *ppCursor.
  146336. */
  146337. static int icuOpen(
  146338. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  146339. const char *zInput, /* Input string */
  146340. int nInput, /* Length of zInput in bytes */
  146341. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  146342. ){
  146343. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  146344. IcuCursor *pCsr;
  146345. const int32_t opt = U_FOLD_CASE_DEFAULT;
  146346. UErrorCode status = U_ZERO_ERROR;
  146347. int nChar;
  146348. UChar32 c;
  146349. int iInput = 0;
  146350. int iOut = 0;
  146351. *ppCursor = 0;
  146352. if( zInput==0 ){
  146353. nInput = 0;
  146354. zInput = "";
  146355. }else if( nInput<0 ){
  146356. nInput = strlen(zInput);
  146357. }
  146358. nChar = nInput+1;
  146359. pCsr = (IcuCursor *)sqlite3_malloc(
  146360. sizeof(IcuCursor) + /* IcuCursor */
  146361. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  146362. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  146363. );
  146364. if( !pCsr ){
  146365. return SQLITE_NOMEM;
  146366. }
  146367. memset(pCsr, 0, sizeof(IcuCursor));
  146368. pCsr->aChar = (UChar *)&pCsr[1];
  146369. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  146370. pCsr->aOffset[iOut] = iInput;
  146371. U8_NEXT(zInput, iInput, nInput, c);
  146372. while( c>0 ){
  146373. int isError = 0;
  146374. c = u_foldCase(c, opt);
  146375. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  146376. if( isError ){
  146377. sqlite3_free(pCsr);
  146378. return SQLITE_ERROR;
  146379. }
  146380. pCsr->aOffset[iOut] = iInput;
  146381. if( iInput<nInput ){
  146382. U8_NEXT(zInput, iInput, nInput, c);
  146383. }else{
  146384. c = 0;
  146385. }
  146386. }
  146387. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  146388. if( !U_SUCCESS(status) ){
  146389. sqlite3_free(pCsr);
  146390. return SQLITE_ERROR;
  146391. }
  146392. pCsr->nChar = iOut;
  146393. ubrk_first(pCsr->pIter);
  146394. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  146395. return SQLITE_OK;
  146396. }
  146397. /*
  146398. ** Close a tokenization cursor previously opened by a call to icuOpen().
  146399. */
  146400. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  146401. IcuCursor *pCsr = (IcuCursor *)pCursor;
  146402. ubrk_close(pCsr->pIter);
  146403. sqlite3_free(pCsr->zBuffer);
  146404. sqlite3_free(pCsr);
  146405. return SQLITE_OK;
  146406. }
  146407. /*
  146408. ** Extract the next token from a tokenization cursor.
  146409. */
  146410. static int icuNext(
  146411. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  146412. const char **ppToken, /* OUT: *ppToken is the token text */
  146413. int *pnBytes, /* OUT: Number of bytes in token */
  146414. int *piStartOffset, /* OUT: Starting offset of token */
  146415. int *piEndOffset, /* OUT: Ending offset of token */
  146416. int *piPosition /* OUT: Position integer of token */
  146417. ){
  146418. IcuCursor *pCsr = (IcuCursor *)pCursor;
  146419. int iStart = 0;
  146420. int iEnd = 0;
  146421. int nByte = 0;
  146422. while( iStart==iEnd ){
  146423. UChar32 c;
  146424. iStart = ubrk_current(pCsr->pIter);
  146425. iEnd = ubrk_next(pCsr->pIter);
  146426. if( iEnd==UBRK_DONE ){
  146427. return SQLITE_DONE;
  146428. }
  146429. while( iStart<iEnd ){
  146430. int iWhite = iStart;
  146431. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  146432. if( u_isspace(c) ){
  146433. iStart = iWhite;
  146434. }else{
  146435. break;
  146436. }
  146437. }
  146438. assert(iStart<=iEnd);
  146439. }
  146440. do {
  146441. UErrorCode status = U_ZERO_ERROR;
  146442. if( nByte ){
  146443. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  146444. if( !zNew ){
  146445. return SQLITE_NOMEM;
  146446. }
  146447. pCsr->zBuffer = zNew;
  146448. pCsr->nBuffer = nByte;
  146449. }
  146450. u_strToUTF8(
  146451. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  146452. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  146453. &status /* Output success/failure */
  146454. );
  146455. } while( nByte>pCsr->nBuffer );
  146456. *ppToken = pCsr->zBuffer;
  146457. *pnBytes = nByte;
  146458. *piStartOffset = pCsr->aOffset[iStart];
  146459. *piEndOffset = pCsr->aOffset[iEnd];
  146460. *piPosition = pCsr->iToken++;
  146461. return SQLITE_OK;
  146462. }
  146463. /*
  146464. ** The set of routines that implement the simple tokenizer
  146465. */
  146466. static const sqlite3_tokenizer_module icuTokenizerModule = {
  146467. 0, /* iVersion */
  146468. icuCreate, /* xCreate */
  146469. icuDestroy, /* xCreate */
  146470. icuOpen, /* xOpen */
  146471. icuClose, /* xClose */
  146472. icuNext, /* xNext */
  146473. 0, /* xLanguageid */
  146474. };
  146475. /*
  146476. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  146477. */
  146478. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  146479. sqlite3_tokenizer_module const**ppModule
  146480. ){
  146481. *ppModule = &icuTokenizerModule;
  146482. }
  146483. #endif /* defined(SQLITE_ENABLE_ICU) */
  146484. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  146485. /************** End of fts3_icu.c ********************************************/
  146486. /************** Begin file sqlite3rbu.c **************************************/
  146487. /*
  146488. ** 2014 August 30
  146489. **
  146490. ** The author disclaims copyright to this source code. In place of
  146491. ** a legal notice, here is a blessing:
  146492. **
  146493. ** May you do good and not evil.
  146494. ** May you find forgiveness for yourself and forgive others.
  146495. ** May you share freely, never taking more than you give.
  146496. **
  146497. *************************************************************************
  146498. **
  146499. **
  146500. ** OVERVIEW
  146501. **
  146502. ** The RBU extension requires that the RBU update be packaged as an
  146503. ** SQLite database. The tables it expects to find are described in
  146504. ** sqlite3rbu.h. Essentially, for each table xyz in the target database
  146505. ** that the user wishes to write to, a corresponding data_xyz table is
  146506. ** created in the RBU database and populated with one row for each row to
  146507. ** update, insert or delete from the target table.
  146508. **
  146509. ** The update proceeds in three stages:
  146510. **
  146511. ** 1) The database is updated. The modified database pages are written
  146512. ** to a *-oal file. A *-oal file is just like a *-wal file, except
  146513. ** that it is named "<database>-oal" instead of "<database>-wal".
  146514. ** Because regular SQLite clients do not look for file named
  146515. ** "<database>-oal", they go on using the original database in
  146516. ** rollback mode while the *-oal file is being generated.
  146517. **
  146518. ** During this stage RBU does not update the database by writing
  146519. ** directly to the target tables. Instead it creates "imposter"
  146520. ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
  146521. ** to update each b-tree individually. All updates required by each
  146522. ** b-tree are completed before moving on to the next, and all
  146523. ** updates are done in sorted key order.
  146524. **
  146525. ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
  146526. ** location using a call to rename(2). Before doing this the RBU
  146527. ** module takes an EXCLUSIVE lock on the database file, ensuring
  146528. ** that there are no other active readers.
  146529. **
  146530. ** Once the EXCLUSIVE lock is released, any other database readers
  146531. ** detect the new *-wal file and read the database in wal mode. At
  146532. ** this point they see the new version of the database - including
  146533. ** the updates made as part of the RBU update.
  146534. **
  146535. ** 3) The new *-wal file is checkpointed. This proceeds in the same way
  146536. ** as a regular database checkpoint, except that a single frame is
  146537. ** checkpointed each time sqlite3rbu_step() is called. If the RBU
  146538. ** handle is closed before the entire *-wal file is checkpointed,
  146539. ** the checkpoint progress is saved in the RBU database and the
  146540. ** checkpoint can be resumed by another RBU client at some point in
  146541. ** the future.
  146542. **
  146543. ** POTENTIAL PROBLEMS
  146544. **
  146545. ** The rename() call might not be portable. And RBU is not currently
  146546. ** syncing the directory after renaming the file.
  146547. **
  146548. ** When state is saved, any commit to the *-oal file and the commit to
  146549. ** the RBU update database are not atomic. So if the power fails at the
  146550. ** wrong moment they might get out of sync. As the main database will be
  146551. ** committed before the RBU update database this will likely either just
  146552. ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
  146553. ** constraint violations).
  146554. **
  146555. ** If some client does modify the target database mid RBU update, or some
  146556. ** other error occurs, the RBU extension will keep throwing errors. It's
  146557. ** not really clear how to get out of this state. The system could just
  146558. ** by delete the RBU update database and *-oal file and have the device
  146559. ** download the update again and start over.
  146560. **
  146561. ** At present, for an UPDATE, both the new.* and old.* records are
  146562. ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
  146563. ** fields are collected. This means we're probably writing a lot more
  146564. ** data to disk when saving the state of an ongoing update to the RBU
  146565. ** update database than is strictly necessary.
  146566. **
  146567. */
  146568. /* #include <assert.h> */
  146569. /* #include <string.h> */
  146570. /* #include <stdio.h> */
  146571. #if !defined(_WIN32)
  146572. /* # include <unistd.h> */
  146573. #endif
  146574. /* #include "sqlite3.h" */
  146575. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
  146576. /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
  146577. /************** Begin file sqlite3rbu.h **************************************/
  146578. /*
  146579. ** 2014 August 30
  146580. **
  146581. ** The author disclaims copyright to this source code. In place of
  146582. ** a legal notice, here is a blessing:
  146583. **
  146584. ** May you do good and not evil.
  146585. ** May you find forgiveness for yourself and forgive others.
  146586. ** May you share freely, never taking more than you give.
  146587. **
  146588. *************************************************************************
  146589. **
  146590. ** This file contains the public interface for the RBU extension.
  146591. */
  146592. /*
  146593. ** SUMMARY
  146594. **
  146595. ** Writing a transaction containing a large number of operations on
  146596. ** b-tree indexes that are collectively larger than the available cache
  146597. ** memory can be very inefficient.
  146598. **
  146599. ** The problem is that in order to update a b-tree, the leaf page (at least)
  146600. ** containing the entry being inserted or deleted must be modified. If the
  146601. ** working set of leaves is larger than the available cache memory, then a
  146602. ** single leaf that is modified more than once as part of the transaction
  146603. ** may be loaded from or written to the persistent media multiple times.
  146604. ** Additionally, because the index updates are likely to be applied in
  146605. ** random order, access to pages within the database is also likely to be in
  146606. ** random order, which is itself quite inefficient.
  146607. **
  146608. ** One way to improve the situation is to sort the operations on each index
  146609. ** by index key before applying them to the b-tree. This leads to an IO
  146610. ** pattern that resembles a single linear scan through the index b-tree,
  146611. ** and all but guarantees each modified leaf page is loaded and stored
  146612. ** exactly once. SQLite uses this trick to improve the performance of
  146613. ** CREATE INDEX commands. This extension allows it to be used to improve
  146614. ** the performance of large transactions on existing databases.
  146615. **
  146616. ** Additionally, this extension allows the work involved in writing the
  146617. ** large transaction to be broken down into sub-transactions performed
  146618. ** sequentially by separate processes. This is useful if the system cannot
  146619. ** guarantee that a single update process will run for long enough to apply
  146620. ** the entire update, for example because the update is being applied on a
  146621. ** mobile device that is frequently rebooted. Even after the writer process
  146622. ** has committed one or more sub-transactions, other database clients continue
  146623. ** to read from the original database snapshot. In other words, partially
  146624. ** applied transactions are not visible to other clients.
  146625. **
  146626. ** "RBU" stands for "Resumable Bulk Update". As in a large database update
  146627. ** transmitted via a wireless network to a mobile device. A transaction
  146628. ** applied using this extension is hence refered to as an "RBU update".
  146629. **
  146630. **
  146631. ** LIMITATIONS
  146632. **
  146633. ** An "RBU update" transaction is subject to the following limitations:
  146634. **
  146635. ** * The transaction must consist of INSERT, UPDATE and DELETE operations
  146636. ** only.
  146637. **
  146638. ** * INSERT statements may not use any default values.
  146639. **
  146640. ** * UPDATE and DELETE statements must identify their target rows by
  146641. ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
  146642. ** KEY fields may not be updated or deleted. If the table being written
  146643. ** has no PRIMARY KEY, affected rows must be identified by rowid.
  146644. **
  146645. ** * UPDATE statements may not modify PRIMARY KEY columns.
  146646. **
  146647. ** * No triggers will be fired.
  146648. **
  146649. ** * No foreign key violations are detected or reported.
  146650. **
  146651. ** * CHECK constraints are not enforced.
  146652. **
  146653. ** * No constraint handling mode except for "OR ROLLBACK" is supported.
  146654. **
  146655. **
  146656. ** PREPARATION
  146657. **
  146658. ** An "RBU update" is stored as a separate SQLite database. A database
  146659. ** containing an RBU update is an "RBU database". For each table in the
  146660. ** target database to be updated, the RBU database should contain a table
  146661. ** named "data_<target name>" containing the same set of columns as the
  146662. ** target table, and one more - "rbu_control". The data_% table should
  146663. ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
  146664. ** the same type as the corresponding column in the target database.
  146665. ** The "rbu_control" column should have no type at all. For example, if
  146666. ** the target database contains:
  146667. **
  146668. ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
  146669. **
  146670. ** Then the RBU database should contain:
  146671. **
  146672. ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
  146673. **
  146674. ** The order of the columns in the data_% table does not matter.
  146675. **
  146676. ** If the target database table is a virtual table or a table that has no
  146677. ** PRIMARY KEY declaration, the data_% table must also contain a column
  146678. ** named "rbu_rowid". This column is mapped to the tables implicit primary
  146679. ** key column - "rowid". Virtual tables for which the "rowid" column does
  146680. ** not function like a primary key value cannot be updated using RBU. For
  146681. ** example, if the target db contains either of the following:
  146682. **
  146683. ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
  146684. ** CREATE TABLE x1(a, b)
  146685. **
  146686. ** then the RBU database should contain:
  146687. **
  146688. ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
  146689. **
  146690. ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
  146691. ** target table must be present in the input table. For virtual tables,
  146692. ** hidden columns are optional - they are updated by RBU if present in
  146693. ** the input table, or not otherwise. For example, to write to an fts4
  146694. ** table with a hidden languageid column such as:
  146695. **
  146696. ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
  146697. **
  146698. ** Either of the following input table schemas may be used:
  146699. **
  146700. ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
  146701. ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
  146702. **
  146703. ** For each row to INSERT into the target database as part of the RBU
  146704. ** update, the corresponding data_% table should contain a single record
  146705. ** with the "rbu_control" column set to contain integer value 0. The
  146706. ** other columns should be set to the values that make up the new record
  146707. ** to insert.
  146708. **
  146709. ** If the target database table has an INTEGER PRIMARY KEY, it is not
  146710. ** possible to insert a NULL value into the IPK column. Attempting to
  146711. ** do so results in an SQLITE_MISMATCH error.
  146712. **
  146713. ** For each row to DELETE from the target database as part of the RBU
  146714. ** update, the corresponding data_% table should contain a single record
  146715. ** with the "rbu_control" column set to contain integer value 1. The
  146716. ** real primary key values of the row to delete should be stored in the
  146717. ** corresponding columns of the data_% table. The values stored in the
  146718. ** other columns are not used.
  146719. **
  146720. ** For each row to UPDATE from the target database as part of the RBU
  146721. ** update, the corresponding data_% table should contain a single record
  146722. ** with the "rbu_control" column set to contain a value of type text.
  146723. ** The real primary key values identifying the row to update should be
  146724. ** stored in the corresponding columns of the data_% table row, as should
  146725. ** the new values of all columns being update. The text value in the
  146726. ** "rbu_control" column must contain the same number of characters as
  146727. ** there are columns in the target database table, and must consist entirely
  146728. ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
  146729. ** each column that is being updated, the corresponding character is set to
  146730. ** 'x'. For those that remain as they are, the corresponding character of the
  146731. ** rbu_control value should be set to '.'. For example, given the tables
  146732. ** above, the update statement:
  146733. **
  146734. ** UPDATE t1 SET c = 'usa' WHERE a = 4;
  146735. **
  146736. ** is represented by the data_t1 row created by:
  146737. **
  146738. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
  146739. **
  146740. ** Instead of an 'x' character, characters of the rbu_control value specified
  146741. ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
  146742. ** target table with the value stored in the corresponding data_% column, the
  146743. ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
  146744. ** the target table column. rbu_delta() is invoked with two arguments - the
  146745. ** original value currently stored in the target table column and the
  146746. ** value specified in the data_xxx table.
  146747. **
  146748. ** For example, this row:
  146749. **
  146750. ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
  146751. **
  146752. ** is similar to an UPDATE statement such as:
  146753. **
  146754. ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
  146755. **
  146756. ** If the target database table is a virtual table or a table with no PRIMARY
  146757. ** KEY, the rbu_control value should not include a character corresponding
  146758. ** to the rbu_rowid value. For example, this:
  146759. **
  146760. ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
  146761. ** VALUES(NULL, 'usa', 12, '.x');
  146762. **
  146763. ** causes a result similar to:
  146764. **
  146765. ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
  146766. **
  146767. ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
  146768. ** However, RBU is more efficient if reading the rows in from each data_xxx
  146769. ** table in "rowid" order is roughly the same as reading them sorted by
  146770. ** the PRIMARY KEY of the corresponding target database table. In other
  146771. ** words, rows should be sorted using the destination table PRIMARY KEY
  146772. ** fields before they are inserted into the data_xxx tables.
  146773. **
  146774. ** USAGE
  146775. **
  146776. ** The API declared below allows an application to apply an RBU update
  146777. ** stored on disk to an existing target database. Essentially, the
  146778. ** application:
  146779. **
  146780. ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
  146781. **
  146782. ** 2) Registers any required virtual table modules with the database
  146783. ** handle returned by sqlite3rbu_db(). Also, if required, register
  146784. ** the rbu_delta() implementation.
  146785. **
  146786. ** 3) Calls the sqlite3rbu_step() function one or more times on
  146787. ** the new handle. Each call to sqlite3rbu_step() performs a single
  146788. ** b-tree operation, so thousands of calls may be required to apply
  146789. ** a complete update.
  146790. **
  146791. ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
  146792. ** sqlite3rbu_step() has been called enough times to completely
  146793. ** apply the update to the target database, then the RBU database
  146794. ** is marked as fully applied. Otherwise, the state of the RBU
  146795. ** update application is saved in the RBU database for later
  146796. ** resumption.
  146797. **
  146798. ** See comments below for more detail on APIs.
  146799. **
  146800. ** If an update is only partially applied to the target database by the
  146801. ** time sqlite3rbu_close() is called, various state information is saved
  146802. ** within the RBU database. This allows subsequent processes to automatically
  146803. ** resume the RBU update from where it left off.
  146804. **
  146805. ** To remove all RBU extension state information, returning an RBU database
  146806. ** to its original contents, it is sufficient to drop all tables that begin
  146807. ** with the prefix "rbu_"
  146808. **
  146809. ** DATABASE LOCKING
  146810. **
  146811. ** An RBU update may not be applied to a database in WAL mode. Attempting
  146812. ** to do so is an error (SQLITE_ERROR).
  146813. **
  146814. ** While an RBU handle is open, a SHARED lock may be held on the target
  146815. ** database file. This means it is possible for other clients to read the
  146816. ** database, but not to write it.
  146817. **
  146818. ** If an RBU update is started and then suspended before it is completed,
  146819. ** then an external client writes to the database, then attempting to resume
  146820. ** the suspended RBU update is also an error (SQLITE_BUSY).
  146821. */
  146822. #ifndef _SQLITE3RBU_H
  146823. #define _SQLITE3RBU_H
  146824. /* #include "sqlite3.h" ** Required for error code definitions ** */
  146825. typedef struct sqlite3rbu sqlite3rbu;
  146826. /*
  146827. ** Open an RBU handle.
  146828. **
  146829. ** Argument zTarget is the path to the target database. Argument zRbu is
  146830. ** the path to the RBU database. Each call to this function must be matched
  146831. ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
  146832. ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
  146833. ** or zRbu begin with "file:", it will be interpreted as an SQLite
  146834. ** database URI, not a regular file name.
  146835. **
  146836. ** If the zState argument is passed a NULL value, the RBU extension stores
  146837. ** the current state of the update (how many rows have been updated, which
  146838. ** indexes are yet to be updated etc.) within the RBU database itself. This
  146839. ** can be convenient, as it means that the RBU application does not need to
  146840. ** organize removing a separate state file after the update is concluded.
  146841. ** Or, if zState is non-NULL, it must be a path to a database file in which
  146842. ** the RBU extension can store the state of the update.
  146843. **
  146844. ** When resuming an RBU update, the zState argument must be passed the same
  146845. ** value as when the RBU update was started.
  146846. **
  146847. ** Once the RBU update is finished, the RBU extension does not
  146848. ** automatically remove any zState database file, even if it created it.
  146849. **
  146850. ** By default, RBU uses the default VFS to access the files on disk. To
  146851. ** use a VFS other than the default, an SQLite "file:" URI containing a
  146852. ** "vfs=..." option may be passed as the zTarget option.
  146853. **
  146854. ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
  146855. ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
  146856. ** not work out of the box with zipvfs. Refer to the comment describing
  146857. ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
  146858. */
  146859. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  146860. const char *zTarget,
  146861. const char *zRbu,
  146862. const char *zState
  146863. );
  146864. /*
  146865. ** Internally, each RBU connection uses a separate SQLite database
  146866. ** connection to access the target and rbu update databases. This
  146867. ** API allows the application direct access to these database handles.
  146868. **
  146869. ** The first argument passed to this function must be a valid, open, RBU
  146870. ** handle. The second argument should be passed zero to access the target
  146871. ** database handle, or non-zero to access the rbu update database handle.
  146872. ** Accessing the underlying database handles may be useful in the
  146873. ** following scenarios:
  146874. **
  146875. ** * If any target tables are virtual tables, it may be necessary to
  146876. ** call sqlite3_create_module() on the target database handle to
  146877. ** register the required virtual table implementations.
  146878. **
  146879. ** * If the data_xxx tables in the RBU source database are virtual
  146880. ** tables, the application may need to call sqlite3_create_module() on
  146881. ** the rbu update db handle to any required virtual table
  146882. ** implementations.
  146883. **
  146884. ** * If the application uses the "rbu_delta()" feature described above,
  146885. ** it must use sqlite3_create_function() or similar to register the
  146886. ** rbu_delta() implementation with the target database handle.
  146887. **
  146888. ** If an error has occurred, either while opening or stepping the RBU object,
  146889. ** this function may return NULL. The error code and message may be collected
  146890. ** when sqlite3rbu_close() is called.
  146891. */
  146892. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
  146893. /*
  146894. ** Do some work towards applying the RBU update to the target db.
  146895. **
  146896. ** Return SQLITE_DONE if the update has been completely applied, or
  146897. ** SQLITE_OK if no error occurs but there remains work to do to apply
  146898. ** the RBU update. If an error does occur, some other error code is
  146899. ** returned.
  146900. **
  146901. ** Once a call to sqlite3rbu_step() has returned a value other than
  146902. ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
  146903. ** that immediately return the same value.
  146904. */
  146905. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
  146906. /*
  146907. ** Close an RBU handle.
  146908. **
  146909. ** If the RBU update has been completely applied, mark the RBU database
  146910. ** as fully applied. Otherwise, assuming no error has occurred, save the
  146911. ** current state of the RBU update appliation to the RBU database.
  146912. **
  146913. ** If an error has already occurred as part of an sqlite3rbu_step()
  146914. ** or sqlite3rbu_open() call, or if one occurs within this function, an
  146915. ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
  146916. ** point to a buffer containing a utf-8 formatted English language error
  146917. ** message. It is the responsibility of the caller to eventually free any
  146918. ** such buffer using sqlite3_free().
  146919. **
  146920. ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
  146921. ** update has been partially applied, or SQLITE_DONE if it has been
  146922. ** completely applied.
  146923. */
  146924. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
  146925. /*
  146926. ** Return the total number of key-value operations (inserts, deletes or
  146927. ** updates) that have been performed on the target database since the
  146928. ** current RBU update was started.
  146929. */
  146930. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
  146931. /*
  146932. ** Create an RBU VFS named zName that accesses the underlying file-system
  146933. ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
  146934. ** then the new RBU VFS uses the default system VFS to access the file-system.
  146935. ** The new object is registered as a non-default VFS with SQLite before
  146936. ** returning.
  146937. **
  146938. ** Part of the RBU implementation uses a custom VFS object. Usually, this
  146939. ** object is created and deleted automatically by RBU.
  146940. **
  146941. ** The exception is for applications that also use zipvfs. In this case,
  146942. ** the custom VFS must be explicitly created by the user before the RBU
  146943. ** handle is opened. The RBU VFS should be installed so that the zipvfs
  146944. ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
  146945. ** (for example multiplexor) to access the file-system. For example,
  146946. ** to assemble an RBU enabled VFS stack that uses both zipvfs and
  146947. ** multiplexor (error checking omitted):
  146948. **
  146949. ** // Create a VFS named "multiplex" (not the default).
  146950. ** sqlite3_multiplex_initialize(0, 0);
  146951. **
  146952. ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
  146953. ** // second argument were replaced with NULL, the "rbu" VFS would
  146954. ** // access the file-system via the system default VFS, bypassing the
  146955. ** // multiplexor.
  146956. ** sqlite3rbu_create_vfs("rbu", "multiplex");
  146957. **
  146958. ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
  146959. ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
  146960. **
  146961. ** // Make zipvfs the default VFS.
  146962. ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
  146963. **
  146964. ** Because the default VFS created above includes a RBU functionality, it
  146965. ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
  146966. ** that does not include the RBU layer results in an error.
  146967. **
  146968. ** The overhead of adding the "rbu" VFS to the system is negligible for
  146969. ** non-RBU users. There is no harm in an application accessing the
  146970. ** file-system via "rbu" all the time, even if it only uses RBU functionality
  146971. ** occasionally.
  146972. */
  146973. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
  146974. /*
  146975. ** Deregister and destroy an RBU vfs created by an earlier call to
  146976. ** sqlite3rbu_create_vfs().
  146977. **
  146978. ** VFS objects are not reference counted. If a VFS object is destroyed
  146979. ** before all database handles that use it have been closed, the results
  146980. ** are undefined.
  146981. */
  146982. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
  146983. #endif /* _SQLITE3RBU_H */
  146984. /************** End of sqlite3rbu.h ******************************************/
  146985. /************** Continuing where we left off in sqlite3rbu.c *****************/
  146986. /* Maximum number of prepared UPDATE statements held by this module */
  146987. #define SQLITE_RBU_UPDATE_CACHESIZE 16
  146988. /*
  146989. ** Swap two objects of type TYPE.
  146990. */
  146991. #if !defined(SQLITE_AMALGAMATION)
  146992. # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  146993. #endif
  146994. /*
  146995. ** The rbu_state table is used to save the state of a partially applied
  146996. ** update so that it can be resumed later. The table consists of integer
  146997. ** keys mapped to values as follows:
  146998. **
  146999. ** RBU_STATE_STAGE:
  147000. ** May be set to integer values 1, 2, 4 or 5. As follows:
  147001. ** 1: the *-rbu file is currently under construction.
  147002. ** 2: the *-rbu file has been constructed, but not yet moved
  147003. ** to the *-wal path.
  147004. ** 4: the checkpoint is underway.
  147005. ** 5: the rbu update has been checkpointed.
  147006. **
  147007. ** RBU_STATE_TBL:
  147008. ** Only valid if STAGE==1. The target database name of the table
  147009. ** currently being written.
  147010. **
  147011. ** RBU_STATE_IDX:
  147012. ** Only valid if STAGE==1. The target database name of the index
  147013. ** currently being written, or NULL if the main table is currently being
  147014. ** updated.
  147015. **
  147016. ** RBU_STATE_ROW:
  147017. ** Only valid if STAGE==1. Number of rows already processed for the current
  147018. ** table/index.
  147019. **
  147020. ** RBU_STATE_PROGRESS:
  147021. ** Trbul number of sqlite3rbu_step() calls made so far as part of this
  147022. ** rbu update.
  147023. **
  147024. ** RBU_STATE_CKPT:
  147025. ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
  147026. ** header created by recovering the *-wal file. This is used to detect
  147027. ** cases when another client appends frames to the *-wal file in the
  147028. ** middle of an incremental checkpoint (an incremental checkpoint cannot
  147029. ** be continued if this happens).
  147030. **
  147031. ** RBU_STATE_COOKIE:
  147032. ** Valid if STAGE==1. The current change-counter cookie value in the
  147033. ** target db file.
  147034. **
  147035. ** RBU_STATE_OALSZ:
  147036. ** Valid if STAGE==1. The size in bytes of the *-oal file.
  147037. */
  147038. #define RBU_STATE_STAGE 1
  147039. #define RBU_STATE_TBL 2
  147040. #define RBU_STATE_IDX 3
  147041. #define RBU_STATE_ROW 4
  147042. #define RBU_STATE_PROGRESS 5
  147043. #define RBU_STATE_CKPT 6
  147044. #define RBU_STATE_COOKIE 7
  147045. #define RBU_STATE_OALSZ 8
  147046. #define RBU_STAGE_OAL 1
  147047. #define RBU_STAGE_MOVE 2
  147048. #define RBU_STAGE_CAPTURE 3
  147049. #define RBU_STAGE_CKPT 4
  147050. #define RBU_STAGE_DONE 5
  147051. #define RBU_CREATE_STATE \
  147052. "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
  147053. typedef struct RbuFrame RbuFrame;
  147054. typedef struct RbuObjIter RbuObjIter;
  147055. typedef struct RbuState RbuState;
  147056. typedef struct rbu_vfs rbu_vfs;
  147057. typedef struct rbu_file rbu_file;
  147058. typedef struct RbuUpdateStmt RbuUpdateStmt;
  147059. #if !defined(SQLITE_AMALGAMATION)
  147060. typedef unsigned int u32;
  147061. typedef unsigned char u8;
  147062. typedef sqlite3_int64 i64;
  147063. #endif
  147064. /*
  147065. ** These values must match the values defined in wal.c for the equivalent
  147066. ** locks. These are not magic numbers as they are part of the SQLite file
  147067. ** format.
  147068. */
  147069. #define WAL_LOCK_WRITE 0
  147070. #define WAL_LOCK_CKPT 1
  147071. #define WAL_LOCK_READ0 3
  147072. /*
  147073. ** A structure to store values read from the rbu_state table in memory.
  147074. */
  147075. struct RbuState {
  147076. int eStage;
  147077. char *zTbl;
  147078. char *zIdx;
  147079. i64 iWalCksum;
  147080. int nRow;
  147081. i64 nProgress;
  147082. u32 iCookie;
  147083. i64 iOalSz;
  147084. };
  147085. struct RbuUpdateStmt {
  147086. char *zMask; /* Copy of update mask used with pUpdate */
  147087. sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
  147088. RbuUpdateStmt *pNext;
  147089. };
  147090. /*
  147091. ** An iterator of this type is used to iterate through all objects in
  147092. ** the target database that require updating. For each such table, the
  147093. ** iterator visits, in order:
  147094. **
  147095. ** * the table itself,
  147096. ** * each index of the table (zero or more points to visit), and
  147097. ** * a special "cleanup table" state.
  147098. **
  147099. ** abIndexed:
  147100. ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
  147101. ** it points to an array of flags nTblCol elements in size. The flag is
  147102. ** set for each column that is either a part of the PK or a part of an
  147103. ** index. Or clear otherwise.
  147104. **
  147105. */
  147106. struct RbuObjIter {
  147107. sqlite3_stmt *pTblIter; /* Iterate through tables */
  147108. sqlite3_stmt *pIdxIter; /* Index iterator */
  147109. int nTblCol; /* Size of azTblCol[] array */
  147110. char **azTblCol; /* Array of unquoted target column names */
  147111. char **azTblType; /* Array of target column types */
  147112. int *aiSrcOrder; /* src table col -> target table col */
  147113. u8 *abTblPk; /* Array of flags, set on target PK columns */
  147114. u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
  147115. u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
  147116. int eType; /* Table type - an RBU_PK_XXX value */
  147117. /* Output variables. zTbl==0 implies EOF. */
  147118. int bCleanup; /* True in "cleanup" state */
  147119. const char *zTbl; /* Name of target db table */
  147120. const char *zIdx; /* Name of target db index (or null) */
  147121. int iTnum; /* Root page of current object */
  147122. int iPkTnum; /* If eType==EXTERNAL, root of PK index */
  147123. int bUnique; /* Current index is unique */
  147124. /* Statements created by rbuObjIterPrepareAll() */
  147125. int nCol; /* Number of columns in current object */
  147126. sqlite3_stmt *pSelect; /* Source data */
  147127. sqlite3_stmt *pInsert; /* Statement for INSERT operations */
  147128. sqlite3_stmt *pDelete; /* Statement for DELETE ops */
  147129. sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zTbl */
  147130. /* Last UPDATE used (for PK b-tree updates only), or NULL. */
  147131. RbuUpdateStmt *pRbuUpdate;
  147132. };
  147133. /*
  147134. ** Values for RbuObjIter.eType
  147135. **
  147136. ** 0: Table does not exist (error)
  147137. ** 1: Table has an implicit rowid.
  147138. ** 2: Table has an explicit IPK column.
  147139. ** 3: Table has an external PK index.
  147140. ** 4: Table is WITHOUT ROWID.
  147141. ** 5: Table is a virtual table.
  147142. */
  147143. #define RBU_PK_NOTABLE 0
  147144. #define RBU_PK_NONE 1
  147145. #define RBU_PK_IPK 2
  147146. #define RBU_PK_EXTERNAL 3
  147147. #define RBU_PK_WITHOUT_ROWID 4
  147148. #define RBU_PK_VTAB 5
  147149. /*
  147150. ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
  147151. ** one of the following operations.
  147152. */
  147153. #define RBU_INSERT 1 /* Insert on a main table b-tree */
  147154. #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
  147155. #define RBU_IDX_DELETE 3 /* Delete a row from an aux. index b-tree */
  147156. #define RBU_IDX_INSERT 4 /* Insert on an aux. index b-tree */
  147157. #define RBU_UPDATE 5 /* Update a row in a main table b-tree */
  147158. /*
  147159. ** A single step of an incremental checkpoint - frame iWalFrame of the wal
  147160. ** file should be copied to page iDbPage of the database file.
  147161. */
  147162. struct RbuFrame {
  147163. u32 iDbPage;
  147164. u32 iWalFrame;
  147165. };
  147166. /*
  147167. ** RBU handle.
  147168. */
  147169. struct sqlite3rbu {
  147170. int eStage; /* Value of RBU_STATE_STAGE field */
  147171. sqlite3 *dbMain; /* target database handle */
  147172. sqlite3 *dbRbu; /* rbu database handle */
  147173. char *zTarget; /* Path to target db */
  147174. char *zRbu; /* Path to rbu db */
  147175. char *zState; /* Path to state db (or NULL if zRbu) */
  147176. char zStateDb[5]; /* Db name for state ("stat" or "main") */
  147177. int rc; /* Value returned by last rbu_step() call */
  147178. char *zErrmsg; /* Error message if rc!=SQLITE_OK */
  147179. int nStep; /* Rows processed for current object */
  147180. int nProgress; /* Rows processed for all objects */
  147181. RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
  147182. const char *zVfsName; /* Name of automatically created rbu vfs */
  147183. rbu_file *pTargetFd; /* File handle open on target db */
  147184. i64 iOalSz;
  147185. /* The following state variables are used as part of the incremental
  147186. ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
  147187. ** function rbuSetupCheckpoint() for details. */
  147188. u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
  147189. u32 mLock;
  147190. int nFrame; /* Entries in aFrame[] array */
  147191. int nFrameAlloc; /* Allocated size of aFrame[] array */
  147192. RbuFrame *aFrame;
  147193. int pgsz;
  147194. u8 *aBuf;
  147195. i64 iWalCksum;
  147196. };
  147197. /*
  147198. ** An rbu VFS is implemented using an instance of this structure.
  147199. */
  147200. struct rbu_vfs {
  147201. sqlite3_vfs base; /* rbu VFS shim methods */
  147202. sqlite3_vfs *pRealVfs; /* Underlying VFS */
  147203. sqlite3_mutex *mutex; /* Mutex to protect pMain */
  147204. rbu_file *pMain; /* Linked list of main db files */
  147205. };
  147206. /*
  147207. ** Each file opened by an rbu VFS is represented by an instance of
  147208. ** the following structure.
  147209. */
  147210. struct rbu_file {
  147211. sqlite3_file base; /* sqlite3_file methods */
  147212. sqlite3_file *pReal; /* Underlying file handle */
  147213. rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
  147214. sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
  147215. int openFlags; /* Flags this file was opened with */
  147216. u32 iCookie; /* Cookie value for main db files */
  147217. u8 iWriteVer; /* "write-version" value for main db files */
  147218. int nShm; /* Number of entries in apShm[] array */
  147219. char **apShm; /* Array of mmap'd *-shm regions */
  147220. char *zDel; /* Delete this when closing file */
  147221. const char *zWal; /* Wal filename for this main db file */
  147222. rbu_file *pWalFd; /* Wal file descriptor for this main db */
  147223. rbu_file *pMainNext; /* Next MAIN_DB file */
  147224. };
  147225. /*
  147226. ** Prepare the SQL statement in buffer zSql against database handle db.
  147227. ** If successful, set *ppStmt to point to the new statement and return
  147228. ** SQLITE_OK.
  147229. **
  147230. ** Otherwise, if an error does occur, set *ppStmt to NULL and return
  147231. ** an SQLite error code. Additionally, set output variable *pzErrmsg to
  147232. ** point to a buffer containing an error message. It is the responsibility
  147233. ** of the caller to (eventually) free this buffer using sqlite3_free().
  147234. */
  147235. static int prepareAndCollectError(
  147236. sqlite3 *db,
  147237. sqlite3_stmt **ppStmt,
  147238. char **pzErrmsg,
  147239. const char *zSql
  147240. ){
  147241. int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
  147242. if( rc!=SQLITE_OK ){
  147243. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  147244. *ppStmt = 0;
  147245. }
  147246. return rc;
  147247. }
  147248. /*
  147249. ** Reset the SQL statement passed as the first argument. Return a copy
  147250. ** of the value returned by sqlite3_reset().
  147251. **
  147252. ** If an error has occurred, then set *pzErrmsg to point to a buffer
  147253. ** containing an error message. It is the responsibility of the caller
  147254. ** to eventually free this buffer using sqlite3_free().
  147255. */
  147256. static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
  147257. int rc = sqlite3_reset(pStmt);
  147258. if( rc!=SQLITE_OK ){
  147259. *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
  147260. }
  147261. return rc;
  147262. }
  147263. /*
  147264. ** Unless it is NULL, argument zSql points to a buffer allocated using
  147265. ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
  147266. ** statement against database db and frees the buffer. If statement
  147267. ** compilation is successful, *ppStmt is set to point to the new statement
  147268. ** handle and SQLITE_OK is returned.
  147269. **
  147270. ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
  147271. ** returned. In this case, *pzErrmsg may also be set to point to an error
  147272. ** message. It is the responsibility of the caller to free this error message
  147273. ** buffer using sqlite3_free().
  147274. **
  147275. ** If argument zSql is NULL, this function assumes that an OOM has occurred.
  147276. ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
  147277. */
  147278. static int prepareFreeAndCollectError(
  147279. sqlite3 *db,
  147280. sqlite3_stmt **ppStmt,
  147281. char **pzErrmsg,
  147282. char *zSql
  147283. ){
  147284. int rc;
  147285. assert( *pzErrmsg==0 );
  147286. if( zSql==0 ){
  147287. rc = SQLITE_NOMEM;
  147288. *ppStmt = 0;
  147289. }else{
  147290. rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
  147291. sqlite3_free(zSql);
  147292. }
  147293. return rc;
  147294. }
  147295. /*
  147296. ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
  147297. ** by an earlier call to rbuObjIterCacheTableInfo().
  147298. */
  147299. static void rbuObjIterFreeCols(RbuObjIter *pIter){
  147300. int i;
  147301. for(i=0; i<pIter->nTblCol; i++){
  147302. sqlite3_free(pIter->azTblCol[i]);
  147303. sqlite3_free(pIter->azTblType[i]);
  147304. }
  147305. sqlite3_free(pIter->azTblCol);
  147306. pIter->azTblCol = 0;
  147307. pIter->azTblType = 0;
  147308. pIter->aiSrcOrder = 0;
  147309. pIter->abTblPk = 0;
  147310. pIter->abNotNull = 0;
  147311. pIter->nTblCol = 0;
  147312. pIter->eType = 0; /* Invalid value */
  147313. }
  147314. /*
  147315. ** Finalize all statements and free all allocations that are specific to
  147316. ** the current object (table/index pair).
  147317. */
  147318. static void rbuObjIterClearStatements(RbuObjIter *pIter){
  147319. RbuUpdateStmt *pUp;
  147320. sqlite3_finalize(pIter->pSelect);
  147321. sqlite3_finalize(pIter->pInsert);
  147322. sqlite3_finalize(pIter->pDelete);
  147323. sqlite3_finalize(pIter->pTmpInsert);
  147324. pUp = pIter->pRbuUpdate;
  147325. while( pUp ){
  147326. RbuUpdateStmt *pTmp = pUp->pNext;
  147327. sqlite3_finalize(pUp->pUpdate);
  147328. sqlite3_free(pUp);
  147329. pUp = pTmp;
  147330. }
  147331. pIter->pSelect = 0;
  147332. pIter->pInsert = 0;
  147333. pIter->pDelete = 0;
  147334. pIter->pRbuUpdate = 0;
  147335. pIter->pTmpInsert = 0;
  147336. pIter->nCol = 0;
  147337. }
  147338. /*
  147339. ** Clean up any resources allocated as part of the iterator object passed
  147340. ** as the only argument.
  147341. */
  147342. static void rbuObjIterFinalize(RbuObjIter *pIter){
  147343. rbuObjIterClearStatements(pIter);
  147344. sqlite3_finalize(pIter->pTblIter);
  147345. sqlite3_finalize(pIter->pIdxIter);
  147346. rbuObjIterFreeCols(pIter);
  147347. memset(pIter, 0, sizeof(RbuObjIter));
  147348. }
  147349. /*
  147350. ** Advance the iterator to the next position.
  147351. **
  147352. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  147353. ** pointing to the next entry. Otherwise, an error code and message is
  147354. ** left in the RBU handle passed as the first argument. A copy of the
  147355. ** error code is returned.
  147356. */
  147357. static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
  147358. int rc = p->rc;
  147359. if( rc==SQLITE_OK ){
  147360. /* Free any SQLite statements used while processing the previous object */
  147361. rbuObjIterClearStatements(pIter);
  147362. if( pIter->zIdx==0 ){
  147363. rc = sqlite3_exec(p->dbMain,
  147364. "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
  147365. "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
  147366. "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
  147367. "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
  147368. , 0, 0, &p->zErrmsg
  147369. );
  147370. }
  147371. if( rc==SQLITE_OK ){
  147372. if( pIter->bCleanup ){
  147373. rbuObjIterFreeCols(pIter);
  147374. pIter->bCleanup = 0;
  147375. rc = sqlite3_step(pIter->pTblIter);
  147376. if( rc!=SQLITE_ROW ){
  147377. rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
  147378. pIter->zTbl = 0;
  147379. }else{
  147380. pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
  147381. rc = pIter->zTbl ? SQLITE_OK : SQLITE_NOMEM;
  147382. }
  147383. }else{
  147384. if( pIter->zIdx==0 ){
  147385. sqlite3_stmt *pIdx = pIter->pIdxIter;
  147386. rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
  147387. }
  147388. if( rc==SQLITE_OK ){
  147389. rc = sqlite3_step(pIter->pIdxIter);
  147390. if( rc!=SQLITE_ROW ){
  147391. rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
  147392. pIter->bCleanup = 1;
  147393. pIter->zIdx = 0;
  147394. }else{
  147395. pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
  147396. pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
  147397. pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
  147398. rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
  147399. }
  147400. }
  147401. }
  147402. }
  147403. }
  147404. if( rc!=SQLITE_OK ){
  147405. rbuObjIterFinalize(pIter);
  147406. p->rc = rc;
  147407. }
  147408. return rc;
  147409. }
  147410. /*
  147411. ** Initialize the iterator structure passed as the second argument.
  147412. **
  147413. ** If no error occurs, SQLITE_OK is returned and the iterator is left
  147414. ** pointing to the first entry. Otherwise, an error code and message is
  147415. ** left in the RBU handle passed as the first argument. A copy of the
  147416. ** error code is returned.
  147417. */
  147418. static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
  147419. int rc;
  147420. memset(pIter, 0, sizeof(RbuObjIter));
  147421. rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
  147422. "SELECT substr(name, 6) FROM sqlite_master "
  147423. "WHERE type IN ('table', 'view') AND name LIKE 'data_%'"
  147424. );
  147425. if( rc==SQLITE_OK ){
  147426. rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
  147427. "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
  147428. " FROM main.sqlite_master "
  147429. " WHERE type='index' AND tbl_name = ?"
  147430. );
  147431. }
  147432. pIter->bCleanup = 1;
  147433. p->rc = rc;
  147434. return rbuObjIterNext(p, pIter);
  147435. }
  147436. /*
  147437. ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
  147438. ** an error code is stored in the RBU handle passed as the first argument.
  147439. **
  147440. ** If an error has already occurred (p->rc is already set to something other
  147441. ** than SQLITE_OK), then this function returns NULL without modifying the
  147442. ** stored error code. In this case it still calls sqlite3_free() on any
  147443. ** printf() parameters associated with %z conversions.
  147444. */
  147445. static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
  147446. char *zSql = 0;
  147447. va_list ap;
  147448. va_start(ap, zFmt);
  147449. zSql = sqlite3_vmprintf(zFmt, ap);
  147450. if( p->rc==SQLITE_OK ){
  147451. if( zSql==0 ) p->rc = SQLITE_NOMEM;
  147452. }else{
  147453. sqlite3_free(zSql);
  147454. zSql = 0;
  147455. }
  147456. va_end(ap);
  147457. return zSql;
  147458. }
  147459. /*
  147460. ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
  147461. ** arguments are the usual subsitution values. This function performs
  147462. ** the printf() style substitutions and executes the result as an SQL
  147463. ** statement on the RBU handles database.
  147464. **
  147465. ** If an error occurs, an error code and error message is stored in the
  147466. ** RBU handle. If an error has already occurred when this function is
  147467. ** called, it is a no-op.
  147468. */
  147469. static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
  147470. va_list ap;
  147471. char *zSql;
  147472. va_start(ap, zFmt);
  147473. zSql = sqlite3_vmprintf(zFmt, ap);
  147474. if( p->rc==SQLITE_OK ){
  147475. if( zSql==0 ){
  147476. p->rc = SQLITE_NOMEM;
  147477. }else{
  147478. p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
  147479. }
  147480. }
  147481. sqlite3_free(zSql);
  147482. va_end(ap);
  147483. return p->rc;
  147484. }
  147485. /*
  147486. ** Attempt to allocate and return a pointer to a zeroed block of nByte
  147487. ** bytes.
  147488. **
  147489. ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
  147490. ** error code in the rbu handle passed as the first argument. Or, if an
  147491. ** error has already occurred when this function is called, return NULL
  147492. ** immediately without attempting the allocation or modifying the stored
  147493. ** error code.
  147494. */
  147495. static void *rbuMalloc(sqlite3rbu *p, int nByte){
  147496. void *pRet = 0;
  147497. if( p->rc==SQLITE_OK ){
  147498. assert( nByte>0 );
  147499. pRet = sqlite3_malloc(nByte);
  147500. if( pRet==0 ){
  147501. p->rc = SQLITE_NOMEM;
  147502. }else{
  147503. memset(pRet, 0, nByte);
  147504. }
  147505. }
  147506. return pRet;
  147507. }
  147508. /*
  147509. ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
  147510. ** there is room for at least nCol elements. If an OOM occurs, store an
  147511. ** error code in the RBU handle passed as the first argument.
  147512. */
  147513. static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
  147514. int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
  147515. char **azNew;
  147516. azNew = (char**)rbuMalloc(p, nByte);
  147517. if( azNew ){
  147518. pIter->azTblCol = azNew;
  147519. pIter->azTblType = &azNew[nCol];
  147520. pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
  147521. pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
  147522. pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
  147523. pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
  147524. }
  147525. }
  147526. /*
  147527. ** The first argument must be a nul-terminated string. This function
  147528. ** returns a copy of the string in memory obtained from sqlite3_malloc().
  147529. ** It is the responsibility of the caller to eventually free this memory
  147530. ** using sqlite3_free().
  147531. **
  147532. ** If an OOM condition is encountered when attempting to allocate memory,
  147533. ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
  147534. ** if the allocation succeeds, (*pRc) is left unchanged.
  147535. */
  147536. static char *rbuStrndup(const char *zStr, int *pRc){
  147537. char *zRet = 0;
  147538. assert( *pRc==SQLITE_OK );
  147539. if( zStr ){
  147540. int nCopy = strlen(zStr) + 1;
  147541. zRet = (char*)sqlite3_malloc(nCopy);
  147542. if( zRet ){
  147543. memcpy(zRet, zStr, nCopy);
  147544. }else{
  147545. *pRc = SQLITE_NOMEM;
  147546. }
  147547. }
  147548. return zRet;
  147549. }
  147550. /*
  147551. ** Finalize the statement passed as the second argument.
  147552. **
  147553. ** If the sqlite3_finalize() call indicates that an error occurs, and the
  147554. ** rbu handle error code is not already set, set the error code and error
  147555. ** message accordingly.
  147556. */
  147557. static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
  147558. sqlite3 *db = sqlite3_db_handle(pStmt);
  147559. int rc = sqlite3_finalize(pStmt);
  147560. if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
  147561. p->rc = rc;
  147562. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  147563. }
  147564. }
  147565. /* Determine the type of a table.
  147566. **
  147567. ** peType is of type (int*), a pointer to an output parameter of type
  147568. ** (int). This call sets the output parameter as follows, depending
  147569. ** on the type of the table specified by parameters dbName and zTbl.
  147570. **
  147571. ** RBU_PK_NOTABLE: No such table.
  147572. ** RBU_PK_NONE: Table has an implicit rowid.
  147573. ** RBU_PK_IPK: Table has an explicit IPK column.
  147574. ** RBU_PK_EXTERNAL: Table has an external PK index.
  147575. ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
  147576. ** RBU_PK_VTAB: Table is a virtual table.
  147577. **
  147578. ** Argument *piPk is also of type (int*), and also points to an output
  147579. ** parameter. Unless the table has an external primary key index
  147580. ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
  147581. ** if the table does have an external primary key index, then *piPk
  147582. ** is set to the root page number of the primary key index before
  147583. ** returning.
  147584. **
  147585. ** ALGORITHM:
  147586. **
  147587. ** if( no entry exists in sqlite_master ){
  147588. ** return RBU_PK_NOTABLE
  147589. ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
  147590. ** return RBU_PK_VTAB
  147591. ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
  147592. ** if( the index that is the pk exists in sqlite_master ){
  147593. ** *piPK = rootpage of that index.
  147594. ** return RBU_PK_EXTERNAL
  147595. ** }else{
  147596. ** return RBU_PK_WITHOUT_ROWID
  147597. ** }
  147598. ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
  147599. ** return RBU_PK_IPK
  147600. ** }else{
  147601. ** return RBU_PK_NONE
  147602. ** }
  147603. */
  147604. static void rbuTableType(
  147605. sqlite3rbu *p,
  147606. const char *zTab,
  147607. int *peType,
  147608. int *piTnum,
  147609. int *piPk
  147610. ){
  147611. /*
  147612. ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
  147613. ** 1) PRAGMA index_list = ?
  147614. ** 2) SELECT count(*) FROM sqlite_master where name=%Q
  147615. ** 3) PRAGMA table_info = ?
  147616. */
  147617. sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
  147618. *peType = RBU_PK_NOTABLE;
  147619. *piPk = 0;
  147620. assert( p->rc==SQLITE_OK );
  147621. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
  147622. sqlite3_mprintf(
  147623. "SELECT (sql LIKE 'create virtual%%'), rootpage"
  147624. " FROM sqlite_master"
  147625. " WHERE name=%Q", zTab
  147626. ));
  147627. if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
  147628. /* Either an error, or no such table. */
  147629. goto rbuTableType_end;
  147630. }
  147631. if( sqlite3_column_int(aStmt[0], 0) ){
  147632. *peType = RBU_PK_VTAB; /* virtual table */
  147633. goto rbuTableType_end;
  147634. }
  147635. *piTnum = sqlite3_column_int(aStmt[0], 1);
  147636. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
  147637. sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
  147638. );
  147639. if( p->rc ) goto rbuTableType_end;
  147640. while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
  147641. const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
  147642. const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
  147643. if( zOrig && zIdx && zOrig[0]=='p' ){
  147644. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
  147645. sqlite3_mprintf(
  147646. "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
  147647. ));
  147648. if( p->rc==SQLITE_OK ){
  147649. if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
  147650. *piPk = sqlite3_column_int(aStmt[2], 0);
  147651. *peType = RBU_PK_EXTERNAL;
  147652. }else{
  147653. *peType = RBU_PK_WITHOUT_ROWID;
  147654. }
  147655. }
  147656. goto rbuTableType_end;
  147657. }
  147658. }
  147659. p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
  147660. sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
  147661. );
  147662. if( p->rc==SQLITE_OK ){
  147663. while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
  147664. if( sqlite3_column_int(aStmt[3],5)>0 ){
  147665. *peType = RBU_PK_IPK; /* explicit IPK column */
  147666. goto rbuTableType_end;
  147667. }
  147668. }
  147669. *peType = RBU_PK_NONE;
  147670. }
  147671. rbuTableType_end: {
  147672. int i;
  147673. for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
  147674. rbuFinalize(p, aStmt[i]);
  147675. }
  147676. }
  147677. }
  147678. /*
  147679. ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
  147680. ** the pIter->abIndexed[] array.
  147681. */
  147682. static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
  147683. sqlite3_stmt *pList = 0;
  147684. int bIndex = 0;
  147685. if( p->rc==SQLITE_OK ){
  147686. memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
  147687. p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
  147688. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  147689. );
  147690. }
  147691. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
  147692. const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
  147693. sqlite3_stmt *pXInfo = 0;
  147694. if( zIdx==0 ) break;
  147695. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  147696. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  147697. );
  147698. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  147699. int iCid = sqlite3_column_int(pXInfo, 1);
  147700. if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
  147701. }
  147702. rbuFinalize(p, pXInfo);
  147703. bIndex = 1;
  147704. }
  147705. rbuFinalize(p, pList);
  147706. if( bIndex==0 ) pIter->abIndexed = 0;
  147707. }
  147708. /*
  147709. ** If they are not already populated, populate the pIter->azTblCol[],
  147710. ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
  147711. ** the table (not index) that the iterator currently points to.
  147712. **
  147713. ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
  147714. ** an error does occur, an error code and error message are also left in
  147715. ** the RBU handle.
  147716. */
  147717. static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
  147718. if( pIter->azTblCol==0 ){
  147719. sqlite3_stmt *pStmt = 0;
  147720. int nCol = 0;
  147721. int i; /* for() loop iterator variable */
  147722. int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
  147723. int iOrder = 0;
  147724. int iTnum = 0;
  147725. /* Figure out the type of table this step will deal with. */
  147726. assert( pIter->eType==0 );
  147727. rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
  147728. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
  147729. p->rc = SQLITE_ERROR;
  147730. p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
  147731. }
  147732. if( p->rc ) return p->rc;
  147733. if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
  147734. assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
  147735. || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
  147736. || pIter->eType==RBU_PK_VTAB
  147737. );
  147738. /* Populate the azTblCol[] and nTblCol variables based on the columns
  147739. ** of the input table. Ignore any input table columns that begin with
  147740. ** "rbu_". */
  147741. p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  147742. sqlite3_mprintf("SELECT * FROM 'data_%q'", pIter->zTbl)
  147743. );
  147744. if( p->rc==SQLITE_OK ){
  147745. nCol = sqlite3_column_count(pStmt);
  147746. rbuAllocateIterArrays(p, pIter, nCol);
  147747. }
  147748. for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
  147749. const char *zName = (const char*)sqlite3_column_name(pStmt, i);
  147750. if( sqlite3_strnicmp("rbu_", zName, 4) ){
  147751. char *zCopy = rbuStrndup(zName, &p->rc);
  147752. pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
  147753. pIter->azTblCol[pIter->nTblCol++] = zCopy;
  147754. }
  147755. else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
  147756. bRbuRowid = 1;
  147757. }
  147758. }
  147759. sqlite3_finalize(pStmt);
  147760. pStmt = 0;
  147761. if( p->rc==SQLITE_OK
  147762. && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  147763. ){
  147764. p->rc = SQLITE_ERROR;
  147765. p->zErrmsg = sqlite3_mprintf(
  147766. "table data_%q %s rbu_rowid column", pIter->zTbl,
  147767. (bRbuRowid ? "may not have" : "requires")
  147768. );
  147769. }
  147770. /* Check that all non-HIDDEN columns in the destination table are also
  147771. ** present in the input table. Populate the abTblPk[], azTblType[] and
  147772. ** aiTblOrder[] arrays at the same time. */
  147773. if( p->rc==SQLITE_OK ){
  147774. p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  147775. sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
  147776. );
  147777. }
  147778. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  147779. const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
  147780. if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
  147781. for(i=iOrder; i<pIter->nTblCol; i++){
  147782. if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
  147783. }
  147784. if( i==pIter->nTblCol ){
  147785. p->rc = SQLITE_ERROR;
  147786. p->zErrmsg = sqlite3_mprintf("column missing from data_%q: %s",
  147787. pIter->zTbl, zName
  147788. );
  147789. }else{
  147790. int iPk = sqlite3_column_int(pStmt, 5);
  147791. int bNotNull = sqlite3_column_int(pStmt, 3);
  147792. const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
  147793. if( i!=iOrder ){
  147794. SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
  147795. SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
  147796. }
  147797. pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
  147798. pIter->abTblPk[iOrder] = (iPk!=0);
  147799. pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
  147800. iOrder++;
  147801. }
  147802. }
  147803. rbuFinalize(p, pStmt);
  147804. rbuObjIterCacheIndexedCols(p, pIter);
  147805. assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
  147806. }
  147807. return p->rc;
  147808. }
  147809. /*
  147810. ** This function constructs and returns a pointer to a nul-terminated
  147811. ** string containing some SQL clause or list based on one or more of the
  147812. ** column names currently stored in the pIter->azTblCol[] array.
  147813. */
  147814. static char *rbuObjIterGetCollist(
  147815. sqlite3rbu *p, /* RBU object */
  147816. RbuObjIter *pIter /* Object iterator for column names */
  147817. ){
  147818. char *zList = 0;
  147819. const char *zSep = "";
  147820. int i;
  147821. for(i=0; i<pIter->nTblCol; i++){
  147822. const char *z = pIter->azTblCol[i];
  147823. zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
  147824. zSep = ", ";
  147825. }
  147826. return zList;
  147827. }
  147828. /*
  147829. ** This function is used to create a SELECT list (the list of SQL
  147830. ** expressions that follows a SELECT keyword) for a SELECT statement
  147831. ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
  147832. ** index object currently indicated by the iterator object passed as the
  147833. ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
  147834. ** to obtain the required information.
  147835. **
  147836. ** If the index is of the following form:
  147837. **
  147838. ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
  147839. **
  147840. ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
  147841. ** "ipk", the returned string is:
  147842. **
  147843. ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
  147844. **
  147845. ** As well as the returned string, three other malloc'd strings are
  147846. ** returned via output parameters. As follows:
  147847. **
  147848. ** pzImposterCols: ...
  147849. ** pzImposterPk: ...
  147850. ** pzWhere: ...
  147851. */
  147852. static char *rbuObjIterGetIndexCols(
  147853. sqlite3rbu *p, /* RBU object */
  147854. RbuObjIter *pIter, /* Object iterator for column names */
  147855. char **pzImposterCols, /* OUT: Columns for imposter table */
  147856. char **pzImposterPk, /* OUT: Imposter PK clause */
  147857. char **pzWhere, /* OUT: WHERE clause */
  147858. int *pnBind /* OUT: Trbul number of columns */
  147859. ){
  147860. int rc = p->rc; /* Error code */
  147861. int rc2; /* sqlite3_finalize() return code */
  147862. char *zRet = 0; /* String to return */
  147863. char *zImpCols = 0; /* String to return via *pzImposterCols */
  147864. char *zImpPK = 0; /* String to return via *pzImposterPK */
  147865. char *zWhere = 0; /* String to return via *pzWhere */
  147866. int nBind = 0; /* Value to return via *pnBind */
  147867. const char *zCom = ""; /* Set to ", " later on */
  147868. const char *zAnd = ""; /* Set to " AND " later on */
  147869. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
  147870. if( rc==SQLITE_OK ){
  147871. assert( p->zErrmsg==0 );
  147872. rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  147873. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
  147874. );
  147875. }
  147876. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  147877. int iCid = sqlite3_column_int(pXInfo, 1);
  147878. int bDesc = sqlite3_column_int(pXInfo, 3);
  147879. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  147880. const char *zCol;
  147881. const char *zType;
  147882. if( iCid<0 ){
  147883. /* An integer primary key. If the table has an explicit IPK, use
  147884. ** its name. Otherwise, use "rbu_rowid". */
  147885. if( pIter->eType==RBU_PK_IPK ){
  147886. int i;
  147887. for(i=0; pIter->abTblPk[i]==0; i++);
  147888. assert( i<pIter->nTblCol );
  147889. zCol = pIter->azTblCol[i];
  147890. }else{
  147891. zCol = "rbu_rowid";
  147892. }
  147893. zType = "INTEGER";
  147894. }else{
  147895. zCol = pIter->azTblCol[iCid];
  147896. zType = pIter->azTblType[iCid];
  147897. }
  147898. zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
  147899. if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
  147900. const char *zOrder = (bDesc ? " DESC" : "");
  147901. zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
  147902. zImpPK, zCom, nBind, zCol, zOrder
  147903. );
  147904. }
  147905. zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
  147906. zImpCols, zCom, nBind, zCol, zType, zCollate
  147907. );
  147908. zWhere = sqlite3_mprintf(
  147909. "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
  147910. );
  147911. if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
  147912. zCom = ", ";
  147913. zAnd = " AND ";
  147914. nBind++;
  147915. }
  147916. rc2 = sqlite3_finalize(pXInfo);
  147917. if( rc==SQLITE_OK ) rc = rc2;
  147918. if( rc!=SQLITE_OK ){
  147919. sqlite3_free(zRet);
  147920. sqlite3_free(zImpCols);
  147921. sqlite3_free(zImpPK);
  147922. sqlite3_free(zWhere);
  147923. zRet = 0;
  147924. zImpCols = 0;
  147925. zImpPK = 0;
  147926. zWhere = 0;
  147927. p->rc = rc;
  147928. }
  147929. *pzImposterCols = zImpCols;
  147930. *pzImposterPk = zImpPK;
  147931. *pzWhere = zWhere;
  147932. *pnBind = nBind;
  147933. return zRet;
  147934. }
  147935. /*
  147936. ** Assuming the current table columns are "a", "b" and "c", and the zObj
  147937. ** paramter is passed "old", return a string of the form:
  147938. **
  147939. ** "old.a, old.b, old.b"
  147940. **
  147941. ** With the column names escaped.
  147942. **
  147943. ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
  147944. ** the text ", old._rowid_" to the returned value.
  147945. */
  147946. static char *rbuObjIterGetOldlist(
  147947. sqlite3rbu *p,
  147948. RbuObjIter *pIter,
  147949. const char *zObj
  147950. ){
  147951. char *zList = 0;
  147952. if( p->rc==SQLITE_OK && pIter->abIndexed ){
  147953. const char *zS = "";
  147954. int i;
  147955. for(i=0; i<pIter->nTblCol; i++){
  147956. if( pIter->abIndexed[i] ){
  147957. const char *zCol = pIter->azTblCol[i];
  147958. zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
  147959. }else{
  147960. zList = sqlite3_mprintf("%z%sNULL", zList, zS);
  147961. }
  147962. zS = ", ";
  147963. if( zList==0 ){
  147964. p->rc = SQLITE_NOMEM;
  147965. break;
  147966. }
  147967. }
  147968. /* For a table with implicit rowids, append "old._rowid_" to the list. */
  147969. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  147970. zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
  147971. }
  147972. }
  147973. return zList;
  147974. }
  147975. /*
  147976. ** Return an expression that can be used in a WHERE clause to match the
  147977. ** primary key of the current table. For example, if the table is:
  147978. **
  147979. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
  147980. **
  147981. ** Return the string:
  147982. **
  147983. ** "b = ?1 AND c = ?2"
  147984. */
  147985. static char *rbuObjIterGetWhere(
  147986. sqlite3rbu *p,
  147987. RbuObjIter *pIter
  147988. ){
  147989. char *zList = 0;
  147990. if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
  147991. zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
  147992. }else if( pIter->eType==RBU_PK_EXTERNAL ){
  147993. const char *zSep = "";
  147994. int i;
  147995. for(i=0; i<pIter->nTblCol; i++){
  147996. if( pIter->abTblPk[i] ){
  147997. zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
  147998. zSep = " AND ";
  147999. }
  148000. }
  148001. zList = rbuMPrintf(p,
  148002. "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
  148003. );
  148004. }else{
  148005. const char *zSep = "";
  148006. int i;
  148007. for(i=0; i<pIter->nTblCol; i++){
  148008. if( pIter->abTblPk[i] ){
  148009. const char *zCol = pIter->azTblCol[i];
  148010. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
  148011. zSep = " AND ";
  148012. }
  148013. }
  148014. }
  148015. return zList;
  148016. }
  148017. /*
  148018. ** The SELECT statement iterating through the keys for the current object
  148019. ** (p->objiter.pSelect) currently points to a valid row. However, there
  148020. ** is something wrong with the rbu_control value in the rbu_control value
  148021. ** stored in the (p->nCol+1)'th column. Set the error code and error message
  148022. ** of the RBU handle to something reflecting this.
  148023. */
  148024. static void rbuBadControlError(sqlite3rbu *p){
  148025. p->rc = SQLITE_ERROR;
  148026. p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
  148027. }
  148028. /*
  148029. ** Return a nul-terminated string containing the comma separated list of
  148030. ** assignments that should be included following the "SET" keyword of
  148031. ** an UPDATE statement used to update the table object that the iterator
  148032. ** passed as the second argument currently points to if the rbu_control
  148033. ** column of the data_xxx table entry is set to zMask.
  148034. **
  148035. ** The memory for the returned string is obtained from sqlite3_malloc().
  148036. ** It is the responsibility of the caller to eventually free it using
  148037. ** sqlite3_free().
  148038. **
  148039. ** If an OOM error is encountered when allocating space for the new
  148040. ** string, an error code is left in the rbu handle passed as the first
  148041. ** argument and NULL is returned. Or, if an error has already occurred
  148042. ** when this function is called, NULL is returned immediately, without
  148043. ** attempting the allocation or modifying the stored error code.
  148044. */
  148045. static char *rbuObjIterGetSetlist(
  148046. sqlite3rbu *p,
  148047. RbuObjIter *pIter,
  148048. const char *zMask
  148049. ){
  148050. char *zList = 0;
  148051. if( p->rc==SQLITE_OK ){
  148052. int i;
  148053. if( strlen(zMask)!=pIter->nTblCol ){
  148054. rbuBadControlError(p);
  148055. }else{
  148056. const char *zSep = "";
  148057. for(i=0; i<pIter->nTblCol; i++){
  148058. char c = zMask[pIter->aiSrcOrder[i]];
  148059. if( c=='x' ){
  148060. zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
  148061. zList, zSep, pIter->azTblCol[i], i+1
  148062. );
  148063. zSep = ", ";
  148064. }
  148065. if( c=='d' ){
  148066. zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
  148067. zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
  148068. );
  148069. zSep = ", ";
  148070. }
  148071. }
  148072. }
  148073. }
  148074. return zList;
  148075. }
  148076. /*
  148077. ** Return a nul-terminated string consisting of nByte comma separated
  148078. ** "?" expressions. For example, if nByte is 3, return a pointer to
  148079. ** a buffer containing the string "?,?,?".
  148080. **
  148081. ** The memory for the returned string is obtained from sqlite3_malloc().
  148082. ** It is the responsibility of the caller to eventually free it using
  148083. ** sqlite3_free().
  148084. **
  148085. ** If an OOM error is encountered when allocating space for the new
  148086. ** string, an error code is left in the rbu handle passed as the first
  148087. ** argument and NULL is returned. Or, if an error has already occurred
  148088. ** when this function is called, NULL is returned immediately, without
  148089. ** attempting the allocation or modifying the stored error code.
  148090. */
  148091. static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
  148092. char *zRet = 0;
  148093. int nByte = nBind*2 + 1;
  148094. zRet = (char*)rbuMalloc(p, nByte);
  148095. if( zRet ){
  148096. int i;
  148097. for(i=0; i<nBind; i++){
  148098. zRet[i*2] = '?';
  148099. zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
  148100. }
  148101. }
  148102. return zRet;
  148103. }
  148104. /*
  148105. ** The iterator currently points to a table (not index) of type
  148106. ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
  148107. ** declaration for the corresponding imposter table. For example,
  148108. ** if the iterator points to a table created as:
  148109. **
  148110. ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
  148111. **
  148112. ** this function returns:
  148113. **
  148114. ** PRIMARY KEY("b", "a" DESC)
  148115. */
  148116. static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
  148117. char *z = 0;
  148118. assert( pIter->zIdx==0 );
  148119. if( p->rc==SQLITE_OK ){
  148120. const char *zSep = "PRIMARY KEY(";
  148121. sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
  148122. sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
  148123. p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
  148124. sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
  148125. );
  148126. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
  148127. const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
  148128. if( zOrig && strcmp(zOrig, "pk")==0 ){
  148129. const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
  148130. if( zIdx ){
  148131. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  148132. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  148133. );
  148134. }
  148135. break;
  148136. }
  148137. }
  148138. rbuFinalize(p, pXList);
  148139. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  148140. if( sqlite3_column_int(pXInfo, 5) ){
  148141. /* int iCid = sqlite3_column_int(pXInfo, 0); */
  148142. const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
  148143. const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
  148144. z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
  148145. zSep = ", ";
  148146. }
  148147. }
  148148. z = rbuMPrintf(p, "%z)", z);
  148149. rbuFinalize(p, pXInfo);
  148150. }
  148151. return z;
  148152. }
  148153. /*
  148154. ** This function creates the second imposter table used when writing to
  148155. ** a table b-tree where the table has an external primary key. If the
  148156. ** iterator passed as the second argument does not currently point to
  148157. ** a table (not index) with an external primary key, this function is a
  148158. ** no-op.
  148159. **
  148160. ** Assuming the iterator does point to a table with an external PK, this
  148161. ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
  148162. ** used to access that PK index. For example, if the target table is
  148163. ** declared as follows:
  148164. **
  148165. ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
  148166. **
  148167. ** then the imposter table schema is:
  148168. **
  148169. ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
  148170. **
  148171. */
  148172. static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
  148173. if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
  148174. int tnum = pIter->iPkTnum; /* Root page of PK index */
  148175. sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
  148176. const char *zIdx = 0; /* Name of PK index */
  148177. sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
  148178. const char *zComma = "";
  148179. char *zCols = 0; /* Used to build up list of table cols */
  148180. char *zPk = 0; /* Used to build up table PK declaration */
  148181. /* Figure out the name of the primary key index for the current table.
  148182. ** This is needed for the argument to "PRAGMA index_xinfo". Set
  148183. ** zIdx to point to a nul-terminated string containing this name. */
  148184. p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
  148185. "SELECT name FROM sqlite_master WHERE rootpage = ?"
  148186. );
  148187. if( p->rc==SQLITE_OK ){
  148188. sqlite3_bind_int(pQuery, 1, tnum);
  148189. if( SQLITE_ROW==sqlite3_step(pQuery) ){
  148190. zIdx = (const char*)sqlite3_column_text(pQuery, 0);
  148191. }
  148192. }
  148193. if( zIdx ){
  148194. p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
  148195. sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
  148196. );
  148197. }
  148198. rbuFinalize(p, pQuery);
  148199. while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
  148200. int bKey = sqlite3_column_int(pXInfo, 5);
  148201. if( bKey ){
  148202. int iCid = sqlite3_column_int(pXInfo, 1);
  148203. int bDesc = sqlite3_column_int(pXInfo, 3);
  148204. const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
  148205. zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
  148206. iCid, pIter->azTblType[iCid], zCollate
  148207. );
  148208. zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
  148209. zComma = ", ";
  148210. }
  148211. }
  148212. zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
  148213. rbuFinalize(p, pXInfo);
  148214. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  148215. rbuMPrintfExec(p, p->dbMain,
  148216. "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
  148217. zCols, zPk
  148218. );
  148219. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  148220. }
  148221. }
  148222. /*
  148223. ** If an error has already occurred when this function is called, it
  148224. ** immediately returns zero (without doing any work). Or, if an error
  148225. ** occurs during the execution of this function, it sets the error code
  148226. ** in the sqlite3rbu object indicated by the first argument and returns
  148227. ** zero.
  148228. **
  148229. ** The iterator passed as the second argument is guaranteed to point to
  148230. ** a table (not an index) when this function is called. This function
  148231. ** attempts to create any imposter table required to write to the main
  148232. ** table b-tree of the table before returning. Non-zero is returned if
  148233. ** an imposter table are created, or zero otherwise.
  148234. **
  148235. ** An imposter table is required in all cases except RBU_PK_VTAB. Only
  148236. ** virtual tables are written to directly. The imposter table has the
  148237. ** same schema as the actual target table (less any UNIQUE constraints).
  148238. ** More precisely, the "same schema" means the same columns, types,
  148239. ** collation sequences. For tables that do not have an external PRIMARY
  148240. ** KEY, it also means the same PRIMARY KEY declaration.
  148241. */
  148242. static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
  148243. if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
  148244. int tnum = pIter->iTnum;
  148245. const char *zComma = "";
  148246. char *zSql = 0;
  148247. int iCol;
  148248. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  148249. for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
  148250. const char *zPk = "";
  148251. const char *zCol = pIter->azTblCol[iCol];
  148252. const char *zColl = 0;
  148253. p->rc = sqlite3_table_column_metadata(
  148254. p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
  148255. );
  148256. if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
  148257. /* If the target table column is an "INTEGER PRIMARY KEY", add
  148258. ** "PRIMARY KEY" to the imposter table column declaration. */
  148259. zPk = "PRIMARY KEY ";
  148260. }
  148261. zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
  148262. zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
  148263. (pIter->abNotNull[iCol] ? " NOT NULL" : "")
  148264. );
  148265. zComma = ", ";
  148266. }
  148267. if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
  148268. char *zPk = rbuWithoutRowidPK(p, pIter);
  148269. if( zPk ){
  148270. zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
  148271. }
  148272. }
  148273. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
  148274. rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
  148275. pIter->zTbl, zSql,
  148276. (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
  148277. );
  148278. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  148279. }
  148280. }
  148281. /*
  148282. ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
  148283. ** Specifically a statement of the form:
  148284. **
  148285. ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
  148286. **
  148287. ** The number of bound variables is equal to the number of columns in
  148288. ** the target table, plus one (for the rbu_control column), plus one more
  148289. ** (for the rbu_rowid column) if the target table is an implicit IPK or
  148290. ** virtual table.
  148291. */
  148292. static void rbuObjIterPrepareTmpInsert(
  148293. sqlite3rbu *p,
  148294. RbuObjIter *pIter,
  148295. const char *zCollist,
  148296. const char *zRbuRowid
  148297. ){
  148298. int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
  148299. char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
  148300. if( zBind ){
  148301. assert( pIter->pTmpInsert==0 );
  148302. p->rc = prepareFreeAndCollectError(
  148303. p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
  148304. "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
  148305. p->zStateDb, pIter->zTbl, zCollist, zRbuRowid, zBind
  148306. ));
  148307. }
  148308. }
  148309. static void rbuTmpInsertFunc(
  148310. sqlite3_context *pCtx,
  148311. int nVal,
  148312. sqlite3_value **apVal
  148313. ){
  148314. sqlite3rbu *p = sqlite3_user_data(pCtx);
  148315. int rc = SQLITE_OK;
  148316. int i;
  148317. for(i=0; rc==SQLITE_OK && i<nVal; i++){
  148318. rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
  148319. }
  148320. if( rc==SQLITE_OK ){
  148321. sqlite3_step(p->objiter.pTmpInsert);
  148322. rc = sqlite3_reset(p->objiter.pTmpInsert);
  148323. }
  148324. if( rc!=SQLITE_OK ){
  148325. sqlite3_result_error_code(pCtx, rc);
  148326. }
  148327. }
  148328. /*
  148329. ** Ensure that the SQLite statement handles required to update the
  148330. ** target database object currently indicated by the iterator passed
  148331. ** as the second argument are available.
  148332. */
  148333. static int rbuObjIterPrepareAll(
  148334. sqlite3rbu *p,
  148335. RbuObjIter *pIter,
  148336. int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
  148337. ){
  148338. assert( pIter->bCleanup==0 );
  148339. if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
  148340. const int tnum = pIter->iTnum;
  148341. char *zCollist = 0; /* List of indexed columns */
  148342. char **pz = &p->zErrmsg;
  148343. const char *zIdx = pIter->zIdx;
  148344. char *zLimit = 0;
  148345. if( nOffset ){
  148346. zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
  148347. if( !zLimit ) p->rc = SQLITE_NOMEM;
  148348. }
  148349. if( zIdx ){
  148350. const char *zTbl = pIter->zTbl;
  148351. char *zImposterCols = 0; /* Columns for imposter table */
  148352. char *zImposterPK = 0; /* Primary key declaration for imposter */
  148353. char *zWhere = 0; /* WHERE clause on PK columns */
  148354. char *zBind = 0;
  148355. int nBind = 0;
  148356. assert( pIter->eType!=RBU_PK_VTAB );
  148357. zCollist = rbuObjIterGetIndexCols(
  148358. p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
  148359. );
  148360. zBind = rbuObjIterGetBindlist(p, nBind);
  148361. /* Create the imposter table used to write to this index. */
  148362. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
  148363. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
  148364. rbuMPrintfExec(p, p->dbMain,
  148365. "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
  148366. zTbl, zImposterCols, zImposterPK
  148367. );
  148368. sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
  148369. /* Create the statement to insert index entries */
  148370. pIter->nCol = nBind;
  148371. if( p->rc==SQLITE_OK ){
  148372. p->rc = prepareFreeAndCollectError(
  148373. p->dbMain, &pIter->pInsert, &p->zErrmsg,
  148374. sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
  148375. );
  148376. }
  148377. /* And to delete index entries */
  148378. if( p->rc==SQLITE_OK ){
  148379. p->rc = prepareFreeAndCollectError(
  148380. p->dbMain, &pIter->pDelete, &p->zErrmsg,
  148381. sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
  148382. );
  148383. }
  148384. /* Create the SELECT statement to read keys in sorted order */
  148385. if( p->rc==SQLITE_OK ){
  148386. char *zSql;
  148387. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  148388. zSql = sqlite3_mprintf(
  148389. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
  148390. zCollist, p->zStateDb, pIter->zTbl,
  148391. zCollist, zLimit
  148392. );
  148393. }else{
  148394. zSql = sqlite3_mprintf(
  148395. "SELECT %s, rbu_control FROM 'data_%q' "
  148396. "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
  148397. "UNION ALL "
  148398. "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
  148399. "ORDER BY %s%s",
  148400. zCollist, pIter->zTbl,
  148401. zCollist, p->zStateDb, pIter->zTbl,
  148402. zCollist, zLimit
  148403. );
  148404. }
  148405. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
  148406. }
  148407. sqlite3_free(zImposterCols);
  148408. sqlite3_free(zImposterPK);
  148409. sqlite3_free(zWhere);
  148410. sqlite3_free(zBind);
  148411. }else{
  148412. int bRbuRowid = (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE);
  148413. const char *zTbl = pIter->zTbl; /* Table this step applies to */
  148414. const char *zWrite; /* Imposter table name */
  148415. char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
  148416. char *zWhere = rbuObjIterGetWhere(p, pIter);
  148417. char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
  148418. char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
  148419. zCollist = rbuObjIterGetCollist(p, pIter);
  148420. pIter->nCol = pIter->nTblCol;
  148421. /* Create the SELECT statement to read keys from data_xxx */
  148422. if( p->rc==SQLITE_OK ){
  148423. p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
  148424. sqlite3_mprintf(
  148425. "SELECT %s, rbu_control%s FROM 'data_%q'%s",
  148426. zCollist, (bRbuRowid ? ", rbu_rowid" : ""), zTbl, zLimit
  148427. )
  148428. );
  148429. }
  148430. /* Create the imposter table or tables (if required). */
  148431. rbuCreateImposterTable(p, pIter);
  148432. rbuCreateImposterTable2(p, pIter);
  148433. zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
  148434. /* Create the INSERT statement to write to the target PK b-tree */
  148435. if( p->rc==SQLITE_OK ){
  148436. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
  148437. sqlite3_mprintf(
  148438. "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
  148439. zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
  148440. )
  148441. );
  148442. }
  148443. /* Create the DELETE statement to write to the target PK b-tree */
  148444. if( p->rc==SQLITE_OK ){
  148445. p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
  148446. sqlite3_mprintf(
  148447. "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
  148448. )
  148449. );
  148450. }
  148451. if( pIter->abIndexed ){
  148452. const char *zRbuRowid = "";
  148453. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  148454. zRbuRowid = ", rbu_rowid";
  148455. }
  148456. /* Create the rbu_tmp_xxx table and the triggers to populate it. */
  148457. rbuMPrintfExec(p, p->dbRbu,
  148458. "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
  148459. "SELECT *%s FROM 'data_%q' WHERE 0;"
  148460. , p->zStateDb
  148461. , zTbl, (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
  148462. , zTbl
  148463. );
  148464. rbuMPrintfExec(p, p->dbMain,
  148465. "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
  148466. "BEGIN "
  148467. " SELECT rbu_tmp_insert(2, %s);"
  148468. "END;"
  148469. "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
  148470. "BEGIN "
  148471. " SELECT rbu_tmp_insert(2, %s);"
  148472. "END;"
  148473. "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
  148474. "BEGIN "
  148475. " SELECT rbu_tmp_insert(3, %s);"
  148476. "END;",
  148477. zWrite, zTbl, zOldlist,
  148478. zWrite, zTbl, zOldlist,
  148479. zWrite, zTbl, zNewlist
  148480. );
  148481. if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
  148482. rbuMPrintfExec(p, p->dbMain,
  148483. "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
  148484. "BEGIN "
  148485. " SELECT rbu_tmp_insert(0, %s);"
  148486. "END;",
  148487. zWrite, zTbl, zNewlist
  148488. );
  148489. }
  148490. rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
  148491. }
  148492. sqlite3_free(zWhere);
  148493. sqlite3_free(zOldlist);
  148494. sqlite3_free(zNewlist);
  148495. sqlite3_free(zBindings);
  148496. }
  148497. sqlite3_free(zCollist);
  148498. sqlite3_free(zLimit);
  148499. }
  148500. return p->rc;
  148501. }
  148502. /*
  148503. ** Set output variable *ppStmt to point to an UPDATE statement that may
  148504. ** be used to update the imposter table for the main table b-tree of the
  148505. ** table object that pIter currently points to, assuming that the
  148506. ** rbu_control column of the data_xyz table contains zMask.
  148507. **
  148508. ** If the zMask string does not specify any columns to update, then this
  148509. ** is not an error. Output variable *ppStmt is set to NULL in this case.
  148510. */
  148511. static int rbuGetUpdateStmt(
  148512. sqlite3rbu *p, /* RBU handle */
  148513. RbuObjIter *pIter, /* Object iterator */
  148514. const char *zMask, /* rbu_control value ('x.x.') */
  148515. sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
  148516. ){
  148517. RbuUpdateStmt **pp;
  148518. RbuUpdateStmt *pUp = 0;
  148519. int nUp = 0;
  148520. /* In case an error occurs */
  148521. *ppStmt = 0;
  148522. /* Search for an existing statement. If one is found, shift it to the front
  148523. ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
  148524. ** to the number of statements currently in the cache and pUp to the
  148525. ** last object in the list. */
  148526. for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
  148527. pUp = *pp;
  148528. if( strcmp(pUp->zMask, zMask)==0 ){
  148529. *pp = pUp->pNext;
  148530. pUp->pNext = pIter->pRbuUpdate;
  148531. pIter->pRbuUpdate = pUp;
  148532. *ppStmt = pUp->pUpdate;
  148533. return SQLITE_OK;
  148534. }
  148535. nUp++;
  148536. }
  148537. assert( pUp==0 || pUp->pNext==0 );
  148538. if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
  148539. for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
  148540. *pp = 0;
  148541. sqlite3_finalize(pUp->pUpdate);
  148542. pUp->pUpdate = 0;
  148543. }else{
  148544. pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
  148545. }
  148546. if( pUp ){
  148547. char *zWhere = rbuObjIterGetWhere(p, pIter);
  148548. char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
  148549. char *zUpdate = 0;
  148550. pUp->zMask = (char*)&pUp[1];
  148551. memcpy(pUp->zMask, zMask, pIter->nTblCol);
  148552. pUp->pNext = pIter->pRbuUpdate;
  148553. pIter->pRbuUpdate = pUp;
  148554. if( zSet ){
  148555. const char *zPrefix = "";
  148556. if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
  148557. zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
  148558. zPrefix, pIter->zTbl, zSet, zWhere
  148559. );
  148560. p->rc = prepareFreeAndCollectError(
  148561. p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
  148562. );
  148563. *ppStmt = pUp->pUpdate;
  148564. }
  148565. sqlite3_free(zWhere);
  148566. sqlite3_free(zSet);
  148567. }
  148568. return p->rc;
  148569. }
  148570. static sqlite3 *rbuOpenDbhandle(sqlite3rbu *p, const char *zName){
  148571. sqlite3 *db = 0;
  148572. if( p->rc==SQLITE_OK ){
  148573. const int flags = SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_URI;
  148574. p->rc = sqlite3_open_v2(zName, &db, flags, p->zVfsName);
  148575. if( p->rc ){
  148576. p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  148577. sqlite3_close(db);
  148578. db = 0;
  148579. }
  148580. }
  148581. return db;
  148582. }
  148583. /*
  148584. ** Open the database handle and attach the RBU database as "rbu". If an
  148585. ** error occurs, leave an error code and message in the RBU handle.
  148586. */
  148587. static void rbuOpenDatabase(sqlite3rbu *p){
  148588. assert( p->rc==SQLITE_OK );
  148589. assert( p->dbMain==0 && p->dbRbu==0 );
  148590. p->eStage = 0;
  148591. p->dbMain = rbuOpenDbhandle(p, p->zTarget);
  148592. p->dbRbu = rbuOpenDbhandle(p, p->zRbu);
  148593. /* If using separate RBU and state databases, attach the state database to
  148594. ** the RBU db handle now. */
  148595. if( p->zState ){
  148596. rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
  148597. memcpy(p->zStateDb, "stat", 4);
  148598. }else{
  148599. memcpy(p->zStateDb, "main", 4);
  148600. }
  148601. if( p->rc==SQLITE_OK ){
  148602. p->rc = sqlite3_create_function(p->dbMain,
  148603. "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
  148604. );
  148605. }
  148606. if( p->rc==SQLITE_OK ){
  148607. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  148608. }
  148609. rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
  148610. /* Mark the database file just opened as an RBU target database. If
  148611. ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
  148612. ** This is an error. */
  148613. if( p->rc==SQLITE_OK ){
  148614. p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
  148615. }
  148616. if( p->rc==SQLITE_NOTFOUND ){
  148617. p->rc = SQLITE_ERROR;
  148618. p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
  148619. }
  148620. }
  148621. /*
  148622. ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
  148623. ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
  148624. **
  148625. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  148626. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  148627. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  148628. ** three characters, then shorten the suffix on z[] to be the last three
  148629. ** characters of the original suffix.
  148630. **
  148631. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  148632. ** do the suffix shortening regardless of URI parameter.
  148633. **
  148634. ** Examples:
  148635. **
  148636. ** test.db-journal => test.nal
  148637. ** test.db-wal => test.wal
  148638. ** test.db-shm => test.shm
  148639. ** test.db-mj7f3319fa => test.9fa
  148640. */
  148641. static void rbuFileSuffix3(const char *zBase, char *z){
  148642. #ifdef SQLITE_ENABLE_8_3_NAMES
  148643. #if SQLITE_ENABLE_8_3_NAMES<2
  148644. if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
  148645. #endif
  148646. {
  148647. int i, sz;
  148648. sz = sqlite3Strlen30(z);
  148649. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  148650. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  148651. }
  148652. #endif
  148653. }
  148654. /*
  148655. ** Return the current wal-index header checksum for the target database
  148656. ** as a 64-bit integer.
  148657. **
  148658. ** The checksum is store in the first page of xShmMap memory as an 8-byte
  148659. ** blob starting at byte offset 40.
  148660. */
  148661. static i64 rbuShmChecksum(sqlite3rbu *p){
  148662. i64 iRet = 0;
  148663. if( p->rc==SQLITE_OK ){
  148664. sqlite3_file *pDb = p->pTargetFd->pReal;
  148665. u32 volatile *ptr;
  148666. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
  148667. if( p->rc==SQLITE_OK ){
  148668. iRet = ((i64)ptr[10] << 32) + ptr[11];
  148669. }
  148670. }
  148671. return iRet;
  148672. }
  148673. /*
  148674. ** This function is called as part of initializing or reinitializing an
  148675. ** incremental checkpoint.
  148676. **
  148677. ** It populates the sqlite3rbu.aFrame[] array with the set of
  148678. ** (wal frame -> db page) copy operations required to checkpoint the
  148679. ** current wal file, and obtains the set of shm locks required to safely
  148680. ** perform the copy operations directly on the file-system.
  148681. **
  148682. ** If argument pState is not NULL, then the incremental checkpoint is
  148683. ** being resumed. In this case, if the checksum of the wal-index-header
  148684. ** following recovery is not the same as the checksum saved in the RbuState
  148685. ** object, then the rbu handle is set to DONE state. This occurs if some
  148686. ** other client appends a transaction to the wal file in the middle of
  148687. ** an incremental checkpoint.
  148688. */
  148689. static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
  148690. /* If pState is NULL, then the wal file may not have been opened and
  148691. ** recovered. Running a read-statement here to ensure that doing so
  148692. ** does not interfere with the "capture" process below. */
  148693. if( pState==0 ){
  148694. p->eStage = 0;
  148695. if( p->rc==SQLITE_OK ){
  148696. p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
  148697. }
  148698. }
  148699. /* Assuming no error has occurred, run a "restart" checkpoint with the
  148700. ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
  148701. ** special behaviour in the rbu VFS:
  148702. **
  148703. ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
  148704. ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
  148705. ** proceed with running a passive checkpoint instead of failing).
  148706. **
  148707. ** * Attempts to read from the *-wal file or write to the database file
  148708. ** do not perform any IO. Instead, the frame/page combinations that
  148709. ** would be read/written are recorded in the sqlite3rbu.aFrame[]
  148710. ** array.
  148711. **
  148712. ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
  148713. ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
  148714. ** no-ops. These locks will not be released until the connection
  148715. ** is closed.
  148716. **
  148717. ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
  148718. ** error.
  148719. **
  148720. ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
  148721. ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
  148722. ** array populated with a set of (frame -> page) mappings. Because the
  148723. ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
  148724. ** data from the wal file into the database file according to the
  148725. ** contents of aFrame[].
  148726. */
  148727. if( p->rc==SQLITE_OK ){
  148728. int rc2;
  148729. p->eStage = RBU_STAGE_CAPTURE;
  148730. rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
  148731. if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
  148732. }
  148733. if( p->rc==SQLITE_OK ){
  148734. p->eStage = RBU_STAGE_CKPT;
  148735. p->nStep = (pState ? pState->nRow : 0);
  148736. p->aBuf = rbuMalloc(p, p->pgsz);
  148737. p->iWalCksum = rbuShmChecksum(p);
  148738. }
  148739. if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
  148740. p->rc = SQLITE_DONE;
  148741. p->eStage = RBU_STAGE_DONE;
  148742. }
  148743. }
  148744. /*
  148745. ** Called when iAmt bytes are read from offset iOff of the wal file while
  148746. ** the rbu object is in capture mode. Record the frame number of the frame
  148747. ** being read in the aFrame[] array.
  148748. */
  148749. static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
  148750. const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
  148751. u32 iFrame;
  148752. if( pRbu->mLock!=mReq ){
  148753. pRbu->rc = SQLITE_BUSY;
  148754. return SQLITE_INTERNAL;
  148755. }
  148756. pRbu->pgsz = iAmt;
  148757. if( pRbu->nFrame==pRbu->nFrameAlloc ){
  148758. int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
  148759. RbuFrame *aNew;
  148760. aNew = (RbuFrame*)sqlite3_realloc(pRbu->aFrame, nNew * sizeof(RbuFrame));
  148761. if( aNew==0 ) return SQLITE_NOMEM;
  148762. pRbu->aFrame = aNew;
  148763. pRbu->nFrameAlloc = nNew;
  148764. }
  148765. iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
  148766. if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
  148767. pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
  148768. pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
  148769. pRbu->nFrame++;
  148770. return SQLITE_OK;
  148771. }
  148772. /*
  148773. ** Called when a page of data is written to offset iOff of the database
  148774. ** file while the rbu handle is in capture mode. Record the page number
  148775. ** of the page being written in the aFrame[] array.
  148776. */
  148777. static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
  148778. pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
  148779. return SQLITE_OK;
  148780. }
  148781. /*
  148782. ** This is called as part of an incremental checkpoint operation. Copy
  148783. ** a single frame of data from the wal file into the database file, as
  148784. ** indicated by the RbuFrame object.
  148785. */
  148786. static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
  148787. sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
  148788. sqlite3_file *pDb = p->pTargetFd->pReal;
  148789. i64 iOff;
  148790. assert( p->rc==SQLITE_OK );
  148791. iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
  148792. p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
  148793. if( p->rc ) return;
  148794. iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
  148795. p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
  148796. }
  148797. /*
  148798. ** Take an EXCLUSIVE lock on the database file.
  148799. */
  148800. static void rbuLockDatabase(sqlite3rbu *p){
  148801. sqlite3_file *pReal = p->pTargetFd->pReal;
  148802. assert( p->rc==SQLITE_OK );
  148803. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
  148804. if( p->rc==SQLITE_OK ){
  148805. p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
  148806. }
  148807. }
  148808. /*
  148809. ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
  148810. ** on the database file. This proc moves the *-oal file to the *-wal path,
  148811. ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
  148812. ** If an error occurs, leave an error code and error message in the rbu
  148813. ** handle.
  148814. */
  148815. static void rbuMoveOalFile(sqlite3rbu *p){
  148816. const char *zBase = sqlite3_db_filename(p->dbMain, "main");
  148817. char *zWal = sqlite3_mprintf("%s-wal", zBase);
  148818. char *zOal = sqlite3_mprintf("%s-oal", zBase);
  148819. assert( p->eStage==RBU_STAGE_MOVE );
  148820. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  148821. if( zWal==0 || zOal==0 ){
  148822. p->rc = SQLITE_NOMEM;
  148823. }else{
  148824. /* Move the *-oal file to *-wal. At this point connection p->db is
  148825. ** holding a SHARED lock on the target database file (because it is
  148826. ** in WAL mode). So no other connection may be writing the db.
  148827. **
  148828. ** In order to ensure that there are no database readers, an EXCLUSIVE
  148829. ** lock is obtained here before the *-oal is moved to *-wal.
  148830. */
  148831. rbuLockDatabase(p);
  148832. if( p->rc==SQLITE_OK ){
  148833. rbuFileSuffix3(zBase, zWal);
  148834. rbuFileSuffix3(zBase, zOal);
  148835. /* Re-open the databases. */
  148836. rbuObjIterFinalize(&p->objiter);
  148837. sqlite3_close(p->dbMain);
  148838. sqlite3_close(p->dbRbu);
  148839. p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
  148840. if( p->rc==SQLITE_OK ){
  148841. p->dbMain = 0;
  148842. p->dbRbu = 0;
  148843. rbuOpenDatabase(p);
  148844. rbuSetupCheckpoint(p, 0);
  148845. }
  148846. }
  148847. }
  148848. sqlite3_free(zWal);
  148849. sqlite3_free(zOal);
  148850. }
  148851. /*
  148852. ** The SELECT statement iterating through the keys for the current object
  148853. ** (p->objiter.pSelect) currently points to a valid row. This function
  148854. ** determines the type of operation requested by this row and returns
  148855. ** one of the following values to indicate the result:
  148856. **
  148857. ** * RBU_INSERT
  148858. ** * RBU_DELETE
  148859. ** * RBU_IDX_DELETE
  148860. ** * RBU_UPDATE
  148861. **
  148862. ** If RBU_UPDATE is returned, then output variable *pzMask is set to
  148863. ** point to the text value indicating the columns to update.
  148864. **
  148865. ** If the rbu_control field contains an invalid value, an error code and
  148866. ** message are left in the RBU handle and zero returned.
  148867. */
  148868. static int rbuStepType(sqlite3rbu *p, const char **pzMask){
  148869. int iCol = p->objiter.nCol; /* Index of rbu_control column */
  148870. int res = 0; /* Return value */
  148871. switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
  148872. case SQLITE_INTEGER: {
  148873. int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
  148874. if( iVal==0 ){
  148875. res = RBU_INSERT;
  148876. }else if( iVal==1 ){
  148877. res = RBU_DELETE;
  148878. }else if( iVal==2 ){
  148879. res = RBU_IDX_DELETE;
  148880. }else if( iVal==3 ){
  148881. res = RBU_IDX_INSERT;
  148882. }
  148883. break;
  148884. }
  148885. case SQLITE_TEXT: {
  148886. const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
  148887. if( z==0 ){
  148888. p->rc = SQLITE_NOMEM;
  148889. }else{
  148890. *pzMask = (const char*)z;
  148891. }
  148892. res = RBU_UPDATE;
  148893. break;
  148894. }
  148895. default:
  148896. break;
  148897. }
  148898. if( res==0 ){
  148899. rbuBadControlError(p);
  148900. }
  148901. return res;
  148902. }
  148903. #ifdef SQLITE_DEBUG
  148904. /*
  148905. ** Assert that column iCol of statement pStmt is named zName.
  148906. */
  148907. static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
  148908. const char *zCol = sqlite3_column_name(pStmt, iCol);
  148909. assert( 0==sqlite3_stricmp(zName, zCol) );
  148910. }
  148911. #else
  148912. # define assertColumnName(x,y,z)
  148913. #endif
  148914. /*
  148915. ** This function does the work for an sqlite3rbu_step() call.
  148916. **
  148917. ** The object-iterator (p->objiter) currently points to a valid object,
  148918. ** and the input cursor (p->objiter.pSelect) currently points to a valid
  148919. ** input row. Perform whatever processing is required and return.
  148920. **
  148921. ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
  148922. ** and message is left in the RBU handle and a copy of the error code
  148923. ** returned.
  148924. */
  148925. static int rbuStep(sqlite3rbu *p){
  148926. RbuObjIter *pIter = &p->objiter;
  148927. const char *zMask = 0;
  148928. int i;
  148929. int eType = rbuStepType(p, &zMask);
  148930. if( eType ){
  148931. assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
  148932. if( pIter->zIdx==0 && eType==RBU_IDX_DELETE ){
  148933. rbuBadControlError(p);
  148934. }
  148935. else if(
  148936. eType==RBU_INSERT
  148937. || eType==RBU_DELETE
  148938. || eType==RBU_IDX_DELETE
  148939. || eType==RBU_IDX_INSERT
  148940. ){
  148941. sqlite3_value *pVal;
  148942. sqlite3_stmt *pWriter;
  148943. assert( eType!=RBU_UPDATE );
  148944. assert( eType!=RBU_DELETE || pIter->zIdx==0 );
  148945. if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
  148946. pWriter = pIter->pDelete;
  148947. }else{
  148948. pWriter = pIter->pInsert;
  148949. }
  148950. for(i=0; i<pIter->nCol; i++){
  148951. /* If this is an INSERT into a table b-tree and the table has an
  148952. ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
  148953. ** to write a NULL into the IPK column. That is not permitted. */
  148954. if( eType==RBU_INSERT
  148955. && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
  148956. && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
  148957. ){
  148958. p->rc = SQLITE_MISMATCH;
  148959. p->zErrmsg = sqlite3_mprintf("datatype mismatch");
  148960. goto step_out;
  148961. }
  148962. if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
  148963. continue;
  148964. }
  148965. pVal = sqlite3_column_value(pIter->pSelect, i);
  148966. p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
  148967. if( p->rc ) goto step_out;
  148968. }
  148969. if( pIter->zIdx==0
  148970. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  148971. ){
  148972. /* For a virtual table, or a table with no primary key, the
  148973. ** SELECT statement is:
  148974. **
  148975. ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
  148976. **
  148977. ** Hence column_value(pIter->nCol+1).
  148978. */
  148979. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  148980. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  148981. p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
  148982. }
  148983. if( p->rc==SQLITE_OK ){
  148984. sqlite3_step(pWriter);
  148985. p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
  148986. }
  148987. }else{
  148988. sqlite3_value *pVal;
  148989. sqlite3_stmt *pUpdate = 0;
  148990. assert( eType==RBU_UPDATE );
  148991. rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
  148992. if( pUpdate ){
  148993. for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
  148994. char c = zMask[pIter->aiSrcOrder[i]];
  148995. pVal = sqlite3_column_value(pIter->pSelect, i);
  148996. if( pIter->abTblPk[i] || c=='x' || c=='d' ){
  148997. p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
  148998. }
  148999. }
  149000. if( p->rc==SQLITE_OK
  149001. && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
  149002. ){
  149003. /* Bind the rbu_rowid value to column _rowid_ */
  149004. assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
  149005. pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
  149006. p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
  149007. }
  149008. if( p->rc==SQLITE_OK ){
  149009. sqlite3_step(pUpdate);
  149010. p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
  149011. }
  149012. }
  149013. }
  149014. }
  149015. step_out:
  149016. return p->rc;
  149017. }
  149018. /*
  149019. ** Increment the schema cookie of the main database opened by p->dbMain.
  149020. */
  149021. static void rbuIncrSchemaCookie(sqlite3rbu *p){
  149022. if( p->rc==SQLITE_OK ){
  149023. int iCookie = 1000000;
  149024. sqlite3_stmt *pStmt;
  149025. p->rc = prepareAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
  149026. "PRAGMA schema_version"
  149027. );
  149028. if( p->rc==SQLITE_OK ){
  149029. /* Coverage: it may be that this sqlite3_step() cannot fail. There
  149030. ** is already a transaction open, so the prepared statement cannot
  149031. ** throw an SQLITE_SCHEMA exception. The only database page the
  149032. ** statement reads is page 1, which is guaranteed to be in the cache.
  149033. ** And no memory allocations are required. */
  149034. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  149035. iCookie = sqlite3_column_int(pStmt, 0);
  149036. }
  149037. rbuFinalize(p, pStmt);
  149038. }
  149039. if( p->rc==SQLITE_OK ){
  149040. rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
  149041. }
  149042. }
  149043. }
  149044. /*
  149045. ** Update the contents of the rbu_state table within the rbu database. The
  149046. ** value stored in the RBU_STATE_STAGE column is eStage. All other values
  149047. ** are determined by inspecting the rbu handle passed as the first argument.
  149048. */
  149049. static void rbuSaveState(sqlite3rbu *p, int eStage){
  149050. if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
  149051. sqlite3_stmt *pInsert = 0;
  149052. int rc;
  149053. assert( p->zErrmsg==0 );
  149054. rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
  149055. sqlite3_mprintf(
  149056. "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
  149057. "(%d, %d), "
  149058. "(%d, %Q), "
  149059. "(%d, %Q), "
  149060. "(%d, %d), "
  149061. "(%d, %d), "
  149062. "(%d, %lld), "
  149063. "(%d, %lld), "
  149064. "(%d, %lld) ",
  149065. p->zStateDb,
  149066. RBU_STATE_STAGE, eStage,
  149067. RBU_STATE_TBL, p->objiter.zTbl,
  149068. RBU_STATE_IDX, p->objiter.zIdx,
  149069. RBU_STATE_ROW, p->nStep,
  149070. RBU_STATE_PROGRESS, p->nProgress,
  149071. RBU_STATE_CKPT, p->iWalCksum,
  149072. RBU_STATE_COOKIE, (i64)p->pTargetFd->iCookie,
  149073. RBU_STATE_OALSZ, p->iOalSz
  149074. )
  149075. );
  149076. assert( pInsert==0 || rc==SQLITE_OK );
  149077. if( rc==SQLITE_OK ){
  149078. sqlite3_step(pInsert);
  149079. rc = sqlite3_finalize(pInsert);
  149080. }
  149081. if( rc!=SQLITE_OK ) p->rc = rc;
  149082. }
  149083. }
  149084. /*
  149085. ** Step the RBU object.
  149086. */
  149087. SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
  149088. if( p ){
  149089. switch( p->eStage ){
  149090. case RBU_STAGE_OAL: {
  149091. RbuObjIter *pIter = &p->objiter;
  149092. while( p->rc==SQLITE_OK && pIter->zTbl ){
  149093. if( pIter->bCleanup ){
  149094. /* Clean up the rbu_tmp_xxx table for the previous table. It
  149095. ** cannot be dropped as there are currently active SQL statements.
  149096. ** But the contents can be deleted. */
  149097. if( pIter->abIndexed ){
  149098. rbuMPrintfExec(p, p->dbRbu,
  149099. "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zTbl
  149100. );
  149101. }
  149102. }else{
  149103. rbuObjIterPrepareAll(p, pIter, 0);
  149104. /* Advance to the next row to process. */
  149105. if( p->rc==SQLITE_OK ){
  149106. int rc = sqlite3_step(pIter->pSelect);
  149107. if( rc==SQLITE_ROW ){
  149108. p->nProgress++;
  149109. p->nStep++;
  149110. return rbuStep(p);
  149111. }
  149112. p->rc = sqlite3_reset(pIter->pSelect);
  149113. p->nStep = 0;
  149114. }
  149115. }
  149116. rbuObjIterNext(p, pIter);
  149117. }
  149118. if( p->rc==SQLITE_OK ){
  149119. assert( pIter->zTbl==0 );
  149120. rbuSaveState(p, RBU_STAGE_MOVE);
  149121. rbuIncrSchemaCookie(p);
  149122. if( p->rc==SQLITE_OK ){
  149123. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  149124. }
  149125. if( p->rc==SQLITE_OK ){
  149126. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  149127. }
  149128. p->eStage = RBU_STAGE_MOVE;
  149129. }
  149130. break;
  149131. }
  149132. case RBU_STAGE_MOVE: {
  149133. if( p->rc==SQLITE_OK ){
  149134. rbuMoveOalFile(p);
  149135. p->nProgress++;
  149136. }
  149137. break;
  149138. }
  149139. case RBU_STAGE_CKPT: {
  149140. if( p->rc==SQLITE_OK ){
  149141. if( p->nStep>=p->nFrame ){
  149142. sqlite3_file *pDb = p->pTargetFd->pReal;
  149143. /* Sync the db file */
  149144. p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
  149145. /* Update nBackfill */
  149146. if( p->rc==SQLITE_OK ){
  149147. void volatile *ptr;
  149148. p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
  149149. if( p->rc==SQLITE_OK ){
  149150. ((u32 volatile*)ptr)[24] = p->iMaxFrame;
  149151. }
  149152. }
  149153. if( p->rc==SQLITE_OK ){
  149154. p->eStage = RBU_STAGE_DONE;
  149155. p->rc = SQLITE_DONE;
  149156. }
  149157. }else{
  149158. RbuFrame *pFrame = &p->aFrame[p->nStep];
  149159. rbuCheckpointFrame(p, pFrame);
  149160. p->nStep++;
  149161. }
  149162. p->nProgress++;
  149163. }
  149164. break;
  149165. }
  149166. default:
  149167. break;
  149168. }
  149169. return p->rc;
  149170. }else{
  149171. return SQLITE_NOMEM;
  149172. }
  149173. }
  149174. /*
  149175. ** Free an RbuState object allocated by rbuLoadState().
  149176. */
  149177. static void rbuFreeState(RbuState *p){
  149178. if( p ){
  149179. sqlite3_free(p->zTbl);
  149180. sqlite3_free(p->zIdx);
  149181. sqlite3_free(p);
  149182. }
  149183. }
  149184. /*
  149185. ** Allocate an RbuState object and load the contents of the rbu_state
  149186. ** table into it. Return a pointer to the new object. It is the
  149187. ** responsibility of the caller to eventually free the object using
  149188. ** sqlite3_free().
  149189. **
  149190. ** If an error occurs, leave an error code and message in the rbu handle
  149191. ** and return NULL.
  149192. */
  149193. static RbuState *rbuLoadState(sqlite3rbu *p){
  149194. RbuState *pRet = 0;
  149195. sqlite3_stmt *pStmt = 0;
  149196. int rc;
  149197. int rc2;
  149198. pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
  149199. if( pRet==0 ) return 0;
  149200. rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
  149201. sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
  149202. );
  149203. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  149204. switch( sqlite3_column_int(pStmt, 0) ){
  149205. case RBU_STATE_STAGE:
  149206. pRet->eStage = sqlite3_column_int(pStmt, 1);
  149207. if( pRet->eStage!=RBU_STAGE_OAL
  149208. && pRet->eStage!=RBU_STAGE_MOVE
  149209. && pRet->eStage!=RBU_STAGE_CKPT
  149210. ){
  149211. p->rc = SQLITE_CORRUPT;
  149212. }
  149213. break;
  149214. case RBU_STATE_TBL:
  149215. pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  149216. break;
  149217. case RBU_STATE_IDX:
  149218. pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
  149219. break;
  149220. case RBU_STATE_ROW:
  149221. pRet->nRow = sqlite3_column_int(pStmt, 1);
  149222. break;
  149223. case RBU_STATE_PROGRESS:
  149224. pRet->nProgress = sqlite3_column_int64(pStmt, 1);
  149225. break;
  149226. case RBU_STATE_CKPT:
  149227. pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
  149228. break;
  149229. case RBU_STATE_COOKIE:
  149230. pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
  149231. break;
  149232. case RBU_STATE_OALSZ:
  149233. pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
  149234. break;
  149235. default:
  149236. rc = SQLITE_CORRUPT;
  149237. break;
  149238. }
  149239. }
  149240. rc2 = sqlite3_finalize(pStmt);
  149241. if( rc==SQLITE_OK ) rc = rc2;
  149242. p->rc = rc;
  149243. return pRet;
  149244. }
  149245. /*
  149246. ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
  149247. ** otherwise. Either or both argument may be NULL. Two NULL values are
  149248. ** considered equal, and NULL is considered distinct from all other values.
  149249. */
  149250. static int rbuStrCompare(const char *z1, const char *z2){
  149251. if( z1==0 && z2==0 ) return 0;
  149252. if( z1==0 || z2==0 ) return 1;
  149253. return (sqlite3_stricmp(z1, z2)!=0);
  149254. }
  149255. /*
  149256. ** This function is called as part of sqlite3rbu_open() when initializing
  149257. ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
  149258. ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
  149259. ** things so that the next call to sqlite3rbu_step() continues on from
  149260. ** where the previous rbu handle left off.
  149261. **
  149262. ** If an error occurs, an error code and error message are left in the
  149263. ** rbu handle passed as the first argument.
  149264. */
  149265. static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
  149266. assert( p->rc==SQLITE_OK );
  149267. if( pState->zTbl ){
  149268. RbuObjIter *pIter = &p->objiter;
  149269. int rc = SQLITE_OK;
  149270. while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
  149271. || rbuStrCompare(pIter->zIdx, pState->zIdx)
  149272. || rbuStrCompare(pIter->zTbl, pState->zTbl)
  149273. )){
  149274. rc = rbuObjIterNext(p, pIter);
  149275. }
  149276. if( rc==SQLITE_OK && !pIter->zTbl ){
  149277. rc = SQLITE_ERROR;
  149278. p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
  149279. }
  149280. if( rc==SQLITE_OK ){
  149281. p->nStep = pState->nRow;
  149282. rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
  149283. }
  149284. p->rc = rc;
  149285. }
  149286. }
  149287. /*
  149288. ** If there is a "*-oal" file in the file-system corresponding to the
  149289. ** target database in the file-system, delete it. If an error occurs,
  149290. ** leave an error code and error message in the rbu handle.
  149291. */
  149292. static void rbuDeleteOalFile(sqlite3rbu *p){
  149293. char *zOal = sqlite3_mprintf("%s-oal", p->zTarget);
  149294. assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
  149295. unlink(zOal);
  149296. sqlite3_free(zOal);
  149297. }
  149298. /*
  149299. ** Allocate a private rbu VFS for the rbu handle passed as the only
  149300. ** argument. This VFS will be used unless the call to sqlite3rbu_open()
  149301. ** specified a URI with a vfs=? option in place of a target database
  149302. ** file name.
  149303. */
  149304. static void rbuCreateVfs(sqlite3rbu *p){
  149305. int rnd;
  149306. char zRnd[64];
  149307. assert( p->rc==SQLITE_OK );
  149308. sqlite3_randomness(sizeof(int), (void*)&rnd);
  149309. sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
  149310. p->rc = sqlite3rbu_create_vfs(zRnd, 0);
  149311. if( p->rc==SQLITE_OK ){
  149312. sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
  149313. assert( pVfs );
  149314. p->zVfsName = pVfs->zName;
  149315. }
  149316. }
  149317. /*
  149318. ** Destroy the private VFS created for the rbu handle passed as the only
  149319. ** argument by an earlier call to rbuCreateVfs().
  149320. */
  149321. static void rbuDeleteVfs(sqlite3rbu *p){
  149322. if( p->zVfsName ){
  149323. sqlite3rbu_destroy_vfs(p->zVfsName);
  149324. p->zVfsName = 0;
  149325. }
  149326. }
  149327. /*
  149328. ** Open and return a new RBU handle.
  149329. */
  149330. SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
  149331. const char *zTarget,
  149332. const char *zRbu,
  149333. const char *zState
  149334. ){
  149335. sqlite3rbu *p;
  149336. int nTarget = strlen(zTarget);
  149337. int nRbu = strlen(zRbu);
  149338. int nState = zState ? strlen(zState) : 0;
  149339. p = (sqlite3rbu*)sqlite3_malloc(sizeof(sqlite3rbu)+nTarget+1+nRbu+1+nState+1);
  149340. if( p ){
  149341. RbuState *pState = 0;
  149342. /* Create the custom VFS. */
  149343. memset(p, 0, sizeof(sqlite3rbu));
  149344. rbuCreateVfs(p);
  149345. /* Open the target database */
  149346. if( p->rc==SQLITE_OK ){
  149347. p->zTarget = (char*)&p[1];
  149348. memcpy(p->zTarget, zTarget, nTarget+1);
  149349. p->zRbu = &p->zTarget[nTarget+1];
  149350. memcpy(p->zRbu, zRbu, nRbu+1);
  149351. if( zState ){
  149352. p->zState = &p->zRbu[nRbu+1];
  149353. memcpy(p->zState, zState, nState+1);
  149354. }
  149355. rbuOpenDatabase(p);
  149356. }
  149357. /* If it has not already been created, create the rbu_state table */
  149358. rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
  149359. if( p->rc==SQLITE_OK ){
  149360. pState = rbuLoadState(p);
  149361. assert( pState || p->rc!=SQLITE_OK );
  149362. if( p->rc==SQLITE_OK ){
  149363. if( pState->eStage==0 ){
  149364. rbuDeleteOalFile(p);
  149365. p->eStage = RBU_STAGE_OAL;
  149366. }else{
  149367. p->eStage = pState->eStage;
  149368. }
  149369. p->nProgress = pState->nProgress;
  149370. p->iOalSz = pState->iOalSz;
  149371. }
  149372. }
  149373. assert( p->rc!=SQLITE_OK || p->eStage!=0 );
  149374. if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
  149375. if( p->eStage==RBU_STAGE_OAL ){
  149376. p->rc = SQLITE_ERROR;
  149377. p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
  149378. }else if( p->eStage==RBU_STAGE_MOVE ){
  149379. p->eStage = RBU_STAGE_CKPT;
  149380. p->nStep = 0;
  149381. }
  149382. }
  149383. if( p->rc==SQLITE_OK
  149384. && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
  149385. && pState->eStage!=0 && p->pTargetFd->iCookie!=pState->iCookie
  149386. ){
  149387. /* At this point (pTargetFd->iCookie) contains the value of the
  149388. ** change-counter cookie (the thing that gets incremented when a
  149389. ** transaction is committed in rollback mode) currently stored on
  149390. ** page 1 of the database file. */
  149391. p->rc = SQLITE_BUSY;
  149392. p->zErrmsg = sqlite3_mprintf("database modified during rbu update");
  149393. }
  149394. if( p->rc==SQLITE_OK ){
  149395. if( p->eStage==RBU_STAGE_OAL ){
  149396. /* Open transactions both databases. The *-oal file is opened or
  149397. ** created at this point. */
  149398. p->rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  149399. if( p->rc==SQLITE_OK ){
  149400. p->rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
  149401. }
  149402. /* Point the object iterator at the first object */
  149403. if( p->rc==SQLITE_OK ){
  149404. p->rc = rbuObjIterFirst(p, &p->objiter);
  149405. }
  149406. /* If the RBU database contains no data_xxx tables, declare the RBU
  149407. ** update finished. */
  149408. if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
  149409. p->rc = SQLITE_DONE;
  149410. }
  149411. if( p->rc==SQLITE_OK ){
  149412. rbuSetupOal(p, pState);
  149413. }
  149414. }else if( p->eStage==RBU_STAGE_MOVE ){
  149415. /* no-op */
  149416. }else if( p->eStage==RBU_STAGE_CKPT ){
  149417. rbuSetupCheckpoint(p, pState);
  149418. }else if( p->eStage==RBU_STAGE_DONE ){
  149419. p->rc = SQLITE_DONE;
  149420. }else{
  149421. p->rc = SQLITE_CORRUPT;
  149422. }
  149423. }
  149424. rbuFreeState(pState);
  149425. }
  149426. return p;
  149427. }
  149428. /*
  149429. ** Return the database handle used by pRbu.
  149430. */
  149431. SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
  149432. sqlite3 *db = 0;
  149433. if( pRbu ){
  149434. db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
  149435. }
  149436. return db;
  149437. }
  149438. /*
  149439. ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
  149440. ** then edit any error message string so as to remove all occurrences of
  149441. ** the pattern "rbu_imp_[0-9]*".
  149442. */
  149443. static void rbuEditErrmsg(sqlite3rbu *p){
  149444. if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
  149445. int i;
  149446. int nErrmsg = strlen(p->zErrmsg);
  149447. for(i=0; i<(nErrmsg-8); i++){
  149448. if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
  149449. int nDel = 8;
  149450. while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
  149451. memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
  149452. nErrmsg -= nDel;
  149453. }
  149454. }
  149455. }
  149456. }
  149457. /*
  149458. ** Close the RBU handle.
  149459. */
  149460. SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
  149461. int rc;
  149462. if( p ){
  149463. /* Commit the transaction to the *-oal file. */
  149464. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  149465. p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
  149466. }
  149467. rbuSaveState(p, p->eStage);
  149468. if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
  149469. p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
  149470. }
  149471. /* Close any open statement handles. */
  149472. rbuObjIterFinalize(&p->objiter);
  149473. /* Close the open database handle and VFS object. */
  149474. sqlite3_close(p->dbMain);
  149475. sqlite3_close(p->dbRbu);
  149476. rbuDeleteVfs(p);
  149477. sqlite3_free(p->aBuf);
  149478. sqlite3_free(p->aFrame);
  149479. rbuEditErrmsg(p);
  149480. rc = p->rc;
  149481. *pzErrmsg = p->zErrmsg;
  149482. sqlite3_free(p);
  149483. }else{
  149484. rc = SQLITE_NOMEM;
  149485. *pzErrmsg = 0;
  149486. }
  149487. return rc;
  149488. }
  149489. /*
  149490. ** Return the total number of key-value operations (inserts, deletes or
  149491. ** updates) that have been performed on the target database since the
  149492. ** current RBU update was started.
  149493. */
  149494. SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
  149495. return pRbu->nProgress;
  149496. }
  149497. /**************************************************************************
  149498. ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
  149499. ** of a standard VFS in the following ways:
  149500. **
  149501. ** 1. Whenever the first page of a main database file is read or
  149502. ** written, the value of the change-counter cookie is stored in
  149503. ** rbu_file.iCookie. Similarly, the value of the "write-version"
  149504. ** database header field is stored in rbu_file.iWriteVer. This ensures
  149505. ** that the values are always trustworthy within an open transaction.
  149506. **
  149507. ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
  149508. ** member variable of the associated database file descriptor is set
  149509. ** to point to the new file. A mutex protected linked list of all main
  149510. ** db fds opened using a particular RBU VFS is maintained at
  149511. ** rbu_vfs.pMain to facilitate this.
  149512. **
  149513. ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
  149514. ** object can be marked as the target database of an RBU update. This
  149515. ** turns on the following extra special behaviour:
  149516. **
  149517. ** 3a. If xAccess() is called to check if there exists a *-wal file
  149518. ** associated with an RBU target database currently in RBU_STAGE_OAL
  149519. ** stage (preparing the *-oal file), the following special handling
  149520. ** applies:
  149521. **
  149522. ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
  149523. ** target database may not be in wal mode already.
  149524. **
  149525. ** * if the *-wal file does not exist, set the output parameter to
  149526. ** non-zero (to tell SQLite that it does exist) anyway.
  149527. **
  149528. ** Then, when xOpen() is called to open the *-wal file associated with
  149529. ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
  149530. ** file, the rbu vfs opens the corresponding *-oal file instead.
  149531. **
  149532. ** 3b. The *-shm pages returned by xShmMap() for a target db file in
  149533. ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
  149534. ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
  149535. ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
  149536. ** because assert() statements in some VFS implementations fail if
  149537. ** xShmLock() is called before xShmMap().
  149538. **
  149539. ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
  149540. ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
  149541. ** fails with an SQLITE_BUSY error. This is to stop RBU connections
  149542. ** from automatically checkpointing a *-wal (or *-oal) file from within
  149543. ** sqlite3_close().
  149544. **
  149545. ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
  149546. ** all xWrite() calls on the target database file perform no IO.
  149547. ** Instead the frame and page numbers that would be read and written
  149548. ** are recorded. Additionally, successful attempts to obtain exclusive
  149549. ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
  149550. ** database file are recorded. xShmLock() calls to unlock the same
  149551. ** locks are no-ops (so that once obtained, these locks are never
  149552. ** relinquished). Finally, calls to xSync() on the target database
  149553. ** file fail with SQLITE_INTERNAL errors.
  149554. */
  149555. static void rbuUnlockShm(rbu_file *p){
  149556. if( p->pRbu ){
  149557. int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
  149558. int i;
  149559. for(i=0; i<SQLITE_SHM_NLOCK;i++){
  149560. if( (1<<i) & p->pRbu->mLock ){
  149561. xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
  149562. }
  149563. }
  149564. p->pRbu->mLock = 0;
  149565. }
  149566. }
  149567. /*
  149568. ** Close an rbu file.
  149569. */
  149570. static int rbuVfsClose(sqlite3_file *pFile){
  149571. rbu_file *p = (rbu_file*)pFile;
  149572. int rc;
  149573. int i;
  149574. /* Free the contents of the apShm[] array. And the array itself. */
  149575. for(i=0; i<p->nShm; i++){
  149576. sqlite3_free(p->apShm[i]);
  149577. }
  149578. sqlite3_free(p->apShm);
  149579. p->apShm = 0;
  149580. sqlite3_free(p->zDel);
  149581. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  149582. rbu_file **pp;
  149583. sqlite3_mutex_enter(p->pRbuVfs->mutex);
  149584. for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
  149585. *pp = p->pMainNext;
  149586. sqlite3_mutex_leave(p->pRbuVfs->mutex);
  149587. rbuUnlockShm(p);
  149588. p->pReal->pMethods->xShmUnmap(p->pReal, 0);
  149589. }
  149590. /* Close the underlying file handle */
  149591. rc = p->pReal->pMethods->xClose(p->pReal);
  149592. return rc;
  149593. }
  149594. /*
  149595. ** Read and return an unsigned 32-bit big-endian integer from the buffer
  149596. ** passed as the only argument.
  149597. */
  149598. static u32 rbuGetU32(u8 *aBuf){
  149599. return ((u32)aBuf[0] << 24)
  149600. + ((u32)aBuf[1] << 16)
  149601. + ((u32)aBuf[2] << 8)
  149602. + ((u32)aBuf[3]);
  149603. }
  149604. /*
  149605. ** Read data from an rbuVfs-file.
  149606. */
  149607. static int rbuVfsRead(
  149608. sqlite3_file *pFile,
  149609. void *zBuf,
  149610. int iAmt,
  149611. sqlite_int64 iOfst
  149612. ){
  149613. rbu_file *p = (rbu_file*)pFile;
  149614. sqlite3rbu *pRbu = p->pRbu;
  149615. int rc;
  149616. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  149617. assert( p->openFlags & SQLITE_OPEN_WAL );
  149618. rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
  149619. }else{
  149620. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  149621. && (p->openFlags & SQLITE_OPEN_WAL)
  149622. && iOfst>=pRbu->iOalSz
  149623. ){
  149624. rc = SQLITE_OK;
  149625. memset(zBuf, 0, iAmt);
  149626. }else{
  149627. rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
  149628. }
  149629. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  149630. /* These look like magic numbers. But they are stable, as they are part
  149631. ** of the definition of the SQLite file format, which may not change. */
  149632. u8 *pBuf = (u8*)zBuf;
  149633. p->iCookie = rbuGetU32(&pBuf[24]);
  149634. p->iWriteVer = pBuf[19];
  149635. }
  149636. }
  149637. return rc;
  149638. }
  149639. /*
  149640. ** Write data to an rbuVfs-file.
  149641. */
  149642. static int rbuVfsWrite(
  149643. sqlite3_file *pFile,
  149644. const void *zBuf,
  149645. int iAmt,
  149646. sqlite_int64 iOfst
  149647. ){
  149648. rbu_file *p = (rbu_file*)pFile;
  149649. sqlite3rbu *pRbu = p->pRbu;
  149650. int rc;
  149651. if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
  149652. assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
  149653. rc = rbuCaptureDbWrite(p->pRbu, iOfst);
  149654. }else{
  149655. if( pRbu && pRbu->eStage==RBU_STAGE_OAL
  149656. && (p->openFlags & SQLITE_OPEN_WAL)
  149657. && iOfst>=pRbu->iOalSz
  149658. ){
  149659. pRbu->iOalSz = iAmt + iOfst;
  149660. }
  149661. rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
  149662. if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
  149663. /* These look like magic numbers. But they are stable, as they are part
  149664. ** of the definition of the SQLite file format, which may not change. */
  149665. u8 *pBuf = (u8*)zBuf;
  149666. p->iCookie = rbuGetU32(&pBuf[24]);
  149667. p->iWriteVer = pBuf[19];
  149668. }
  149669. }
  149670. return rc;
  149671. }
  149672. /*
  149673. ** Truncate an rbuVfs-file.
  149674. */
  149675. static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
  149676. rbu_file *p = (rbu_file*)pFile;
  149677. return p->pReal->pMethods->xTruncate(p->pReal, size);
  149678. }
  149679. /*
  149680. ** Sync an rbuVfs-file.
  149681. */
  149682. static int rbuVfsSync(sqlite3_file *pFile, int flags){
  149683. rbu_file *p = (rbu_file *)pFile;
  149684. if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
  149685. if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
  149686. return SQLITE_INTERNAL;
  149687. }
  149688. return SQLITE_OK;
  149689. }
  149690. return p->pReal->pMethods->xSync(p->pReal, flags);
  149691. }
  149692. /*
  149693. ** Return the current file-size of an rbuVfs-file.
  149694. */
  149695. static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
  149696. rbu_file *p = (rbu_file *)pFile;
  149697. return p->pReal->pMethods->xFileSize(p->pReal, pSize);
  149698. }
  149699. /*
  149700. ** Lock an rbuVfs-file.
  149701. */
  149702. static int rbuVfsLock(sqlite3_file *pFile, int eLock){
  149703. rbu_file *p = (rbu_file*)pFile;
  149704. sqlite3rbu *pRbu = p->pRbu;
  149705. int rc = SQLITE_OK;
  149706. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  149707. if( pRbu && eLock==SQLITE_LOCK_EXCLUSIVE && pRbu->eStage!=RBU_STAGE_DONE ){
  149708. /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
  149709. ** prevents it from checkpointing the database from sqlite3_close(). */
  149710. rc = SQLITE_BUSY;
  149711. }else{
  149712. rc = p->pReal->pMethods->xLock(p->pReal, eLock);
  149713. }
  149714. return rc;
  149715. }
  149716. /*
  149717. ** Unlock an rbuVfs-file.
  149718. */
  149719. static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
  149720. rbu_file *p = (rbu_file *)pFile;
  149721. return p->pReal->pMethods->xUnlock(p->pReal, eLock);
  149722. }
  149723. /*
  149724. ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
  149725. */
  149726. static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
  149727. rbu_file *p = (rbu_file *)pFile;
  149728. return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
  149729. }
  149730. /*
  149731. ** File control method. For custom operations on an rbuVfs-file.
  149732. */
  149733. static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
  149734. rbu_file *p = (rbu_file *)pFile;
  149735. int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
  149736. int rc;
  149737. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB)
  149738. || p->openFlags & (SQLITE_OPEN_TRANSIENT_DB|SQLITE_OPEN_TEMP_JOURNAL)
  149739. );
  149740. if( op==SQLITE_FCNTL_RBU ){
  149741. sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
  149742. /* First try to find another RBU vfs lower down in the vfs stack. If
  149743. ** one is found, this vfs will operate in pass-through mode. The lower
  149744. ** level vfs will do the special RBU handling. */
  149745. rc = xControl(p->pReal, op, pArg);
  149746. if( rc==SQLITE_NOTFOUND ){
  149747. /* Now search for a zipvfs instance lower down in the VFS stack. If
  149748. ** one is found, this is an error. */
  149749. void *dummy = 0;
  149750. rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
  149751. if( rc==SQLITE_OK ){
  149752. rc = SQLITE_ERROR;
  149753. pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
  149754. }else if( rc==SQLITE_NOTFOUND ){
  149755. pRbu->pTargetFd = p;
  149756. p->pRbu = pRbu;
  149757. if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
  149758. rc = SQLITE_OK;
  149759. }
  149760. }
  149761. return rc;
  149762. }
  149763. rc = xControl(p->pReal, op, pArg);
  149764. if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
  149765. rbu_vfs *pRbuVfs = p->pRbuVfs;
  149766. char *zIn = *(char**)pArg;
  149767. char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
  149768. *(char**)pArg = zOut;
  149769. if( zOut==0 ) rc = SQLITE_NOMEM;
  149770. }
  149771. return rc;
  149772. }
  149773. /*
  149774. ** Return the sector-size in bytes for an rbuVfs-file.
  149775. */
  149776. static int rbuVfsSectorSize(sqlite3_file *pFile){
  149777. rbu_file *p = (rbu_file *)pFile;
  149778. return p->pReal->pMethods->xSectorSize(p->pReal);
  149779. }
  149780. /*
  149781. ** Return the device characteristic flags supported by an rbuVfs-file.
  149782. */
  149783. static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
  149784. rbu_file *p = (rbu_file *)pFile;
  149785. return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
  149786. }
  149787. /*
  149788. ** Take or release a shared-memory lock.
  149789. */
  149790. static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
  149791. rbu_file *p = (rbu_file*)pFile;
  149792. sqlite3rbu *pRbu = p->pRbu;
  149793. int rc = SQLITE_OK;
  149794. #ifdef SQLITE_AMALGAMATION
  149795. assert( WAL_CKPT_LOCK==1 );
  149796. #endif
  149797. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  149798. if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
  149799. /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
  149800. ** taking this lock also prevents any checkpoints from occurring.
  149801. ** todo: really, it's not clear why this might occur, as
  149802. ** wal_autocheckpoint ought to be turned off. */
  149803. if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
  149804. }else{
  149805. int bCapture = 0;
  149806. if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
  149807. && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
  149808. && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
  149809. ){
  149810. bCapture = 1;
  149811. }
  149812. if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
  149813. rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
  149814. if( bCapture && rc==SQLITE_OK ){
  149815. pRbu->mLock |= (1 << ofst);
  149816. }
  149817. }
  149818. }
  149819. return rc;
  149820. }
  149821. /*
  149822. ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
  149823. */
  149824. static int rbuVfsShmMap(
  149825. sqlite3_file *pFile,
  149826. int iRegion,
  149827. int szRegion,
  149828. int isWrite,
  149829. void volatile **pp
  149830. ){
  149831. rbu_file *p = (rbu_file*)pFile;
  149832. int rc = SQLITE_OK;
  149833. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  149834. /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
  149835. ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
  149836. ** instead of a file on disk. */
  149837. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  149838. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  149839. if( iRegion<=p->nShm ){
  149840. int nByte = (iRegion+1) * sizeof(char*);
  149841. char **apNew = (char**)sqlite3_realloc(p->apShm, nByte);
  149842. if( apNew==0 ){
  149843. rc = SQLITE_NOMEM;
  149844. }else{
  149845. memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
  149846. p->apShm = apNew;
  149847. p->nShm = iRegion+1;
  149848. }
  149849. }
  149850. if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
  149851. char *pNew = (char*)sqlite3_malloc(szRegion);
  149852. if( pNew==0 ){
  149853. rc = SQLITE_NOMEM;
  149854. }else{
  149855. memset(pNew, 0, szRegion);
  149856. p->apShm[iRegion] = pNew;
  149857. }
  149858. }
  149859. if( rc==SQLITE_OK ){
  149860. *pp = p->apShm[iRegion];
  149861. }else{
  149862. *pp = 0;
  149863. }
  149864. }else{
  149865. assert( p->apShm==0 );
  149866. rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
  149867. }
  149868. return rc;
  149869. }
  149870. /*
  149871. ** Memory barrier.
  149872. */
  149873. static void rbuVfsShmBarrier(sqlite3_file *pFile){
  149874. rbu_file *p = (rbu_file *)pFile;
  149875. p->pReal->pMethods->xShmBarrier(p->pReal);
  149876. }
  149877. /*
  149878. ** The xShmUnmap method.
  149879. */
  149880. static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
  149881. rbu_file *p = (rbu_file*)pFile;
  149882. int rc = SQLITE_OK;
  149883. int eStage = (p->pRbu ? p->pRbu->eStage : 0);
  149884. assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
  149885. if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
  149886. /* no-op */
  149887. }else{
  149888. /* Release the checkpointer and writer locks */
  149889. rbuUnlockShm(p);
  149890. rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
  149891. }
  149892. return rc;
  149893. }
  149894. /*
  149895. ** Given that zWal points to a buffer containing a wal file name passed to
  149896. ** either the xOpen() or xAccess() VFS method, return a pointer to the
  149897. ** file-handle opened by the same database connection on the corresponding
  149898. ** database file.
  149899. */
  149900. static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
  149901. rbu_file *pDb;
  149902. sqlite3_mutex_enter(pRbuVfs->mutex);
  149903. for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext);
  149904. sqlite3_mutex_leave(pRbuVfs->mutex);
  149905. return pDb;
  149906. }
  149907. /*
  149908. ** Open an rbu file handle.
  149909. */
  149910. static int rbuVfsOpen(
  149911. sqlite3_vfs *pVfs,
  149912. const char *zName,
  149913. sqlite3_file *pFile,
  149914. int flags,
  149915. int *pOutFlags
  149916. ){
  149917. static sqlite3_io_methods rbuvfs_io_methods = {
  149918. 2, /* iVersion */
  149919. rbuVfsClose, /* xClose */
  149920. rbuVfsRead, /* xRead */
  149921. rbuVfsWrite, /* xWrite */
  149922. rbuVfsTruncate, /* xTruncate */
  149923. rbuVfsSync, /* xSync */
  149924. rbuVfsFileSize, /* xFileSize */
  149925. rbuVfsLock, /* xLock */
  149926. rbuVfsUnlock, /* xUnlock */
  149927. rbuVfsCheckReservedLock, /* xCheckReservedLock */
  149928. rbuVfsFileControl, /* xFileControl */
  149929. rbuVfsSectorSize, /* xSectorSize */
  149930. rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
  149931. rbuVfsShmMap, /* xShmMap */
  149932. rbuVfsShmLock, /* xShmLock */
  149933. rbuVfsShmBarrier, /* xShmBarrier */
  149934. rbuVfsShmUnmap /* xShmUnmap */
  149935. };
  149936. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  149937. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  149938. rbu_file *pFd = (rbu_file *)pFile;
  149939. int rc = SQLITE_OK;
  149940. const char *zOpen = zName;
  149941. memset(pFd, 0, sizeof(rbu_file));
  149942. pFd->pReal = (sqlite3_file*)&pFd[1];
  149943. pFd->pRbuVfs = pRbuVfs;
  149944. pFd->openFlags = flags;
  149945. if( zName ){
  149946. if( flags & SQLITE_OPEN_MAIN_DB ){
  149947. /* A main database has just been opened. The following block sets
  149948. ** (pFd->zWal) to point to a buffer owned by SQLite that contains
  149949. ** the name of the *-wal file this db connection will use. SQLite
  149950. ** happens to pass a pointer to this buffer when using xAccess()
  149951. ** or xOpen() to operate on the *-wal file. */
  149952. int n = strlen(zName);
  149953. const char *z = &zName[n];
  149954. if( flags & SQLITE_OPEN_URI ){
  149955. int odd = 0;
  149956. while( 1 ){
  149957. if( z[0]==0 ){
  149958. odd = 1 - odd;
  149959. if( odd && z[1]==0 ) break;
  149960. }
  149961. z++;
  149962. }
  149963. z += 2;
  149964. }else{
  149965. while( *z==0 ) z++;
  149966. }
  149967. z += (n + 8 + 1);
  149968. pFd->zWal = z;
  149969. }
  149970. else if( flags & SQLITE_OPEN_WAL ){
  149971. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
  149972. if( pDb ){
  149973. if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  149974. /* This call is to open a *-wal file. Intead, open the *-oal. This
  149975. ** code ensures that the string passed to xOpen() is terminated by a
  149976. ** pair of '\0' bytes in case the VFS attempts to extract a URI
  149977. ** parameter from it. */
  149978. int nCopy = strlen(zName);
  149979. char *zCopy = sqlite3_malloc(nCopy+2);
  149980. if( zCopy ){
  149981. memcpy(zCopy, zName, nCopy);
  149982. zCopy[nCopy-3] = 'o';
  149983. zCopy[nCopy] = '\0';
  149984. zCopy[nCopy+1] = '\0';
  149985. zOpen = (const char*)(pFd->zDel = zCopy);
  149986. }else{
  149987. rc = SQLITE_NOMEM;
  149988. }
  149989. pFd->pRbu = pDb->pRbu;
  149990. }
  149991. pDb->pWalFd = pFd;
  149992. }
  149993. }
  149994. }
  149995. if( rc==SQLITE_OK ){
  149996. rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, flags, pOutFlags);
  149997. }
  149998. if( pFd->pReal->pMethods ){
  149999. /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
  150000. ** pointer and, if the file is a main database file, link it into the
  150001. ** mutex protected linked list of all such files. */
  150002. pFile->pMethods = &rbuvfs_io_methods;
  150003. if( flags & SQLITE_OPEN_MAIN_DB ){
  150004. sqlite3_mutex_enter(pRbuVfs->mutex);
  150005. pFd->pMainNext = pRbuVfs->pMain;
  150006. pRbuVfs->pMain = pFd;
  150007. sqlite3_mutex_leave(pRbuVfs->mutex);
  150008. }
  150009. }else{
  150010. sqlite3_free(pFd->zDel);
  150011. }
  150012. return rc;
  150013. }
  150014. /*
  150015. ** Delete the file located at zPath.
  150016. */
  150017. static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  150018. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150019. return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
  150020. }
  150021. /*
  150022. ** Test for access permissions. Return true if the requested permission
  150023. ** is available, or false otherwise.
  150024. */
  150025. static int rbuVfsAccess(
  150026. sqlite3_vfs *pVfs,
  150027. const char *zPath,
  150028. int flags,
  150029. int *pResOut
  150030. ){
  150031. rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
  150032. sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
  150033. int rc;
  150034. rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
  150035. /* If this call is to check if a *-wal file associated with an RBU target
  150036. ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
  150037. ** the following special handling is activated:
  150038. **
  150039. ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
  150040. ** ensures that the RBU extension never tries to update a database
  150041. ** in wal mode, even if the first page of the database file has
  150042. ** been damaged.
  150043. **
  150044. ** b) if the *-wal file does not exist, claim that it does anyway,
  150045. ** causing SQLite to call xOpen() to open it. This call will also
  150046. ** be intercepted (see the rbuVfsOpen() function) and the *-oal
  150047. ** file opened instead.
  150048. */
  150049. if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
  150050. rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
  150051. if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
  150052. if( *pResOut ){
  150053. rc = SQLITE_CANTOPEN;
  150054. }else{
  150055. *pResOut = 1;
  150056. }
  150057. }
  150058. }
  150059. return rc;
  150060. }
  150061. /*
  150062. ** Populate buffer zOut with the full canonical pathname corresponding
  150063. ** to the pathname in zPath. zOut is guaranteed to point to a buffer
  150064. ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
  150065. */
  150066. static int rbuVfsFullPathname(
  150067. sqlite3_vfs *pVfs,
  150068. const char *zPath,
  150069. int nOut,
  150070. char *zOut
  150071. ){
  150072. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150073. return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
  150074. }
  150075. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  150076. /*
  150077. ** Open the dynamic library located at zPath and return a handle.
  150078. */
  150079. static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  150080. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150081. return pRealVfs->xDlOpen(pRealVfs, zPath);
  150082. }
  150083. /*
  150084. ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
  150085. ** utf-8 string describing the most recent error encountered associated
  150086. ** with dynamic libraries.
  150087. */
  150088. static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
  150089. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150090. pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
  150091. }
  150092. /*
  150093. ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
  150094. */
  150095. static void (*rbuVfsDlSym(
  150096. sqlite3_vfs *pVfs,
  150097. void *pArg,
  150098. const char *zSym
  150099. ))(void){
  150100. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150101. return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
  150102. }
  150103. /*
  150104. ** Close the dynamic library handle pHandle.
  150105. */
  150106. static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  150107. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150108. pRealVfs->xDlClose(pRealVfs, pHandle);
  150109. }
  150110. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  150111. /*
  150112. ** Populate the buffer pointed to by zBufOut with nByte bytes of
  150113. ** random data.
  150114. */
  150115. static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  150116. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150117. return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
  150118. }
  150119. /*
  150120. ** Sleep for nMicro microseconds. Return the number of microseconds
  150121. ** actually slept.
  150122. */
  150123. static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
  150124. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150125. return pRealVfs->xSleep(pRealVfs, nMicro);
  150126. }
  150127. /*
  150128. ** Return the current time as a Julian Day number in *pTimeOut.
  150129. */
  150130. static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
  150131. sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
  150132. return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
  150133. }
  150134. /*
  150135. ** No-op.
  150136. */
  150137. static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
  150138. return 0;
  150139. }
  150140. /*
  150141. ** Deregister and destroy an RBU vfs created by an earlier call to
  150142. ** sqlite3rbu_create_vfs().
  150143. */
  150144. SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
  150145. sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
  150146. if( pVfs && pVfs->xOpen==rbuVfsOpen ){
  150147. sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
  150148. sqlite3_vfs_unregister(pVfs);
  150149. sqlite3_free(pVfs);
  150150. }
  150151. }
  150152. /*
  150153. ** Create an RBU VFS named zName that accesses the underlying file-system
  150154. ** via existing VFS zParent. The new object is registered as a non-default
  150155. ** VFS with SQLite before returning.
  150156. */
  150157. SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
  150158. /* Template for VFS */
  150159. static sqlite3_vfs vfs_template = {
  150160. 1, /* iVersion */
  150161. 0, /* szOsFile */
  150162. 0, /* mxPathname */
  150163. 0, /* pNext */
  150164. 0, /* zName */
  150165. 0, /* pAppData */
  150166. rbuVfsOpen, /* xOpen */
  150167. rbuVfsDelete, /* xDelete */
  150168. rbuVfsAccess, /* xAccess */
  150169. rbuVfsFullPathname, /* xFullPathname */
  150170. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  150171. rbuVfsDlOpen, /* xDlOpen */
  150172. rbuVfsDlError, /* xDlError */
  150173. rbuVfsDlSym, /* xDlSym */
  150174. rbuVfsDlClose, /* xDlClose */
  150175. #else
  150176. 0, 0, 0, 0,
  150177. #endif
  150178. rbuVfsRandomness, /* xRandomness */
  150179. rbuVfsSleep, /* xSleep */
  150180. rbuVfsCurrentTime, /* xCurrentTime */
  150181. rbuVfsGetLastError, /* xGetLastError */
  150182. 0, /* xCurrentTimeInt64 (version 2) */
  150183. 0, 0, 0 /* Unimplemented version 3 methods */
  150184. };
  150185. rbu_vfs *pNew = 0; /* Newly allocated VFS */
  150186. int nName;
  150187. int rc = SQLITE_OK;
  150188. int nByte;
  150189. nName = strlen(zName);
  150190. nByte = sizeof(rbu_vfs) + nName + 1;
  150191. pNew = (rbu_vfs*)sqlite3_malloc(nByte);
  150192. if( pNew==0 ){
  150193. rc = SQLITE_NOMEM;
  150194. }else{
  150195. sqlite3_vfs *pParent; /* Parent VFS */
  150196. memset(pNew, 0, nByte);
  150197. pParent = sqlite3_vfs_find(zParent);
  150198. if( pParent==0 ){
  150199. rc = SQLITE_NOTFOUND;
  150200. }else{
  150201. char *zSpace;
  150202. memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
  150203. pNew->base.mxPathname = pParent->mxPathname;
  150204. pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
  150205. pNew->pRealVfs = pParent;
  150206. pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
  150207. memcpy(zSpace, zName, nName);
  150208. /* Allocate the mutex and register the new VFS (not as the default) */
  150209. pNew->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_RECURSIVE);
  150210. if( pNew->mutex==0 ){
  150211. rc = SQLITE_NOMEM;
  150212. }else{
  150213. rc = sqlite3_vfs_register(&pNew->base, 0);
  150214. }
  150215. }
  150216. if( rc!=SQLITE_OK ){
  150217. sqlite3_mutex_free(pNew->mutex);
  150218. sqlite3_free(pNew);
  150219. }
  150220. }
  150221. return rc;
  150222. }
  150223. /**************************************************************************/
  150224. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
  150225. /************** End of sqlite3rbu.c ******************************************/
  150226. /************** Begin file dbstat.c ******************************************/
  150227. /*
  150228. ** 2010 July 12
  150229. **
  150230. ** The author disclaims copyright to this source code. In place of
  150231. ** a legal notice, here is a blessing:
  150232. **
  150233. ** May you do good and not evil.
  150234. ** May you find forgiveness for yourself and forgive others.
  150235. ** May you share freely, never taking more than you give.
  150236. **
  150237. ******************************************************************************
  150238. **
  150239. ** This file contains an implementation of the "dbstat" virtual table.
  150240. **
  150241. ** The dbstat virtual table is used to extract low-level formatting
  150242. ** information from an SQLite database in order to implement the
  150243. ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
  150244. ** for an example implementation.
  150245. */
  150246. /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
  150247. #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
  150248. && !defined(SQLITE_OMIT_VIRTUALTABLE)
  150249. /*
  150250. ** Page paths:
  150251. **
  150252. ** The value of the 'path' column describes the path taken from the
  150253. ** root-node of the b-tree structure to each page. The value of the
  150254. ** root-node path is '/'.
  150255. **
  150256. ** The value of the path for the left-most child page of the root of
  150257. ** a b-tree is '/000/'. (Btrees store content ordered from left to right
  150258. ** so the pages to the left have smaller keys than the pages to the right.)
  150259. ** The next to left-most child of the root page is
  150260. ** '/001', and so on, each sibling page identified by a 3-digit hex
  150261. ** value. The children of the 451st left-most sibling have paths such
  150262. ** as '/1c2/000/, '/1c2/001/' etc.
  150263. **
  150264. ** Overflow pages are specified by appending a '+' character and a
  150265. ** six-digit hexadecimal value to the path to the cell they are linked
  150266. ** from. For example, the three overflow pages in a chain linked from
  150267. ** the left-most cell of the 450th child of the root page are identified
  150268. ** by the paths:
  150269. **
  150270. ** '/1c2/000+000000' // First page in overflow chain
  150271. ** '/1c2/000+000001' // Second page in overflow chain
  150272. ** '/1c2/000+000002' // Third page in overflow chain
  150273. **
  150274. ** If the paths are sorted using the BINARY collation sequence, then
  150275. ** the overflow pages associated with a cell will appear earlier in the
  150276. ** sort-order than its child page:
  150277. **
  150278. ** '/1c2/000/' // Left-most child of 451st child of root
  150279. */
  150280. #define VTAB_SCHEMA \
  150281. "CREATE TABLE xx( " \
  150282. " name STRING, /* Name of table or index */" \
  150283. " path INTEGER, /* Path to page from root */" \
  150284. " pageno INTEGER, /* Page number */" \
  150285. " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \
  150286. " ncell INTEGER, /* Cells on page (0 for overflow) */" \
  150287. " payload INTEGER, /* Bytes of payload on this page */" \
  150288. " unused INTEGER, /* Bytes of unused space on this page */" \
  150289. " mx_payload INTEGER, /* Largest payload size of all cells */" \
  150290. " pgoffset INTEGER, /* Offset of page in file */" \
  150291. " pgsize INTEGER /* Size of the page */" \
  150292. ");"
  150293. typedef struct StatTable StatTable;
  150294. typedef struct StatCursor StatCursor;
  150295. typedef struct StatPage StatPage;
  150296. typedef struct StatCell StatCell;
  150297. struct StatCell {
  150298. int nLocal; /* Bytes of local payload */
  150299. u32 iChildPg; /* Child node (or 0 if this is a leaf) */
  150300. int nOvfl; /* Entries in aOvfl[] */
  150301. u32 *aOvfl; /* Array of overflow page numbers */
  150302. int nLastOvfl; /* Bytes of payload on final overflow page */
  150303. int iOvfl; /* Iterates through aOvfl[] */
  150304. };
  150305. struct StatPage {
  150306. u32 iPgno;
  150307. DbPage *pPg;
  150308. int iCell;
  150309. char *zPath; /* Path to this page */
  150310. /* Variables populated by statDecodePage(): */
  150311. u8 flags; /* Copy of flags byte */
  150312. int nCell; /* Number of cells on page */
  150313. int nUnused; /* Number of unused bytes on page */
  150314. StatCell *aCell; /* Array of parsed cells */
  150315. u32 iRightChildPg; /* Right-child page number (or 0) */
  150316. int nMxPayload; /* Largest payload of any cell on this page */
  150317. };
  150318. struct StatCursor {
  150319. sqlite3_vtab_cursor base;
  150320. sqlite3_stmt *pStmt; /* Iterates through set of root pages */
  150321. int isEof; /* After pStmt has returned SQLITE_DONE */
  150322. StatPage aPage[32];
  150323. int iPage; /* Current entry in aPage[] */
  150324. /* Values to return. */
  150325. char *zName; /* Value of 'name' column */
  150326. char *zPath; /* Value of 'path' column */
  150327. u32 iPageno; /* Value of 'pageno' column */
  150328. char *zPagetype; /* Value of 'pagetype' column */
  150329. int nCell; /* Value of 'ncell' column */
  150330. int nPayload; /* Value of 'payload' column */
  150331. int nUnused; /* Value of 'unused' column */
  150332. int nMxPayload; /* Value of 'mx_payload' column */
  150333. i64 iOffset; /* Value of 'pgOffset' column */
  150334. int szPage; /* Value of 'pgSize' column */
  150335. };
  150336. struct StatTable {
  150337. sqlite3_vtab base;
  150338. sqlite3 *db;
  150339. int iDb; /* Index of database to analyze */
  150340. };
  150341. #ifndef get2byte
  150342. # define get2byte(x) ((x)[0]<<8 | (x)[1])
  150343. #endif
  150344. /*
  150345. ** Connect to or create a statvfs virtual table.
  150346. */
  150347. static int statConnect(
  150348. sqlite3 *db,
  150349. void *pAux,
  150350. int argc, const char *const*argv,
  150351. sqlite3_vtab **ppVtab,
  150352. char **pzErr
  150353. ){
  150354. StatTable *pTab = 0;
  150355. int rc = SQLITE_OK;
  150356. int iDb;
  150357. if( argc>=4 ){
  150358. iDb = sqlite3FindDbName(db, argv[3]);
  150359. if( iDb<0 ){
  150360. *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
  150361. return SQLITE_ERROR;
  150362. }
  150363. }else{
  150364. iDb = 0;
  150365. }
  150366. rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
  150367. if( rc==SQLITE_OK ){
  150368. pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
  150369. if( pTab==0 ) rc = SQLITE_NOMEM;
  150370. }
  150371. assert( rc==SQLITE_OK || pTab==0 );
  150372. if( rc==SQLITE_OK ){
  150373. memset(pTab, 0, sizeof(StatTable));
  150374. pTab->db = db;
  150375. pTab->iDb = iDb;
  150376. }
  150377. *ppVtab = (sqlite3_vtab*)pTab;
  150378. return rc;
  150379. }
  150380. /*
  150381. ** Disconnect from or destroy a statvfs virtual table.
  150382. */
  150383. static int statDisconnect(sqlite3_vtab *pVtab){
  150384. sqlite3_free(pVtab);
  150385. return SQLITE_OK;
  150386. }
  150387. /*
  150388. ** There is no "best-index". This virtual table always does a linear
  150389. ** scan of the binary VFS log file.
  150390. */
  150391. static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  150392. /* Records are always returned in ascending order of (name, path).
  150393. ** If this will satisfy the client, set the orderByConsumed flag so that
  150394. ** SQLite does not do an external sort.
  150395. */
  150396. if( ( pIdxInfo->nOrderBy==1
  150397. && pIdxInfo->aOrderBy[0].iColumn==0
  150398. && pIdxInfo->aOrderBy[0].desc==0
  150399. ) ||
  150400. ( pIdxInfo->nOrderBy==2
  150401. && pIdxInfo->aOrderBy[0].iColumn==0
  150402. && pIdxInfo->aOrderBy[0].desc==0
  150403. && pIdxInfo->aOrderBy[1].iColumn==1
  150404. && pIdxInfo->aOrderBy[1].desc==0
  150405. )
  150406. ){
  150407. pIdxInfo->orderByConsumed = 1;
  150408. }
  150409. pIdxInfo->estimatedCost = 10.0;
  150410. return SQLITE_OK;
  150411. }
  150412. /*
  150413. ** Open a new statvfs cursor.
  150414. */
  150415. static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  150416. StatTable *pTab = (StatTable *)pVTab;
  150417. StatCursor *pCsr;
  150418. int rc;
  150419. pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
  150420. if( pCsr==0 ){
  150421. rc = SQLITE_NOMEM;
  150422. }else{
  150423. char *zSql;
  150424. memset(pCsr, 0, sizeof(StatCursor));
  150425. pCsr->base.pVtab = pVTab;
  150426. zSql = sqlite3_mprintf(
  150427. "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
  150428. " UNION ALL "
  150429. "SELECT name, rootpage, type"
  150430. " FROM \"%w\".sqlite_master WHERE rootpage!=0"
  150431. " ORDER BY name", pTab->db->aDb[pTab->iDb].zName);
  150432. if( zSql==0 ){
  150433. rc = SQLITE_NOMEM;
  150434. }else{
  150435. rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
  150436. sqlite3_free(zSql);
  150437. }
  150438. if( rc!=SQLITE_OK ){
  150439. sqlite3_free(pCsr);
  150440. pCsr = 0;
  150441. }
  150442. }
  150443. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  150444. return rc;
  150445. }
  150446. static void statClearPage(StatPage *p){
  150447. int i;
  150448. if( p->aCell ){
  150449. for(i=0; i<p->nCell; i++){
  150450. sqlite3_free(p->aCell[i].aOvfl);
  150451. }
  150452. sqlite3_free(p->aCell);
  150453. }
  150454. sqlite3PagerUnref(p->pPg);
  150455. sqlite3_free(p->zPath);
  150456. memset(p, 0, sizeof(StatPage));
  150457. }
  150458. static void statResetCsr(StatCursor *pCsr){
  150459. int i;
  150460. sqlite3_reset(pCsr->pStmt);
  150461. for(i=0; i<ArraySize(pCsr->aPage); i++){
  150462. statClearPage(&pCsr->aPage[i]);
  150463. }
  150464. pCsr->iPage = 0;
  150465. sqlite3_free(pCsr->zPath);
  150466. pCsr->zPath = 0;
  150467. }
  150468. /*
  150469. ** Close a statvfs cursor.
  150470. */
  150471. static int statClose(sqlite3_vtab_cursor *pCursor){
  150472. StatCursor *pCsr = (StatCursor *)pCursor;
  150473. statResetCsr(pCsr);
  150474. sqlite3_finalize(pCsr->pStmt);
  150475. sqlite3_free(pCsr);
  150476. return SQLITE_OK;
  150477. }
  150478. static void getLocalPayload(
  150479. int nUsable, /* Usable bytes per page */
  150480. u8 flags, /* Page flags */
  150481. int nTotal, /* Total record (payload) size */
  150482. int *pnLocal /* OUT: Bytes stored locally */
  150483. ){
  150484. int nLocal;
  150485. int nMinLocal;
  150486. int nMaxLocal;
  150487. if( flags==0x0D ){ /* Table leaf node */
  150488. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  150489. nMaxLocal = nUsable - 35;
  150490. }else{ /* Index interior and leaf nodes */
  150491. nMinLocal = (nUsable - 12) * 32 / 255 - 23;
  150492. nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
  150493. }
  150494. nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
  150495. if( nLocal>nMaxLocal ) nLocal = nMinLocal;
  150496. *pnLocal = nLocal;
  150497. }
  150498. static int statDecodePage(Btree *pBt, StatPage *p){
  150499. int nUnused;
  150500. int iOff;
  150501. int nHdr;
  150502. int isLeaf;
  150503. int szPage;
  150504. u8 *aData = sqlite3PagerGetData(p->pPg);
  150505. u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
  150506. p->flags = aHdr[0];
  150507. p->nCell = get2byte(&aHdr[3]);
  150508. p->nMxPayload = 0;
  150509. isLeaf = (p->flags==0x0A || p->flags==0x0D);
  150510. nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
  150511. nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
  150512. nUnused += (int)aHdr[7];
  150513. iOff = get2byte(&aHdr[1]);
  150514. while( iOff ){
  150515. nUnused += get2byte(&aData[iOff+2]);
  150516. iOff = get2byte(&aData[iOff]);
  150517. }
  150518. p->nUnused = nUnused;
  150519. p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
  150520. szPage = sqlite3BtreeGetPageSize(pBt);
  150521. if( p->nCell ){
  150522. int i; /* Used to iterate through cells */
  150523. int nUsable; /* Usable bytes per page */
  150524. sqlite3BtreeEnter(pBt);
  150525. nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
  150526. sqlite3BtreeLeave(pBt);
  150527. p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
  150528. if( p->aCell==0 ) return SQLITE_NOMEM;
  150529. memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
  150530. for(i=0; i<p->nCell; i++){
  150531. StatCell *pCell = &p->aCell[i];
  150532. iOff = get2byte(&aData[nHdr+i*2]);
  150533. if( !isLeaf ){
  150534. pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
  150535. iOff += 4;
  150536. }
  150537. if( p->flags==0x05 ){
  150538. /* A table interior node. nPayload==0. */
  150539. }else{
  150540. u32 nPayload; /* Bytes of payload total (local+overflow) */
  150541. int nLocal; /* Bytes of payload stored locally */
  150542. iOff += getVarint32(&aData[iOff], nPayload);
  150543. if( p->flags==0x0D ){
  150544. u64 dummy;
  150545. iOff += sqlite3GetVarint(&aData[iOff], &dummy);
  150546. }
  150547. if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
  150548. getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
  150549. pCell->nLocal = nLocal;
  150550. assert( nLocal>=0 );
  150551. assert( nPayload>=(u32)nLocal );
  150552. assert( nLocal<=(nUsable-35) );
  150553. if( nPayload>(u32)nLocal ){
  150554. int j;
  150555. int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
  150556. pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
  150557. pCell->nOvfl = nOvfl;
  150558. pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
  150559. if( pCell->aOvfl==0 ) return SQLITE_NOMEM;
  150560. pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
  150561. for(j=1; j<nOvfl; j++){
  150562. int rc;
  150563. u32 iPrev = pCell->aOvfl[j-1];
  150564. DbPage *pPg = 0;
  150565. rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg);
  150566. if( rc!=SQLITE_OK ){
  150567. assert( pPg==0 );
  150568. return rc;
  150569. }
  150570. pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
  150571. sqlite3PagerUnref(pPg);
  150572. }
  150573. }
  150574. }
  150575. }
  150576. }
  150577. return SQLITE_OK;
  150578. }
  150579. /*
  150580. ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
  150581. ** the current value of pCsr->iPageno.
  150582. */
  150583. static void statSizeAndOffset(StatCursor *pCsr){
  150584. StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
  150585. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  150586. Pager *pPager = sqlite3BtreePager(pBt);
  150587. sqlite3_file *fd;
  150588. sqlite3_int64 x[2];
  150589. /* The default page size and offset */
  150590. pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
  150591. pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
  150592. /* If connected to a ZIPVFS backend, override the page size and
  150593. ** offset with actual values obtained from ZIPVFS.
  150594. */
  150595. fd = sqlite3PagerFile(pPager);
  150596. x[0] = pCsr->iPageno;
  150597. if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
  150598. pCsr->iOffset = x[0];
  150599. pCsr->szPage = (int)x[1];
  150600. }
  150601. }
  150602. /*
  150603. ** Move a statvfs cursor to the next entry in the file.
  150604. */
  150605. static int statNext(sqlite3_vtab_cursor *pCursor){
  150606. int rc;
  150607. int nPayload;
  150608. char *z;
  150609. StatCursor *pCsr = (StatCursor *)pCursor;
  150610. StatTable *pTab = (StatTable *)pCursor->pVtab;
  150611. Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
  150612. Pager *pPager = sqlite3BtreePager(pBt);
  150613. sqlite3_free(pCsr->zPath);
  150614. pCsr->zPath = 0;
  150615. statNextRestart:
  150616. if( pCsr->aPage[0].pPg==0 ){
  150617. rc = sqlite3_step(pCsr->pStmt);
  150618. if( rc==SQLITE_ROW ){
  150619. int nPage;
  150620. u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
  150621. sqlite3PagerPagecount(pPager, &nPage);
  150622. if( nPage==0 ){
  150623. pCsr->isEof = 1;
  150624. return sqlite3_reset(pCsr->pStmt);
  150625. }
  150626. rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg);
  150627. pCsr->aPage[0].iPgno = iRoot;
  150628. pCsr->aPage[0].iCell = 0;
  150629. pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
  150630. pCsr->iPage = 0;
  150631. if( z==0 ) rc = SQLITE_NOMEM;
  150632. }else{
  150633. pCsr->isEof = 1;
  150634. return sqlite3_reset(pCsr->pStmt);
  150635. }
  150636. }else{
  150637. /* Page p itself has already been visited. */
  150638. StatPage *p = &pCsr->aPage[pCsr->iPage];
  150639. while( p->iCell<p->nCell ){
  150640. StatCell *pCell = &p->aCell[p->iCell];
  150641. if( pCell->iOvfl<pCell->nOvfl ){
  150642. int nUsable;
  150643. sqlite3BtreeEnter(pBt);
  150644. nUsable = sqlite3BtreeGetPageSize(pBt) -
  150645. sqlite3BtreeGetReserveNoMutex(pBt);
  150646. sqlite3BtreeLeave(pBt);
  150647. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  150648. pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
  150649. pCsr->zPagetype = "overflow";
  150650. pCsr->nCell = 0;
  150651. pCsr->nMxPayload = 0;
  150652. pCsr->zPath = z = sqlite3_mprintf(
  150653. "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
  150654. );
  150655. if( pCell->iOvfl<pCell->nOvfl-1 ){
  150656. pCsr->nUnused = 0;
  150657. pCsr->nPayload = nUsable - 4;
  150658. }else{
  150659. pCsr->nPayload = pCell->nLastOvfl;
  150660. pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
  150661. }
  150662. pCell->iOvfl++;
  150663. statSizeAndOffset(pCsr);
  150664. return z==0 ? SQLITE_NOMEM : SQLITE_OK;
  150665. }
  150666. if( p->iRightChildPg ) break;
  150667. p->iCell++;
  150668. }
  150669. if( !p->iRightChildPg || p->iCell>p->nCell ){
  150670. statClearPage(p);
  150671. if( pCsr->iPage==0 ) return statNext(pCursor);
  150672. pCsr->iPage--;
  150673. goto statNextRestart; /* Tail recursion */
  150674. }
  150675. pCsr->iPage++;
  150676. assert( p==&pCsr->aPage[pCsr->iPage-1] );
  150677. if( p->iCell==p->nCell ){
  150678. p[1].iPgno = p->iRightChildPg;
  150679. }else{
  150680. p[1].iPgno = p->aCell[p->iCell].iChildPg;
  150681. }
  150682. rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg);
  150683. p[1].iCell = 0;
  150684. p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
  150685. p->iCell++;
  150686. if( z==0 ) rc = SQLITE_NOMEM;
  150687. }
  150688. /* Populate the StatCursor fields with the values to be returned
  150689. ** by the xColumn() and xRowid() methods.
  150690. */
  150691. if( rc==SQLITE_OK ){
  150692. int i;
  150693. StatPage *p = &pCsr->aPage[pCsr->iPage];
  150694. pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
  150695. pCsr->iPageno = p->iPgno;
  150696. rc = statDecodePage(pBt, p);
  150697. if( rc==SQLITE_OK ){
  150698. statSizeAndOffset(pCsr);
  150699. switch( p->flags ){
  150700. case 0x05: /* table internal */
  150701. case 0x02: /* index internal */
  150702. pCsr->zPagetype = "internal";
  150703. break;
  150704. case 0x0D: /* table leaf */
  150705. case 0x0A: /* index leaf */
  150706. pCsr->zPagetype = "leaf";
  150707. break;
  150708. default:
  150709. pCsr->zPagetype = "corrupted";
  150710. break;
  150711. }
  150712. pCsr->nCell = p->nCell;
  150713. pCsr->nUnused = p->nUnused;
  150714. pCsr->nMxPayload = p->nMxPayload;
  150715. pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
  150716. if( z==0 ) rc = SQLITE_NOMEM;
  150717. nPayload = 0;
  150718. for(i=0; i<p->nCell; i++){
  150719. nPayload += p->aCell[i].nLocal;
  150720. }
  150721. pCsr->nPayload = nPayload;
  150722. }
  150723. }
  150724. return rc;
  150725. }
  150726. static int statEof(sqlite3_vtab_cursor *pCursor){
  150727. StatCursor *pCsr = (StatCursor *)pCursor;
  150728. return pCsr->isEof;
  150729. }
  150730. static int statFilter(
  150731. sqlite3_vtab_cursor *pCursor,
  150732. int idxNum, const char *idxStr,
  150733. int argc, sqlite3_value **argv
  150734. ){
  150735. StatCursor *pCsr = (StatCursor *)pCursor;
  150736. statResetCsr(pCsr);
  150737. return statNext(pCursor);
  150738. }
  150739. static int statColumn(
  150740. sqlite3_vtab_cursor *pCursor,
  150741. sqlite3_context *ctx,
  150742. int i
  150743. ){
  150744. StatCursor *pCsr = (StatCursor *)pCursor;
  150745. switch( i ){
  150746. case 0: /* name */
  150747. sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
  150748. break;
  150749. case 1: /* path */
  150750. sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
  150751. break;
  150752. case 2: /* pageno */
  150753. sqlite3_result_int64(ctx, pCsr->iPageno);
  150754. break;
  150755. case 3: /* pagetype */
  150756. sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
  150757. break;
  150758. case 4: /* ncell */
  150759. sqlite3_result_int(ctx, pCsr->nCell);
  150760. break;
  150761. case 5: /* payload */
  150762. sqlite3_result_int(ctx, pCsr->nPayload);
  150763. break;
  150764. case 6: /* unused */
  150765. sqlite3_result_int(ctx, pCsr->nUnused);
  150766. break;
  150767. case 7: /* mx_payload */
  150768. sqlite3_result_int(ctx, pCsr->nMxPayload);
  150769. break;
  150770. case 8: /* pgoffset */
  150771. sqlite3_result_int64(ctx, pCsr->iOffset);
  150772. break;
  150773. default: /* pgsize */
  150774. assert( i==9 );
  150775. sqlite3_result_int(ctx, pCsr->szPage);
  150776. break;
  150777. }
  150778. return SQLITE_OK;
  150779. }
  150780. static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  150781. StatCursor *pCsr = (StatCursor *)pCursor;
  150782. *pRowid = pCsr->iPageno;
  150783. return SQLITE_OK;
  150784. }
  150785. /*
  150786. ** Invoke this routine to register the "dbstat" virtual table module
  150787. */
  150788. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
  150789. static sqlite3_module dbstat_module = {
  150790. 0, /* iVersion */
  150791. statConnect, /* xCreate */
  150792. statConnect, /* xConnect */
  150793. statBestIndex, /* xBestIndex */
  150794. statDisconnect, /* xDisconnect */
  150795. statDisconnect, /* xDestroy */
  150796. statOpen, /* xOpen - open a cursor */
  150797. statClose, /* xClose - close a cursor */
  150798. statFilter, /* xFilter - configure scan constraints */
  150799. statNext, /* xNext - advance a cursor */
  150800. statEof, /* xEof - check for end of scan */
  150801. statColumn, /* xColumn - read data */
  150802. statRowid, /* xRowid - read data */
  150803. 0, /* xUpdate */
  150804. 0, /* xBegin */
  150805. 0, /* xSync */
  150806. 0, /* xCommit */
  150807. 0, /* xRollback */
  150808. 0, /* xFindMethod */
  150809. 0, /* xRename */
  150810. };
  150811. return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
  150812. }
  150813. #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
  150814. SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
  150815. #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
  150816. /************** End of dbstat.c **********************************************/